text string | size int64 | token_count int64 |
|---|---|---|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/connect/model/UpdateInstanceAttributeRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Connect::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
UpdateInstanceAttributeRequest::UpdateInstanceAttributeRequest() :
m_instanceIdHasBeenSet(false),
m_attributeType(InstanceAttributeType::NOT_SET),
m_attributeTypeHasBeenSet(false),
m_valueHasBeenSet(false)
{
}
Aws::String UpdateInstanceAttributeRequest::SerializePayload() const
{
JsonValue payload;
if(m_valueHasBeenSet)
{
payload.WithString("Value", m_value);
}
return payload.View().WriteReadable();
}
| 794 | 264 |
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#ifndef AZ_UNITY_BUILD
#include <AzCore/Debug/StackTracer.h>
#if defined(AZ_PLATFORM_WINDOWS)
# include <AzCore/Debug/StackTracerWinCpp.inl>
#elif defined(AZ_PLATFORM_X360)
# include <AzCore/Debug/StackTracerX360Cpp.inl>
#elif defined(AZ_PLATFORM_WII)
# include <AzCore/Debug/StackTracerWiiCpp.inl>
#elif defined(AZ_PLATFORM_LINUX) || defined(AZ_PLATFORM_APPLE)
# include <AzCore/Debug/StackTracerLinux.inl>
#else // DEFAULT NOT STACK TRACE SUPPORT
#if defined(AZ_PLATFORM_XBONE) || defined(AZ_PLATFORM_PS4) || defined(AZ_PLATFORM_ANDROID)
/* NOTE: Android has not official support, but there are solutions for different versions like
https://android.googlesource.com/platform/system/core/+/kitkat-dev/libutils/CallStack.cpp for KitKat
Add an implementation when we establish the supported versions!*/
#pragma message("--- No stack trace support ---")
#pragma message("--- Implement it ---")
#endif
// By default callstack tracing is not supported.
using namespace AZ;
using namespace AZ::Debug;
unsigned int StackRecorder::Record(StackFrame*, unsigned int, unsigned int, void*) { return false; }
void SymbolStorage::LoadModuleData(const void*, unsigned int) {}
unsigned int SymbolStorage::GetModuleInfoDataSize() { return 0; }
void SymbolStorage::StoreModuleInfoData(void*, unsigned int) {}
unsigned int SymbolStorage::GetNumLoadedModules() { return 0; }
const SymbolStorage::ModuleInfo* SymbolStorage::GetModuleInfo(unsigned int) { return 0; }
void SymbolStorage::RegisterModuleListeners() {}
void SymbolStorage::UnregisterModuleListeners() {}
void SymbolStorage::SetMapFilename(const char*) {}
const char* SymbolStorage::GetMapFilename() { return 0; }
void SymbolStorage::DecodeFrames(const StackFrame*, unsigned int, StackLine*) {}
#endif
#endif // #ifndef AZ_UNITY_BUILD
| 2,423 | 762 |
/*################################################################################
##
## Copyright (C) 2011-2021 Keith O'Hara
##
## This file is part of the StatsLib C++ library.
##
## 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.
##
################################################################################*/
/*
* cdf of the univariate log-normal distribution
*/
//
// single input
namespace internal
{
template<typename T>
statslib_constexpr
T
plnorm_vals_check(const T x, const T mu_par, const T sigma_par, const bool log_form)
{
return( !lnorm_sanity_check(x,mu_par,sigma_par) ? \
STLIM<T>::quiet_NaN() :
//
STLIM<T>::epsilon() > x ? \
log_zero_if<T>(log_form) :
//
pnorm(stmath::log(x),mu_par,sigma_par,log_form) );
}
template<typename T1, typename T2, typename T3, typename TC = common_return_t<T1,T2,T3>>
statslib_constexpr
TC
plnorm_type_check(const T1 x, const T2 mu_par, const T3 sigma_par, const bool log_form)
noexcept
{
return plnorm_vals_check(static_cast<TC>(x),static_cast<TC>(mu_par),
static_cast<TC>(sigma_par),log_form);
}
}
/**
* @brief Distribution function of the Log-Normal distribution
*
* @param x a real-valued input.
* @param mu_par the mean parameter, a real-valued input.
* @param sigma_par the standard deviation parameter, a real-valued input.
* @param log_form return the log-probability or the true form.
*
* @return the cumulative distribution function evaluated at \c x.
*
* Example:
* \code{.cpp} stats::plnorm(2.0,1.0,2.0,false); \endcode
*/
template<typename T1, typename T2, typename T3>
statslib_constexpr
common_return_t<T1,T2,T3>
plnorm(const T1 x, const T2 mu_par, const T3 sigma_par, const bool log_form)
noexcept
{
return internal::plnorm_type_check(x,mu_par,sigma_par,log_form);
}
//
// vector/matrix input
namespace internal
{
#ifdef STATS_ENABLE_INTERNAL_VEC_FEATURES
template<typename eT, typename T1, typename T2, typename rT>
statslib_inline
void
plnorm_vec(const eT* __stats_pointer_settings__ vals_in, const T1 mu_par, const T2 sigma_par, const bool log_form,
rT* __stats_pointer_settings__ vals_out, const ullint_t num_elem)
{
EVAL_DIST_FN_VEC(plnorm,vals_in,vals_out,num_elem,mu_par,sigma_par,log_form);
}
#endif
}
/**
* @brief Distribution function of the Log-Normal distribution
*
* @param x a standard vector.
* @param mu_par the location parameter, a real-valued input.
* @param sigma_par the scale parameter, a real-valued input.
* @param log_form return the log-probability or the true form.
*
* @return a vector of CDF values corresponding to the elements of \c x.
*
* Example:
* \code{.cpp}
* std::vector<double> x = {0.0, 1.0, 2.0};
* stats::plnorm(x,1.0,2.0,false);
* \endcode
*/
#ifdef STATS_ENABLE_STDVEC_WRAPPERS
template<typename eT, typename T1, typename T2, typename rT>
statslib_inline
std::vector<rT>
plnorm(const std::vector<eT>& x, const T1 mu_par, const T2 sigma_par, const bool log_form)
{
STDVEC_DIST_FN(plnorm_vec,mu_par,sigma_par,log_form);
}
#endif
/**
* @brief Distribution function of the Log-Normal distribution
*
* @param X a matrix of input values.
* @param mu_par the location parameter, a real-valued input.
* @param sigma_par the scale parameter, a real-valued input.
* @param log_form return the log-probability or the true form.
*
* @return a matrix of CDF values corresponding to the elements of \c X.
*
* Example:
* \code{.cpp}
* arma::mat X = { {0.2, 1.7, 0.1},
* {0.9, 4.0, 0.3} };
* stats::plnorm(X,1.0,1.0,false);
* \endcode
*/
#ifdef STATS_ENABLE_ARMA_WRAPPERS
template<typename eT, typename T1, typename T2, typename rT>
statslib_inline
ArmaMat<rT>
plnorm(const ArmaMat<eT>& X, const T1 mu_par, const T2 sigma_par, const bool log_form)
{
ARMA_DIST_FN(plnorm_vec,mu_par,sigma_par,log_form);
}
template<typename mT, typename tT, typename T1, typename T2>
statslib_inline
mT
plnorm(const ArmaGen<mT,tT>& X, const T1 mu_par, const T2 sigma_par, const bool log_form)
{
return plnorm(X.eval(),mu_par,sigma_par,log_form);
}
#endif
/**
* @brief Distribution function of the Log-Normal distribution
*
* @param X a matrix of input values.
* @param mu_par the location parameter, a real-valued input.
* @param sigma_par the scale parameter, a real-valued input.
* @param log_form return the log-probability or the true form.
*
* @return a matrix of CDF values corresponding to the elements of \c X.
*
* Example:
* \code{.cpp}
* stats::plnorm(X,1.0,1.0,false);
* \endcode
*/
#ifdef STATS_ENABLE_BLAZE_WRAPPERS
template<typename eT, typename T1, typename T2, typename rT, bool To>
statslib_inline
BlazeMat<rT,To>
plnorm(const BlazeMat<eT,To>& X, const T1 mu_par, const T2 sigma_par, const bool log_form)
{
BLAZE_DIST_FN(plnorm_vec,mu_par,sigma_par,log_form);
}
#endif
/**
* @brief Distribution function of the Log-Normal distribution
*
* @param X a matrix of input values.
* @param mu_par the location parameter, a real-valued input.
* @param sigma_par the scale parameter, a real-valued input.
* @param log_form return the log-probability or the true form.
*
* @return a matrix of CDF values corresponding to the elements of \c X.
*
* Example:
* \code{.cpp}
* stats::plnorm(X,1.0,1.0,false);
* \endcode
*/
#ifdef STATS_ENABLE_EIGEN_WRAPPERS
template<typename eT, typename T1, typename T2, typename rT, int iTr, int iTc>
statslib_inline
EigenMat<rT,iTr,iTc>
plnorm(const EigenMat<eT,iTr,iTc>& X, const T1 mu_par, const T2 sigma_par, const bool log_form)
{
EIGEN_DIST_FN(plnorm_vec,mu_par,sigma_par,log_form);
}
#endif
| 6,253 | 2,272 |
/*
* Copyright (c) 2021 Arm Limited.
*
* SPDX-License-Identifier: MIT
*
* 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 <cstddef>
#include <cstdint>
#if defined(ARM_COMPUTE_ENABLE_SVE)
namespace arm_conv {
namespace depthwise {
void sve_fp32_nhwc_3x3_s1_output2x2_mla_depthfirst_impl(
const float *const *const input_ptrs,
float *const *const outptrs,
const void *params,
unsigned int n_channels,
const float activation_min,
const float activation_max
)
{
const float *const inptrs[16] = {
input_ptrs[0], input_ptrs[1], input_ptrs[4], input_ptrs[5], input_ptrs[2], input_ptrs[6], input_ptrs[3], input_ptrs[7], input_ptrs[8], input_ptrs[9], input_ptrs[10], input_ptrs[11], input_ptrs[12], input_ptrs[13], input_ptrs[14], input_ptrs[15],
};
const float minmax_vals[2] = { activation_min, activation_max };
__asm__ __volatile__(
"ldp x26, x23, [%x[inptrs], #0x0]\n"
"ptrue p2.b\n"
"ldp x25, x16, [%x[inptrs], #0x10]\n"
"mov x15, #0x0\n"
"ld1w { z15.s }, p2/Z, [%x[params]]\n"
"mov z14.d, z15.d\n"
"ld1w { z13.s }, p2/Z, [%x[params], #1, MUL VL]\n"
"cntw x14\n"
"mov z12.d, z15.d\n"
"ld1w { z11.s }, p2/Z, [%x[params], #2, MUL VL]\n"
"sub x13, XZR, x14\n"
"mov z10.d, z15.d\n"
"ld1w { z9.s }, p2/Z, [%x[params], #3, MUL VL]\n"
"whilelt p1.s, XZR, %x[n_channels]\n"
"mov z8.d, z15.d\n"
"ld1w { z7.s }, p2/Z, [%x[params], #4, MUL VL]\n"
"cmp x14, %x[n_channels]\n"
"ld1w { z6.s }, p2/Z, [%x[params], #5, MUL VL]\n"
"ld1w { z5.s }, p2/Z, [%x[params], #6, MUL VL]\n"
"ld1w { z4.s }, p2/Z, [%x[params], #7, MUL VL]\n"
"addvl %x[params], %x[params], #16\n"
"ld1w { z3.s }, p1/Z, [x26, x15, LSL #2]\n"
"ld1w { z2.s }, p2/Z, [%x[params], #-8, MUL VL]\n"
"ld1w { z1.s }, p2/Z, [%x[params], #-7, MUL VL]\n"
"addvl %x[params], %x[params], #-6\n"
"ld1w { z0.s }, p1/Z, [x23, x15, LSL #2]\n"
"ld1w { z31.s }, p1/Z, [x25, x15, LSL #2]\n"
"ld1w { z30.s }, p1/Z, [x16, x15, LSL #2]\n"
"ldp x24, x12, [%x[inptrs], #0x20]\n"
"ldp x23, x11, [%x[inptrs], #0x30]\n"
"ldp x10, x9, [%x[inptrs], #0x40]\n"
"ld1w { z29.s }, p1/Z, [x24, x15, LSL #2]\n"
"ld1w { z28.s }, p1/Z, [x12, x15, LSL #2]\n"
"ld1w { z27.s }, p1/Z, [x23, x15, LSL #2]\n"
"ld1w { z26.s }, p1/Z, [x11, x15, LSL #2]\n"
"ld1w { z25.s }, p1/Z, [x10, x15, LSL #2]\n"
"ld1w { z24.s }, p1/Z, [x9, x15, LSL #2]\n"
"ldp x28, x27, [%x[inptrs], #0x50]\n"
"ldp x26, x25, [%x[inptrs], #0x60]\n"
"ldp x24, x23, [%x[inptrs], #0x70]\n"
"ld1w { z23.s }, p1/Z, [x28, x15, LSL #2]\n"
"ld1w { z22.s }, p1/Z, [x27, x15, LSL #2]\n"
"ld1w { z21.s }, p1/Z, [x26, x15, LSL #2]\n"
"ld1w { z20.s }, p1/Z, [x25, x15, LSL #2]\n"
"ld1w { z19.s }, p1/Z, [x24, x15, LSL #2]\n"
"ld1w { z18.s }, p1/Z, [x23, x15, LSL #2]\n"
"ldp x22, x21, [%x[outptrs], #0x0]\n"
"ldp x20, x19, [%x[outptrs], #0x10]\n"
"ld1rw { z17.s }, p2/Z, [%x[minmax_vals]]\n"
"ld1rw { z16.s }, p2/Z, [%x[minmax_vals], #4]\n"
"bge 1f\n"
"1:" // Loop
"fmla z14.s, p2/M, z13.s, z3.s\n"
"ld1w { z15.s }, p2/Z, [%x[params]]\n"
"incw x13\n"
"fmla z12.s, p2/M, z13.s, z0.s\n"
"ldp x26, x23, [%x[inptrs], #0x0]\n"
"mov p0.b, p1.b\n"
"fmla z10.s, p2/M, z13.s, z31.s\n"
"ldp x25, x16, [%x[inptrs], #0x10]\n"
"mov x15, x14\n"
"fmla z8.s, p2/M, z13.s, z30.s\n"
"ld1w { z13.s }, p2/Z, [%x[params], #1, MUL VL]\n"
"incw x14\n"
"fmla z14.s, p2/M, z11.s, z0.s\n"
"ldp x24, x12, [%x[inptrs], #0x20]\n"
"whilelt p1.s, x15, %x[n_channels]\n"
"fmla z12.s, p2/M, z11.s, z29.s\n"
"ld1w { z3.s }, p1/Z, [x26, x15, LSL #2]\n"
"cmp x14, %x[n_channels]\n"
"fmla z10.s, p2/M, z11.s, z30.s\n"
"ld1w { z0.s }, p1/Z, [x23, x15, LSL #2]\n"
"ldp x23, x11, [%x[inptrs], #0x30]\n"
"fmla z8.s, p2/M, z11.s, z28.s\n"
"ld1w { z11.s }, p2/Z, [%x[params], #2, MUL VL]\n"
"fmla z14.s, p2/M, z9.s, z29.s\n"
"ld1w { z29.s }, p1/Z, [x24, x15, LSL #2]\n"
"fmla z12.s, p2/M, z9.s, z27.s\n"
"ld1w { z27.s }, p1/Z, [x23, x15, LSL #2]\n"
"fmla z10.s, p2/M, z9.s, z28.s\n"
"ldp x10, x9, [%x[inptrs], #0x40]\n"
"fmla z8.s, p2/M, z9.s, z26.s\n"
"ld1w { z9.s }, p2/Z, [%x[params], #3, MUL VL]\n"
"fmla z14.s, p2/M, z7.s, z31.s\n"
"ld1w { z31.s }, p1/Z, [x25, x15, LSL #2]\n"
"fmla z12.s, p2/M, z7.s, z30.s\n"
"ldp x28, x27, [%x[inptrs], #0x50]\n"
"fmla z10.s, p2/M, z7.s, z25.s\n"
"ldp x26, x25, [%x[inptrs], #0x60]\n"
"fmla z8.s, p2/M, z7.s, z24.s\n"
"ld1w { z7.s }, p2/Z, [%x[params], #4, MUL VL]\n"
"fmla z14.s, p2/M, z6.s, z30.s\n"
"ld1w { z30.s }, p1/Z, [x16, x15, LSL #2]\n"
"fmla z12.s, p2/M, z6.s, z28.s\n"
"ldp x24, x23, [%x[inptrs], #0x70]\n"
"fmla z10.s, p2/M, z6.s, z24.s\n"
"fmla z8.s, p2/M, z6.s, z23.s\n"
"ld1w { z6.s }, p2/Z, [%x[params], #5, MUL VL]\n"
"fmla z14.s, p2/M, z5.s, z28.s\n"
"ld1w { z28.s }, p1/Z, [x12, x15, LSL #2]\n"
"fmla z12.s, p2/M, z5.s, z26.s\n"
"ld1w { z26.s }, p1/Z, [x11, x15, LSL #2]\n"
"fmla z10.s, p2/M, z5.s, z23.s\n"
"fmla z8.s, p2/M, z5.s, z22.s\n"
"ld1w { z5.s }, p2/Z, [%x[params], #6, MUL VL]\n"
"fmla z14.s, p2/M, z4.s, z25.s\n"
"ld1w { z25.s }, p1/Z, [x10, x15, LSL #2]\n"
"fmla z12.s, p2/M, z4.s, z24.s\n"
"fmla z10.s, p2/M, z4.s, z21.s\n"
"ld1w { z21.s }, p1/Z, [x26, x15, LSL #2]\n"
"fmla z8.s, p2/M, z4.s, z20.s\n"
"ld1w { z4.s }, p2/Z, [%x[params], #7, MUL VL]\n"
"addvl %x[params], %x[params], #16\n"
"fmla z14.s, p2/M, z2.s, z24.s\n"
"ld1w { z24.s }, p1/Z, [x9, x15, LSL #2]\n"
"fmla z12.s, p2/M, z2.s, z23.s\n"
"fmla z10.s, p2/M, z2.s, z20.s\n"
"ld1w { z20.s }, p1/Z, [x25, x15, LSL #2]\n"
"fmla z8.s, p2/M, z2.s, z19.s\n"
"ld1w { z2.s }, p2/Z, [%x[params], #-8, MUL VL]\n"
"fmla z14.s, p2/M, z1.s, z23.s\n"
"ld1w { z23.s }, p1/Z, [x28, x15, LSL #2]\n"
"fmla z12.s, p2/M, z1.s, z22.s\n"
"ld1w { z22.s }, p1/Z, [x27, x15, LSL #2]\n"
"fmla z10.s, p2/M, z1.s, z19.s\n"
"ld1w { z19.s }, p1/Z, [x24, x15, LSL #2]\n"
"fmla z8.s, p2/M, z1.s, z18.s\n"
"ld1w { z1.s }, p2/Z, [%x[params], #-7, MUL VL]\n"
"addvl %x[params], %x[params], #-6\n"
"fmax z14.s, p2/M, z14.s, z17.s\n"
"ld1w { z18.s }, p1/Z, [x23, x15, LSL #2]\n"
"fmax z12.s, p2/M, z12.s, z17.s\n"
"fmax z10.s, p2/M, z10.s, z17.s\n"
"fmax z8.s, p2/M, z8.s, z17.s\n"
"fmin z14.s, p2/M, z14.s, z16.s\n"
"st1w { z14.s }, p0, [x22, x13, LSL #2]\n"
"mov z14.d, z15.d\n"
"fmin z12.s, p2/M, z12.s, z16.s\n"
"st1w { z12.s }, p0, [x21, x13, LSL #2]\n"
"mov z12.d, z15.d\n"
"fmin z10.s, p2/M, z10.s, z16.s\n"
"st1w { z10.s }, p0, [x20, x13, LSL #2]\n"
"mov z10.d, z15.d\n"
"fmin z8.s, p2/M, z8.s, z16.s\n"
"st1w { z8.s }, p0, [x19, x13, LSL #2]\n"
"mov z8.d, z15.d\n"
"blt 1b\n"
"2:" // Tail
"fmla z14.s, p2/M, z13.s, z3.s\n"
"incw x13\n"
"fmla z12.s, p2/M, z13.s, z0.s\n"
"mov p0.b, p1.b\n"
"fmla z10.s, p2/M, z13.s, z31.s\n"
"fmla z8.s, p2/M, z13.s, z30.s\n"
"fmla z14.s, p2/M, z11.s, z0.s\n"
"fmla z12.s, p2/M, z11.s, z29.s\n"
"fmla z10.s, p2/M, z11.s, z30.s\n"
"fmla z8.s, p2/M, z11.s, z28.s\n"
"fmla z14.s, p2/M, z9.s, z29.s\n"
"fmla z12.s, p2/M, z9.s, z27.s\n"
"fmla z10.s, p2/M, z9.s, z28.s\n"
"fmla z8.s, p2/M, z9.s, z26.s\n"
"fmla z14.s, p2/M, z7.s, z31.s\n"
"fmla z12.s, p2/M, z7.s, z30.s\n"
"fmla z10.s, p2/M, z7.s, z25.s\n"
"fmla z8.s, p2/M, z7.s, z24.s\n"
"fmla z14.s, p2/M, z6.s, z30.s\n"
"fmla z12.s, p2/M, z6.s, z28.s\n"
"fmla z10.s, p2/M, z6.s, z24.s\n"
"fmla z8.s, p2/M, z6.s, z23.s\n"
"fmla z14.s, p2/M, z5.s, z28.s\n"
"fmla z12.s, p2/M, z5.s, z26.s\n"
"fmla z10.s, p2/M, z5.s, z23.s\n"
"fmla z8.s, p2/M, z5.s, z22.s\n"
"fmla z14.s, p2/M, z4.s, z25.s\n"
"fmla z12.s, p2/M, z4.s, z24.s\n"
"fmla z10.s, p2/M, z4.s, z21.s\n"
"fmla z8.s, p2/M, z4.s, z20.s\n"
"fmla z14.s, p2/M, z2.s, z24.s\n"
"fmla z12.s, p2/M, z2.s, z23.s\n"
"fmla z10.s, p2/M, z2.s, z20.s\n"
"fmla z8.s, p2/M, z2.s, z19.s\n"
"fmla z14.s, p2/M, z1.s, z23.s\n"
"fmla z12.s, p2/M, z1.s, z22.s\n"
"fmla z10.s, p2/M, z1.s, z19.s\n"
"fmla z8.s, p2/M, z1.s, z18.s\n"
"fmax z14.s, p2/M, z14.s, z17.s\n"
"fmax z12.s, p2/M, z12.s, z17.s\n"
"fmax z10.s, p2/M, z10.s, z17.s\n"
"fmax z8.s, p2/M, z8.s, z17.s\n"
"fmin z14.s, p2/M, z14.s, z16.s\n"
"st1w { z14.s }, p0, [x22, x13, LSL #2]\n"
"fmin z12.s, p2/M, z12.s, z16.s\n"
"fmin z10.s, p2/M, z10.s, z16.s\n"
"st1w { z12.s }, p0, [x21, x13, LSL #2]\n"
"fmin z8.s, p2/M, z8.s, z16.s\n"
"st1w { z10.s }, p0, [x20, x13, LSL #2]\n"
"st1w { z8.s }, p0, [x19, x13, LSL #2]\n"
: [params] "+r" (params)
: [inptrs] "r" (inptrs), [minmax_vals] "r" (minmax_vals), [n_channels] "r" ((unsigned long) n_channels), [outptrs] "r" (outptrs)
: "cc", "memory", "p0", "p1", "p2", "x9", "x10", "x11", "x12", "x13", "x14", "x15", "x16", "x19", "x20", "x21", "x22", "x23", "x24", "x25", "x26", "x27", "x28", "z0", "z1", "z2", "z3", "z4", "z5", "z6", "z7", "z8", "z9", "z10", "z11", "z12", "z13", "z14", "z15", "z16", "z17", "z18", "z19", "z20", "z21", "z22", "z23", "z24", "z25", "z26", "z27", "z28", "z29", "z30", "z31"
);
}
} // namespace depthwise
} // namespace arm_conv
#endif // defined(ARM_COMPUTE_ENABLE_SVE)
| 10,522 | 6,672 |
//===--- SwitchEnumBuilder.cpp --------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "SwitchEnumBuilder.h"
#include "SILGenFunction.h"
#include "swift/SIL/SILLocation.h"
using namespace swift;
using namespace Lowering;
//===----------------------------------------------------------------------===//
// SwitchCaseFullExpr Implementation
//===----------------------------------------------------------------------===//
SwitchCaseFullExpr::SwitchCaseFullExpr(SILGenFunction &SGF, CleanupLocation loc)
: SGF(SGF), scope(SGF, loc), loc(loc), branchDest() {}
SwitchCaseFullExpr::SwitchCaseFullExpr(SILGenFunction &SGF, CleanupLocation loc,
SwitchCaseBranchDest branchDest)
: SGF(SGF), scope(SGF, loc), loc(loc), branchDest(branchDest) {}
void SwitchCaseFullExpr::exitAndBranch(SILLocation loc,
ArrayRef<SILValue> branchArgs) {
assert(bool(branchDest) && "Must have a branch destination!");
assert(SGF.B.hasValidInsertionPoint());
scope.pop();
// Then either do a direct branch or a branch + cleanups.
if (SILBasicBlock *block = branchDest.getBlock()) {
SGF.B.createBranch(loc, block, branchArgs);
return;
}
SGF.Cleanups.emitBranchAndCleanups(branchDest.getJumpDest(), loc, branchArgs);
}
void SwitchCaseFullExpr::exit() {
assert(!bool(branchDest) &&
"Should not call this if we do have a continuation block");
assert(SGF.B.hasValidInsertionPoint());
scope.pop();
}
SwitchCaseFullExpr::~SwitchCaseFullExpr() {
assert(!scope.isValid() && "Did not pop scope?!");
}
void SwitchCaseFullExpr::unreachableExit() {
// This is important to ensure that we do not actually emit any cleanups since
// we already know that an unreachable was emitted.
assert(!SGF.B.hasValidInsertionPoint() && "Expected to pop scope without a "
"valid insertion point!");
scope.pop();
}
//===----------------------------------------------------------------------===//
// SwitchEnumBuilder Implementation
//===----------------------------------------------------------------------===//
void SwitchEnumBuilder::emit() && {
bool isAddressOnly =
subjectExprOperand.getType().isAddressOnly(builder.getFunction()) &&
getSGF().silConv.useLoweredAddresses();
using DeclBlockPair = std::pair<EnumElementDecl *, SILBasicBlock *>;
{
// TODO: We could store the data in CaseBB form and not have to do this.
llvm::SmallVector<DeclBlockPair, 8> caseBlocks;
llvm::SmallVector<ProfileCounter, 8> caseBlockCounts;
std::transform(caseDataArray.begin(), caseDataArray.end(),
std::back_inserter(caseBlocks),
[](NormalCaseData &caseData) -> DeclBlockPair {
return {caseData.decl, caseData.block};
});
std::transform(caseDataArray.begin(), caseDataArray.end(),
std::back_inserter(caseBlockCounts),
[](NormalCaseData &caseData) -> ProfileCounter {
return caseData.count;
});
SILBasicBlock *defaultBlock =
defaultBlockData ? defaultBlockData->block : nullptr;
ProfileCounter defaultBlockCount =
defaultBlockData ? defaultBlockData->count : ProfileCounter();
ArrayRef<ProfileCounter> caseBlockCountsRef = caseBlockCounts;
if (isAddressOnly) {
builder.createSwitchEnumAddr(loc, subjectExprOperand.getValue(),
defaultBlock, caseBlocks, caseBlockCountsRef,
defaultBlockCount);
} else {
if (subjectExprOperand.getType().isAddress()) {
// TODO: Refactor this into a maybe load.
if (subjectExprOperand.hasCleanup()) {
subjectExprOperand = builder.createLoadTake(loc, subjectExprOperand);
} else {
subjectExprOperand = builder.createLoadCopy(loc, subjectExprOperand);
}
}
builder.createSwitchEnum(loc, subjectExprOperand.forward(getSGF()),
defaultBlock, caseBlocks, caseBlockCountsRef,
defaultBlockCount);
}
}
// If we are asked to create a default block and it is specified that the
// default block should be emitted before normal cases, emit it now.
if (defaultBlockData &&
defaultBlockData->dispatchTime ==
DefaultDispatchTime::BeforeNormalCases) {
SILBasicBlock *defaultBlock = defaultBlockData->block;
SwitchCaseBranchDest branchDest = defaultBlockData->branchDest;
DefaultCaseHandler handler = defaultBlockData->handler;
// Don't allow cleanups to escape the conditional block.
SwitchCaseFullExpr presentScope(builder.getSILGenFunction(),
CleanupLocation(loc), branchDest);
builder.emitBlock(defaultBlock);
ManagedValue input = subjectExprOperand;
if (!isAddressOnly) {
input = builder.createOwnedPhiArgument(subjectExprOperand.getType());
}
handler(input, std::move(presentScope));
builder.clearInsertionPoint();
}
for (NormalCaseData &caseData : caseDataArray) {
EnumElementDecl *decl = caseData.decl;
SILBasicBlock *caseBlock = caseData.block;
SwitchCaseBranchDest branchDest = caseData.branchDest;
NormalCaseHandler handler = caseData.handler;
// Don't allow cleanups to escape the conditional block.
SwitchCaseFullExpr presentScope(builder.getSILGenFunction(),
CleanupLocation(loc), branchDest);
builder.emitBlock(caseBlock);
ManagedValue input;
if (decl->hasAssociatedValues()) {
// Pull the payload out if we have one.
SILType inputType = subjectExprOperand.getType().getEnumElementType(
decl, builder.getModule(), builder.getFunction());
input = subjectExprOperand;
if (!isAddressOnly) {
input = builder.createOwnedPhiArgument(inputType);
}
}
handler(input, std::move(presentScope));
builder.clearInsertionPoint();
}
// If we are asked to create a default block and it is specified that the
// default block should be emitted after normal cases, emit it now.
if (defaultBlockData &&
defaultBlockData->dispatchTime == DefaultDispatchTime::AfterNormalCases) {
SILBasicBlock *defaultBlock = defaultBlockData->block;
auto branchDest = defaultBlockData->branchDest;
DefaultCaseHandler handler = defaultBlockData->handler;
// Don't allow cleanups to escape the conditional block.
SwitchCaseFullExpr presentScope(builder.getSILGenFunction(),
CleanupLocation(loc), branchDest);
builder.emitBlock(defaultBlock);
ManagedValue input = subjectExprOperand;
if (!isAddressOnly) {
input = builder.createOwnedPhiArgument(subjectExprOperand.getType());
}
handler(input, std::move(presentScope));
builder.clearInsertionPoint();
}
}
| 7,434 | 1,994 |
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include "base/file_util.h"
#include "base/platform_file.h"
#include "base/scoped_temp_dir.h"
#include "testing/gtest/include/gtest/gtest.h"
TEST(ScopedTempDir, FullPath) {
FilePath test_path;
file_util::CreateNewTempDirectory(FILE_PATH_LITERAL("scoped_temp_dir"),
&test_path);
// Against an existing dir, it should get destroyed when leaving scope.
EXPECT_TRUE(file_util::DirectoryExists(test_path));
{
ScopedTempDir dir;
EXPECT_TRUE(dir.Set(test_path));
EXPECT_TRUE(dir.IsValid());
}
EXPECT_FALSE(file_util::DirectoryExists(test_path));
{
ScopedTempDir dir;
EXPECT_TRUE(dir.Set(test_path));
// Now the dir doesn't exist, so ensure that it gets created.
EXPECT_TRUE(file_util::DirectoryExists(test_path));
// When we call Release(), it shouldn't get destroyed when leaving scope.
FilePath path = dir.Take();
EXPECT_EQ(path.value(), test_path.value());
EXPECT_FALSE(dir.IsValid());
}
EXPECT_TRUE(file_util::DirectoryExists(test_path));
// Clean up.
{
ScopedTempDir dir;
EXPECT_TRUE(dir.Set(test_path));
}
EXPECT_FALSE(file_util::DirectoryExists(test_path));
}
TEST(ScopedTempDir, TempDir) {
// In this case, just verify that a directory was created and that it's a
// child of TempDir.
FilePath test_path;
{
ScopedTempDir dir;
EXPECT_TRUE(dir.CreateUniqueTempDir());
test_path = dir.path();
EXPECT_TRUE(file_util::DirectoryExists(test_path));
FilePath tmp_dir;
EXPECT_TRUE(file_util::GetTempDir(&tmp_dir));
EXPECT_TRUE(test_path.value().find(tmp_dir.value()) != std::string::npos);
}
EXPECT_FALSE(file_util::DirectoryExists(test_path));
}
TEST(ScopedTempDir, UniqueTempDirUnderPath) {
// Create a path which will contain a unique temp path.
FilePath base_path;
ASSERT_TRUE(file_util::CreateNewTempDirectory(FILE_PATH_LITERAL("base_dir"),
&base_path));
FilePath test_path;
{
ScopedTempDir dir;
EXPECT_TRUE(dir.CreateUniqueTempDirUnderPath(base_path));
test_path = dir.path();
EXPECT_TRUE(file_util::DirectoryExists(test_path));
EXPECT_TRUE(base_path.IsParent(test_path));
EXPECT_TRUE(test_path.value().find(base_path.value()) != std::string::npos);
}
EXPECT_FALSE(file_util::DirectoryExists(test_path));
file_util::Delete(base_path, true);
}
TEST(ScopedTempDir, MultipleInvocations) {
ScopedTempDir dir;
EXPECT_TRUE(dir.CreateUniqueTempDir());
EXPECT_FALSE(dir.CreateUniqueTempDir());
EXPECT_TRUE(dir.Delete());
EXPECT_TRUE(dir.CreateUniqueTempDir());
EXPECT_FALSE(dir.CreateUniqueTempDir());
ScopedTempDir other_dir;
EXPECT_TRUE(other_dir.Set(dir.Take()));
EXPECT_TRUE(dir.CreateUniqueTempDir());
EXPECT_FALSE(dir.CreateUniqueTempDir());
EXPECT_FALSE(other_dir.CreateUniqueTempDir());
}
#if defined(OS_WIN)
TEST(ScopedTempDir, LockedTempDir) {
ScopedTempDir dir;
EXPECT_TRUE(dir.CreateUniqueTempDir());
int file_flags = base::PLATFORM_FILE_CREATE_ALWAYS |
base::PLATFORM_FILE_WRITE;
base::PlatformFileError error_code = base::PLATFORM_FILE_OK;
FilePath file_path(dir.path().Append(FILE_PATH_LITERAL("temp")));
base::PlatformFile file = base::CreatePlatformFile(file_path, file_flags,
NULL, &error_code);
EXPECT_NE(base::kInvalidPlatformFileValue, file);
EXPECT_EQ(base::PLATFORM_FILE_OK, error_code);
EXPECT_FALSE(dir.Delete()); // We should not be able to delete.
EXPECT_FALSE(dir.path().empty()); // We should still have a valid path.
EXPECT_TRUE(base::ClosePlatformFile(file));
// Now, we should be able to delete.
EXPECT_TRUE(dir.Delete());
}
#endif // defined(OS_WIN)
| 3,938 | 1,386 |
//---------------------------------------------------------------------------------------------------------------------
// Copyright (C) 2015, M. G. Tsai.
// ALL RIGHTS RESERVED.
//---------------------------------------------------------------------------------------------------------------------
| 299 | 53 |
/////////////////////////////////////////////////////////////////////////////
// Name: src/common/sysopt.cpp
// Purpose: wxSystemOptions
// Author: Julian Smart
// Modified by:
// Created: 2001-07-10
// Copyright: (c) Julian Smart
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ---------------------------------------------------------------------------
// headers
// ---------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#if defined(__BORLANDC__)
#pragma hdrstop
#endif
#if wxUSE_SYSTEM_OPTIONS
#include "wx/sysopt.h"
#ifndef WX_PRECOMP
#include "wx/app.h"
#include "wx/list.h"
#include "wx/string.h"
#include "wx/arrstr.h"
#endif
// ----------------------------------------------------------------------------
// private globals
// ----------------------------------------------------------------------------
static wxArrayString gs_optionNames,
gs_optionValues;
// ============================================================================
// wxSystemOptions implementation
// ============================================================================
// Option functions (arbitrary name/value mapping)
void wxSystemOptions::SetOption(const wxString& name, const wxString& value)
{
int idx = gs_optionNames.Index(name, false);
if (idx == wxNOT_FOUND)
{
gs_optionNames.Add(name);
gs_optionValues.Add(value);
}
else
{
gs_optionNames[idx] = name;
gs_optionValues[idx] = value;
}
}
void wxSystemOptions::SetOption(const wxString& name, int value)
{
SetOption(name, wxString::Format(wxT("%d"), value));
}
wxString wxSystemOptions::GetOption(const wxString& name)
{
wxString val;
int idx = gs_optionNames.Index(name, false);
if ( idx != wxNOT_FOUND )
{
val = gs_optionValues[idx];
}
else // not set explicitly
{
// look in the environment: first for a variable named "wx_appname_name"
// which can be set to affect the behaviour or just this application
// and then for "wx_name" which can be set to change the option globally
wxString var(name);
var.Replace(wxT("."), wxT("_")); // '.'s not allowed in env var names
var.Replace(wxT("-"), wxT("_")); // and neither are '-'s
wxString appname;
if ( wxTheApp )
appname = wxTheApp->GetAppName();
if ( !appname.empty() )
val = wxGetenv(wxT("wx_") + appname + wxT('_') + var);
if ( val.empty() )
val = wxGetenv(wxT("wx_") + var);
}
return val;
}
int wxSystemOptions::GetOptionInt(const wxString& name)
{
return wxAtoi (GetOption(name));
}
bool wxSystemOptions::HasOption(const wxString& name)
{
return !GetOption(name).empty();
}
#endif // wxUSE_SYSTEM_OPTIONS
| 3,176 | 901 |
/********************************************************************
CrazyGaze (http://www.crazygaze.com)
Author : Rui Figueira
Email : rui@crazygaze.com
purpose:
*********************************************************************/
#include "SamplesCommonPCH.h"
#include "Parameters.h"
namespace cz
{
std::string Parameters::ms_empty;
Parameters::Parameters()
{
}
void Parameters::set(int argc, char* argv[])
{
if (argc<=1)
return;
for (int i=1; i<argc; i++)
{
const char *arg = argv[i];
if (*arg == '-')
arg++;
const char *seperator = strchr(arg, '=');
if (seperator==nullptr)
{
m_args.emplace_back(arg, "");
}
else
{
std::string name(arg, seperator);
std::string value(++seperator);
m_args.emplace_back(std::move(name), std::move(value));
}
}
}
const Parameters::Param* Parameters::begin() const
{
if (m_args.size())
return &m_args[0];
else
return nullptr;
}
const Parameters::Param* Parameters::end() const
{
return begin() + m_args.size();
}
bool Parameters::has( const char* name ) const
{
for(auto &i: m_args)
{
if (i.name==name)
{
return true;
}
}
return false;
}
bool Parameters::has( const std::string& name ) const
{
return has(name.c_str());
}
const std::string& Parameters::get( const char *name ) const
{
for (auto &i: m_args)
{
if (i.name==name)
return i.value;
}
return ms_empty;
}
} // namespace cz
| 1,498 | 613 |
#include "Skin.hpp"
#include <core/GodotGlobal.hpp>
#include <core/CoreTypes.hpp>
#include <core/Ref.hpp>
#include <core/Godot.hpp>
#include "__icalls.hpp"
namespace godot {
Skin::___method_bindings Skin::___mb = {};
void Skin::___init_method_bindings() {
___mb.mb_add_bind = godot::api->godot_method_bind_get_method("Skin", "add_bind");
___mb.mb_clear_binds = godot::api->godot_method_bind_get_method("Skin", "clear_binds");
___mb.mb_get_bind_bone = godot::api->godot_method_bind_get_method("Skin", "get_bind_bone");
___mb.mb_get_bind_count = godot::api->godot_method_bind_get_method("Skin", "get_bind_count");
___mb.mb_get_bind_pose = godot::api->godot_method_bind_get_method("Skin", "get_bind_pose");
___mb.mb_set_bind_bone = godot::api->godot_method_bind_get_method("Skin", "set_bind_bone");
___mb.mb_set_bind_count = godot::api->godot_method_bind_get_method("Skin", "set_bind_count");
___mb.mb_set_bind_pose = godot::api->godot_method_bind_get_method("Skin", "set_bind_pose");
}
Skin *Skin::_new()
{
return (Skin *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, godot::api->godot_get_class_constructor((char *)"Skin")());
}
void Skin::add_bind(const int64_t bone, const Transform pose) {
___godot_icall_void_int_Transform(___mb.mb_add_bind, (const Object *) this, bone, pose);
}
void Skin::clear_binds() {
___godot_icall_void(___mb.mb_clear_binds, (const Object *) this);
}
int64_t Skin::get_bind_bone(const int64_t bind_index) const {
return ___godot_icall_int_int(___mb.mb_get_bind_bone, (const Object *) this, bind_index);
}
int64_t Skin::get_bind_count() const {
return ___godot_icall_int(___mb.mb_get_bind_count, (const Object *) this);
}
Transform Skin::get_bind_pose(const int64_t bind_index) const {
return ___godot_icall_Transform_int(___mb.mb_get_bind_pose, (const Object *) this, bind_index);
}
void Skin::set_bind_bone(const int64_t bind_index, const int64_t bone) {
___godot_icall_void_int_int(___mb.mb_set_bind_bone, (const Object *) this, bind_index, bone);
}
void Skin::set_bind_count(const int64_t bind_count) {
___godot_icall_void_int(___mb.mb_set_bind_count, (const Object *) this, bind_count);
}
void Skin::set_bind_pose(const int64_t bind_index, const Transform pose) {
___godot_icall_void_int_Transform(___mb.mb_set_bind_pose, (const Object *) this, bind_index, pose);
}
} | 2,402 | 981 |
// Copyright 2016 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 <stdint.h>
#include "base/bind.h"
#include "base/logging.h"
#include "base/single_thread_task_runner.h"
#include "base/synchronization/waitable_event.h"
#include "base/threading/thread.h"
#include "media/video/mock_gpu_video_accelerator_factories.h"
#include "media/video/mock_video_encode_accelerator.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/platform/peerconnection/rtc_video_encoder.h"
#include "third_party/libyuv/include/libyuv/planar_functions.h"
#include "third_party/webrtc/api/video/i420_buffer.h"
#include "third_party/webrtc/api/video_codecs/video_encoder.h"
#include "third_party/webrtc/modules/video_coding/include/video_codec_interface.h"
#include "third_party/webrtc/rtc_base/time_utils.h"
using ::testing::_;
using ::testing::AtLeast;
using ::testing::Invoke;
using ::testing::Return;
using ::testing::SaveArg;
using ::testing::Values;
using ::testing::WithArgs;
namespace blink {
namespace {
const int kInputFrameFillY = 12;
const int kInputFrameFillU = 23;
const int kInputFrameFillV = 34;
const uint16_t kInputFrameHeight = 234;
const uint16_t kInputFrameWidth = 345;
const uint16_t kStartBitrate = 100;
class EncodedImageCallbackWrapper : public webrtc::EncodedImageCallback {
public:
using EncodedCallback = base::OnceCallback<void(
const webrtc::EncodedImage& encoded_image,
const webrtc::CodecSpecificInfo* codec_specific_info)>;
EncodedImageCallbackWrapper(EncodedCallback encoded_callback)
: encoded_callback_(std::move(encoded_callback)) {}
Result OnEncodedImage(
const webrtc::EncodedImage& encoded_image,
const webrtc::CodecSpecificInfo* codec_specific_info) override {
std::move(encoded_callback_).Run(encoded_image, codec_specific_info);
return Result(Result::OK);
}
private:
EncodedCallback encoded_callback_;
};
} // anonymous namespace
class RTCVideoEncoderTest
: public ::testing::TestWithParam<webrtc::VideoCodecType> {
public:
RTCVideoEncoderTest()
: encoder_thread_("vea_thread"),
mock_gpu_factories_(
new media::MockGpuVideoAcceleratorFactories(nullptr)),
idle_waiter_(base::WaitableEvent::ResetPolicy::AUTOMATIC,
base::WaitableEvent::InitialState::NOT_SIGNALED) {}
media::MockVideoEncodeAccelerator* ExpectCreateInitAndDestroyVEA() {
// The VEA will be owned by the RTCVideoEncoder once
// factory.CreateVideoEncodeAccelerator() is called.
media::MockVideoEncodeAccelerator* mock_vea =
new media::MockVideoEncodeAccelerator();
EXPECT_CALL(*mock_gpu_factories_.get(), DoCreateVideoEncodeAccelerator())
.WillRepeatedly(Return(mock_vea));
EXPECT_CALL(*mock_vea, Initialize(_, _))
.WillOnce(Invoke(this, &RTCVideoEncoderTest::Initialize));
EXPECT_CALL(*mock_vea, UseOutputBitstreamBuffer(_)).Times(AtLeast(3));
EXPECT_CALL(*mock_vea, Destroy()).Times(1);
return mock_vea;
}
void SetUp() override {
DVLOG(3) << __func__;
ASSERT_TRUE(encoder_thread_.Start());
EXPECT_CALL(*mock_gpu_factories_.get(), GetTaskRunner())
.WillRepeatedly(Return(encoder_thread_.task_runner()));
mock_vea_ = ExpectCreateInitAndDestroyVEA();
}
void TearDown() override {
DVLOG(3) << __func__;
EXPECT_TRUE(encoder_thread_.IsRunning());
RunUntilIdle();
rtc_encoder_->Release();
RunUntilIdle();
encoder_thread_.Stop();
}
void RunUntilIdle() {
DVLOG(3) << __func__;
encoder_thread_.task_runner()->PostTask(
FROM_HERE, base::BindOnce(&base::WaitableEvent::Signal,
base::Unretained(&idle_waiter_)));
idle_waiter_.Wait();
}
void CreateEncoder(webrtc::VideoCodecType codec_type) {
DVLOG(3) << __func__;
media::VideoCodecProfile media_profile;
switch (codec_type) {
case webrtc::kVideoCodecVP8:
media_profile = media::VP8PROFILE_ANY;
break;
case webrtc::kVideoCodecH264:
media_profile = media::H264PROFILE_BASELINE;
break;
case webrtc::kVideoCodecVP9:
media_profile = media::VP9PROFILE_PROFILE0;
break;
default:
ADD_FAILURE() << "Unexpected codec type: " << codec_type;
media_profile = media::VIDEO_CODEC_PROFILE_UNKNOWN;
}
rtc_encoder_ = std::make_unique<RTCVideoEncoder>(media_profile, false,
mock_gpu_factories_.get());
}
// media::VideoEncodeAccelerator implementation.
bool Initialize(const media::VideoEncodeAccelerator::Config& config,
media::VideoEncodeAccelerator::Client* client) {
DVLOG(3) << __func__;
client_ = client;
client_->RequireBitstreamBuffers(0, config.input_visible_size,
config.input_visible_size.GetArea());
return true;
}
void RegisterEncodeCompleteCallback(
EncodedImageCallbackWrapper::EncodedCallback callback) {
callback_wrapper_ =
std::make_unique<EncodedImageCallbackWrapper>(std::move(callback));
rtc_encoder_->RegisterEncodeCompleteCallback(callback_wrapper_.get());
}
webrtc::VideoCodec GetDefaultCodec() {
webrtc::VideoCodec codec = {};
memset(&codec, 0, sizeof(codec));
codec.width = kInputFrameWidth;
codec.height = kInputFrameHeight;
codec.codecType = webrtc::kVideoCodecVP8;
codec.startBitrate = kStartBitrate;
return codec;
}
webrtc::VideoCodec GetDefaultTemporalLayerCodec() {
const webrtc::VideoCodecType codec_type = webrtc::kVideoCodecVP9;
webrtc::VideoCodec codec{};
codec.codecType = codec_type;
codec.width = kInputFrameWidth;
codec.height = kInputFrameHeight;
codec.startBitrate = kStartBitrate;
codec.maxBitrate = codec.startBitrate * 2;
codec.minBitrate = codec.startBitrate / 2;
codec.maxFramerate = 24;
codec.active = true;
codec.qpMax = 30;
codec.numberOfSimulcastStreams = 1;
codec.mode = webrtc::VideoCodecMode::kRealtimeVideo;
webrtc::VideoCodecVP9& vp9 = *codec.VP9();
vp9.numberOfTemporalLayers = 3;
vp9.numberOfSpatialLayers = 1;
webrtc::SpatialLayer& sl = codec.spatialLayers[0];
sl.width = kInputFrameWidth;
sl.height = kInputFrameHeight;
sl.maxFramerate = 24;
sl.numberOfTemporalLayers = vp9.numberOfTemporalLayers;
sl.targetBitrate = kStartBitrate;
sl.maxBitrate = sl.targetBitrate;
sl.minBitrate = sl.targetBitrate;
sl.qpMax = 30;
sl.active = true;
return codec;
}
void FillFrameBuffer(rtc::scoped_refptr<webrtc::I420Buffer> frame) {
CHECK(libyuv::I420Rect(frame->MutableDataY(), frame->StrideY(),
frame->MutableDataU(), frame->StrideU(),
frame->MutableDataV(), frame->StrideV(), 0, 0,
frame->width(), frame->height(), kInputFrameFillY,
kInputFrameFillU, kInputFrameFillV) == 0);
}
void VerifyEncodedFrame(scoped_refptr<media::VideoFrame> frame,
bool force_keyframe) {
DVLOG(3) << __func__;
EXPECT_EQ(kInputFrameWidth, frame->visible_rect().width());
EXPECT_EQ(kInputFrameHeight, frame->visible_rect().height());
EXPECT_EQ(kInputFrameFillY,
frame->visible_data(media::VideoFrame::kYPlane)[0]);
EXPECT_EQ(kInputFrameFillU,
frame->visible_data(media::VideoFrame::kUPlane)[0]);
EXPECT_EQ(kInputFrameFillV,
frame->visible_data(media::VideoFrame::kVPlane)[0]);
}
void ReturnFrameWithTimeStamp(scoped_refptr<media::VideoFrame> frame,
bool force_keyframe) {
client_->BitstreamBufferReady(
0,
media::BitstreamBufferMetadata(0, force_keyframe, frame->timestamp()));
}
void ReturnTemporalLayerFrameWithVp9Metadata(
scoped_refptr<media::VideoFrame> frame,
bool force_keyframe) {
int32_t bitstream_buffer_id = frame->timestamp().InMicroseconds();
CHECK(0 <= bitstream_buffer_id && bitstream_buffer_id <= 4);
media::BitstreamBufferMetadata metadata(100u /* payload_size_bytes */,
force_keyframe, frame->timestamp());
// Assume the number of TLs is three. TL structure is below.
// TL2: [#1] /-[#3]
// TL1: /_____[#2] /
// TL0: [#0]-----------------[#4]
media::Vp9Metadata vp9;
vp9.has_reference = bitstream_buffer_id != 0 && !force_keyframe;
vp9.temporal_up_switch = bitstream_buffer_id != 3;
switch (bitstream_buffer_id) {
case 0:
vp9.temporal_idx = 0;
break;
case 1:
vp9.temporal_idx = 2;
vp9.p_diffs = {1};
break;
case 2:
vp9.temporal_idx = 1;
vp9.p_diffs = {2};
break;
case 3:
vp9.temporal_idx = 2;
vp9.p_diffs = {1, 3};
break;
case 4:
vp9.temporal_idx = 0;
vp9.p_diffs = {4};
break;
}
metadata.vp9 = vp9;
client_->BitstreamBufferReady(bitstream_buffer_id, metadata);
}
void VerifyTimestamp(uint32_t rtp_timestamp,
int64_t capture_time_ms,
const webrtc::EncodedImage& encoded_image,
const webrtc::CodecSpecificInfo* codec_specific_info) {
DVLOG(3) << __func__;
EXPECT_EQ(rtp_timestamp, encoded_image.Timestamp());
EXPECT_EQ(capture_time_ms, encoded_image.capture_time_ms_);
}
protected:
media::MockVideoEncodeAccelerator* mock_vea_;
std::unique_ptr<RTCVideoEncoder> rtc_encoder_;
media::VideoEncodeAccelerator::Client* client_;
base::Thread encoder_thread_;
private:
std::unique_ptr<media::MockGpuVideoAcceleratorFactories> mock_gpu_factories_;
std::unique_ptr<EncodedImageCallbackWrapper> callback_wrapper_;
base::WaitableEvent idle_waiter_;
};
TEST_P(RTCVideoEncoderTest, CreateAndInitSucceeds) {
const webrtc::VideoCodecType codec_type = GetParam();
CreateEncoder(codec_type);
webrtc::VideoCodec codec = GetDefaultCodec();
codec.codecType = codec_type;
EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK, rtc_encoder_->InitEncode(&codec, 1, 12345));
}
TEST_P(RTCVideoEncoderTest, RepeatedInitSucceeds) {
const webrtc::VideoCodecType codec_type = GetParam();
CreateEncoder(codec_type);
webrtc::VideoCodec codec = GetDefaultCodec();
codec.codecType = codec_type;
EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK, rtc_encoder_->InitEncode(&codec, 1, 12345));
ExpectCreateInitAndDestroyVEA();
EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK, rtc_encoder_->InitEncode(&codec, 1, 12345));
}
INSTANTIATE_TEST_SUITE_P(CodecProfiles,
RTCVideoEncoderTest,
Values(webrtc::kVideoCodecVP8,
webrtc::kVideoCodecH264));
TEST_F(RTCVideoEncoderTest, CreateAndInitSucceedsForTemporalLayer) {
webrtc::VideoCodec tl_codec = GetDefaultTemporalLayerCodec();
CreateEncoder(tl_codec.codecType);
EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK,
rtc_encoder_->InitEncode(&tl_codec, 1, 12345));
}
// Checks that WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE is returned when there is
// platform error.
TEST_F(RTCVideoEncoderTest, SoftwareFallbackAfterError) {
const webrtc::VideoCodecType codec_type = webrtc::kVideoCodecVP8;
CreateEncoder(codec_type);
webrtc::VideoCodec codec = GetDefaultCodec();
codec.codecType = codec_type;
EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK, rtc_encoder_->InitEncode(&codec, 1, 12345));
EXPECT_CALL(*mock_vea_, Encode(_, _))
.WillOnce(Invoke([this](scoped_refptr<media::VideoFrame>, bool) {
encoder_thread_.task_runner()->PostTask(
FROM_HERE,
base::BindOnce(
&media::VideoEncodeAccelerator::Client::NotifyError,
base::Unretained(client_),
media::VideoEncodeAccelerator::kPlatformFailureError));
}));
const rtc::scoped_refptr<webrtc::I420Buffer> buffer =
webrtc::I420Buffer::Create(kInputFrameWidth, kInputFrameHeight);
FillFrameBuffer(buffer);
std::vector<webrtc::VideoFrameType> frame_types;
EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK,
rtc_encoder_->Encode(webrtc::VideoFrame::Builder()
.set_video_frame_buffer(buffer)
.set_timestamp_rtp(0)
.set_timestamp_us(0)
.set_rotation(webrtc::kVideoRotation_0)
.build(),
&frame_types));
RunUntilIdle();
// Expect the next frame to return SW fallback.
EXPECT_EQ(WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE,
rtc_encoder_->Encode(webrtc::VideoFrame::Builder()
.set_video_frame_buffer(buffer)
.set_timestamp_rtp(0)
.set_timestamp_us(0)
.set_rotation(webrtc::kVideoRotation_0)
.build(),
&frame_types));
}
TEST_F(RTCVideoEncoderTest, EncodeScaledFrame) {
const webrtc::VideoCodecType codec_type = webrtc::kVideoCodecVP8;
CreateEncoder(codec_type);
webrtc::VideoCodec codec = GetDefaultCodec();
EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK, rtc_encoder_->InitEncode(&codec, 1, 12345));
EXPECT_CALL(*mock_vea_, Encode(_, _))
.Times(2)
.WillRepeatedly(Invoke(this, &RTCVideoEncoderTest::VerifyEncodedFrame));
const rtc::scoped_refptr<webrtc::I420Buffer> buffer =
webrtc::I420Buffer::Create(kInputFrameWidth, kInputFrameHeight);
FillFrameBuffer(buffer);
std::vector<webrtc::VideoFrameType> frame_types;
EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK,
rtc_encoder_->Encode(webrtc::VideoFrame::Builder()
.set_video_frame_buffer(buffer)
.set_timestamp_rtp(0)
.set_timestamp_us(0)
.set_rotation(webrtc::kVideoRotation_0)
.build(),
&frame_types));
const rtc::scoped_refptr<webrtc::I420Buffer> upscaled_buffer =
webrtc::I420Buffer::Create(2 * kInputFrameWidth, 2 * kInputFrameHeight);
FillFrameBuffer(upscaled_buffer);
webrtc::VideoFrame rtc_frame = webrtc::VideoFrame::Builder()
.set_video_frame_buffer(upscaled_buffer)
.set_timestamp_rtp(0)
.set_timestamp_us(0)
.set_rotation(webrtc::kVideoRotation_0)
.build();
rtc_frame.set_ntp_time_ms(123456);
EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK,
rtc_encoder_->Encode(rtc_frame, &frame_types));
}
TEST_F(RTCVideoEncoderTest, PreserveTimestamps) {
const webrtc::VideoCodecType codec_type = webrtc::kVideoCodecVP8;
CreateEncoder(codec_type);
webrtc::VideoCodec codec = GetDefaultCodec();
EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK, rtc_encoder_->InitEncode(&codec, 1, 12345));
const uint32_t rtp_timestamp = 1234567;
const uint32_t capture_time_ms = 3456789;
RegisterEncodeCompleteCallback(
base::BindOnce(&RTCVideoEncoderTest::VerifyTimestamp,
base::Unretained(this), rtp_timestamp, capture_time_ms));
EXPECT_CALL(*mock_vea_, Encode(_, _))
.WillOnce(Invoke(this, &RTCVideoEncoderTest::ReturnFrameWithTimeStamp));
const rtc::scoped_refptr<webrtc::I420Buffer> buffer =
webrtc::I420Buffer::Create(kInputFrameWidth, kInputFrameHeight);
FillFrameBuffer(buffer);
std::vector<webrtc::VideoFrameType> frame_types;
webrtc::VideoFrame rtc_frame = webrtc::VideoFrame::Builder()
.set_video_frame_buffer(buffer)
.set_timestamp_rtp(rtp_timestamp)
.set_timestamp_us(0)
.set_rotation(webrtc::kVideoRotation_0)
.build();
rtc_frame.set_timestamp_us(capture_time_ms * rtc::kNumMicrosecsPerMillisec);
// We need to set ntp_time_ms because it will be used to derive
// media::VideoFrame timestamp.
rtc_frame.set_ntp_time_ms(4567891);
EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK,
rtc_encoder_->Encode(rtc_frame, &frame_types));
}
TEST_F(RTCVideoEncoderTest, EncodeTemporalLayer) {
webrtc::VideoCodec tl_codec = GetDefaultTemporalLayerCodec();
CreateEncoder(tl_codec.codecType);
EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK,
rtc_encoder_->InitEncode(&tl_codec, 1, 12345));
size_t kNumEncodeFrames = 5u;
EXPECT_CALL(*mock_vea_, Encode(_, _))
.Times(kNumEncodeFrames)
.WillRepeatedly(Invoke(
this, &RTCVideoEncoderTest::ReturnTemporalLayerFrameWithVp9Metadata));
for (size_t i = 0; i < kNumEncodeFrames; i++) {
const rtc::scoped_refptr<webrtc::I420Buffer> buffer =
webrtc::I420Buffer::Create(kInputFrameWidth, kInputFrameHeight);
FillFrameBuffer(buffer);
std::vector<webrtc::VideoFrameType> frame_types;
EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK,
rtc_encoder_->Encode(webrtc::VideoFrame::Builder()
.set_video_frame_buffer(buffer)
.set_timestamp_rtp(0)
.set_timestamp_us(i)
.set_rotation(webrtc::kVideoRotation_0)
.build(),
&frame_types));
}
}
} // namespace blink
| 17,763 | 6,224 |
#include "TerrainBrush.h"
#include "../Kernel/Gateway.h"
#include "../Geometry/Ray3D.h"
#include "../Factories/TerrainVisuals.h"
#include "../Factories/TerrainPasture.h"
#include "../Factories/TerrainLogic.h"
#include "../Factories/WorldVisuals.h"
#include "../Factories/Meadow.h"
#include "../Factories/Water.h"
#include "../Managers/ManagersUtils.h"
#include "../Controllers/VillageModelController.h"
#include "../Controllers/TileController.h"
#include "../Databases/TerrainDatabase.h"
#include "../Databases/ModelDatabase.h"
#include "../Nodes/SpatialIndexNode.h"
#include "../Nodes/SpatialIndexCell.h"
#include "../Nodes/TransformGroup.h"
#include "../Tools/NodeIterator.h"
#include "../Tools/RangeIterator.h"
#include "../Strategies/BrushBitEStrategy.h"
#include "../Strategies/BrushBitDStrategy.h"
#include "../Containers/ocsort.h"
TerrainBrush::TerrainBrush()
{
strategies.append(new BrushBitEStrategy());
strategies.append(new BrushBitDStrategy());
reset();
}
void TerrainBrush::visit(SpatialIndexBaseNode* node)
{
pointAVLTree.clear();
if (intersect(&node->getBoundsDescriptor()))
{
NodeIterator iter(node->getFirstChild());
while (!iter.end())
{
iter.current()->accept(this);
iter++;
}
}
if (pointAVLTree.isEmpty())
return;
if (saveCollPoint)
{
AVLTreeTIterator <float, Tuple3f, 4> pointIter(pointAVLTree);
++pointIter;
cpoint = pointIter.value();
if (!enabled) return;
}
switch (type)
{
case BrushTypes::TILE:
editTiles();
break;
case BrushTypes::GRASS:
editGrass();
break;
case BrushTypes::WATER:
editWater();
break;
case BrushTypes::MODEL:
editModel();
break;
default:
break;
}
}
void TerrainBrush::visit(SpatialIndexNode* node)
{
if (intersect(&node->getBoundsDescriptor()))
{
NodeIterator iter(node->getFirstChild());
while (!iter.end())
{
iter.current()->accept(this);
iter++;
}
}
}
void TerrainBrush::visit(SpatialIndexCell* node)
{
BoundsDescriptor *bounds = &node->getBoundsDescriptor();
TileController* controller;
RangeIterator iter;
Tuple4f packet;
Tuple3f point;
float distance;
TerrainVisuals* visuals = Gateway::getTerrainVisuals();
TerrainDatabase* tdatabase = Gateway::getTerrainDatabase();
if (node->isVisible())
if (intersect(bounds))
{
if (showGuides)
{
glColor3ub(255, 255, 255);
bounds->render(BoundsDescriptor::AABB | BoundsDescriptor::WIRE);
}
if (enabled || saveCollPoint)
{
iter.set(visuals->getArea().x, node->getRange());
while (!iter.end())
{
controller = tdatabase->getController(iter.current());
packet = intersector.intersectTriangles(ray, controller->getVertices(), visuals->getTileIndices(0), 8);
if (1 == packet.w)
{
point.set(packet.x, packet.y, packet.z);
distance = point.getDistance(ray->getOrigin());
if (2.0f < distance)
pointAVLTree.insertKeyAndValue(distance, point);
}
iter++;
}
}
}
}
void TerrainBrush::editModel()
{
ModelDatabase *ndatabase, *sdatabase, *vdatabase, *cdatabase;
WorldVisuals* wVisuals;
//int ctrlindex;
GSElementInfo* info;
ModelController* controller;
AVLTreeTIterator <float, Tuple3f, 4> pointIter(pointAVLTree);
++pointIter;
cpoint = pointIter.value();
switch (layer)
{
case BrushLayers::CHARACTER:
if (constant)
{
info = Gateway::getActiveCharacterInfo();
if (info->name)
{
cdatabase = Gateway::getCharacterDatabase();
controller = cdatabase->instantiateModel(info->name);
controller->translateModel(cpoint.x, cpoint.y + 0.05f, cpoint.z);
TransformGroupNode* tgnode = controller->getTGNode();
tgnode->attach(Gateway::getSpatialCell(cpoint));
Gateway::getMapDescriptor().playerPositions.append(Tuple2f(cpoint.x, cpoint.z));
}
}
break;
case BrushLayers::CRITTER:
if (constant)
{
info = Gateway::getActiveCritterInfo();
if (info->name)
{
cdatabase = Gateway::getCritterDatabase();
controller = cdatabase->instantiateModel(info->name);
TransformGroupNode* tgnode = controller->getTGNode();
tgnode->attach(Gateway::getSpatialCell(cpoint));
float y = controller->getTransformGroup()->getBoundsDescriptor().getMinEndAABB().y;
Tuple3f cen = controller->getTransformGroup()->getBoundsDescriptor().getCenterAABB();
controller->translateModel(cpoint.x - cen.x, cpoint.y + 0.05f - y, cpoint.z - cen.z);
wVisuals = Gateway::getWorldVisuals();
WorldObject worldObject;
worldObject.flags = 0;
worldObject.name = info->name;
worldObject.type = WorldObjectTypes::CRITTER;
worldObject.orientation = 0.0f;
worldObject.position.set(cpoint.x, cpoint.y + 0.05f, cpoint.z);
worldObject.windFactor = 0.0f;
wVisuals->addObject(worldObject);
}
}
break;
case BrushLayers::NATURE:
if (constant)
{
info = Gateway::getActiveNatureInfo();
if (info->name)
{
ndatabase = Gateway::getNatureDatabase();
controller = ndatabase->instantiateModel(info->name);
controller->translateModel(cpoint.x, cpoint.y + 0.05f, cpoint.z);
TransformGroupNode* tgnode = controller->getTGNode();
tgnode->attach(Gateway::getSpatialCell(cpoint));
///cannot subtract y because that would cause a problem with canopy models
wVisuals = Gateway::getWorldVisuals();
WorldObject worldObject;
worldObject.flags = 0;
worldObject.name = info->name;
worldObject.type = WorldObjectTypes::NATURE;
worldObject.orientation = 0.79f;
worldObject.position.set(cpoint.x, cpoint.y + 0.05f, cpoint.z);
worldObject.windFactor = info->windFactor;
wVisuals->addObject(worldObject);
}
}
break;
case BrushLayers::STRUCTURE:
if (constant)
{
info = Gateway::getActiveStructureInfo();
if (info->name)
{
sdatabase = Gateway::getStructureDatabase();
controller = sdatabase->instantiateModel(info->name);
TransformGroupNode* tgnode = controller->getTGNode();
tgnode->attach(Gateway::getSpatialCell(cpoint));
float y = controller->getTransformGroup()->getBoundsDescriptor().getMinEndAABB().y;
Tuple3f cen = controller->getTransformGroup()->getBoundsDescriptor().getCenterAABB();
controller->translateModel(cpoint.x - cen.x, cpoint.y + 0.05f - y, cpoint.z - cen.z);
wVisuals = Gateway::getWorldVisuals();
WorldObject worldObject;
worldObject.flags = 0;
worldObject.name = info->name;
worldObject.type = WorldObjectTypes::STRUCTURE;
worldObject.orientation = 0.0f;
worldObject.position.set(cpoint.x, cpoint.y + 0.05f, cpoint.z);
worldObject.windFactor = 0.0f;
wVisuals->addObject(worldObject);
}
}
break;
case BrushLayers::VILLAGE:
if (constant)
{
info = Gateway::getActiveVillageInfo();
if (info->name)
{
vdatabase = Gateway::getVillageDatabase();
VillageModelController* villageController = (VillageModelController*) vdatabase->instantiateModel(info->name);
villageController->setPopulation(info->population);
villageController->setMaxPopulation(info->maxpopulation);
float y = villageController->getTransformGroup()->getBoundsDescriptor().getMinEndAABB().y;
Tuple3f cen = villageController->getTransformGroup()->getBoundsDescriptor().getCenterAABB();
villageController->translateModel(cpoint.x - cen.x, cpoint.y + 0.05f - y, cpoint.z - cen.z);
}
}
break;
default:
break;
}
}
void TerrainBrush::editTiles()
{
if (layer != BrushLayers::TILE)
return;
TileController *controller;
Tuple3f *verts;
Tuple4ub *cols;
float s, y, d;
unsigned int lflag;
char col;
RangeIterator tileiter;
TerrainVisuals* visuals = Gateway::getTerrainVisuals();
TerrainLogic* terrainLogic = Gateway::getTerrainLogic();
TerrainDatabase* tdatabase = Gateway::getTerrainDatabase();
AVLTreeTIterator <float, Tuple3f, 4> pointIter(pointAVLTree);
if (mode == BrushModes::FILL)
{
if (constant)
if (txcoordsIndex >= 0)
for (unsigned int i = 0; i < tdatabase->getControllerCount(); i++)
tdatabase->changeTileTexture(level, txcoordsIndex, i, !tdatabase->getController(i)->isVisible());
return;
}
++pointIter;
cpoint = pointIter.value();
Tuple2i area(visuals->getArea());
unsigned int xOff = clamp(int(cpoint.x - radius), 0, area.y - 1);
unsigned int yOff = clamp(int(cpoint.z - radius), 0, area.x - 1);
unsigned int zOff = clamp(int(cpoint.x + radius), 0, area.y - 1);
unsigned int wOff = clamp(int(cpoint.z + radius), 0, area.x - 1);
tileiter.set(area.x, Tuple4i(yOff, xOff, wOff, zOff));
glPointSize(2.0f);
glColor3ub(255, 200, 0);
glBegin(GL_POINTS);
while (!tileiter.end())
{
controller = tdatabase->getController(tileiter.current());
verts = controller->getVertices();
cols = controller->getColors();
switch (mode)
{
case BrushModes::ROTATE90:
if (constant)
controller->setFlags(TileFlags::TEXTURE_ROTATE90);
break;
case BrushModes::ROTATE180:
if (constant)
controller->setFlags(TileFlags::TEXTURE_ROTATE180);
break;
case BrushModes::ROTATE270:
if (constant)
controller->setFlags(TileFlags::TEXTURE_ROTATE270);
break;
case BrushModes::MIRRORX:
if (constant)
controller->setFlags(TileFlags::TEXTURE_MIRRORX);
break;
case BrushModes::MIRRORY:
if (constant)
controller->setFlags(TileFlags::TEXTURE_MIRRORY);
break;
//case BrushModes::VISIBLE:
//
// if (constant)
// controller->setFlags(TileFlags::TILE_VISIBLE);
//
// break;
//
//case BrushModes::QUAD0DIAGONAL:
//
// if (constant)
// controller->setFlags(TileFlags::QUAD0_DIAGONAL);
//
// break;
//
//case BrushModes::QUAD1DIAGONAL:
//
// if (constant)
// controller->setFlags(TileFlags::QUAD1_DIAGONAL);
//
// break;
//
//case BrushModes::QUAD2DIAGONAL:
//
// if (constant)
// controller->setFlags(TileFlags::QUAD2_DIAGONAL);
//
// break;
//
//case BrushModes::QUAD3DIAGONAL:
//
// if (constant)
// controller->setFlags(TileFlags::QUAD3_DIAGONAL);
//
// break;
//
//case BrushModes::DYNAMICMIX:
//
// if (constant)
// controller->setFlags(TileFlags::DYNAMIC_MIX);
//
// break;
//
//case BrushModes::NOTESSELATE:
//
// if (constant)
// controller->setFlags(TileFlags::TILE_NOTESSELLATE);
//
// break;
case BrushModes::RAISE:
for (unsigned int v = 0; v < 9; v++)
{
d = verts[v].getDistance(cpoint);
if (d <= radius)
{
s = -(d * d) / radius;
verts[v].y += time * strength * 6 * exp(s);
glVertex3f(verts[v].x, verts[v].y + 0.1f, verts[v].z);
}
}
break;
case BrushModes::LOWER:
for (unsigned int v = 0; v < 9; v++)
{
d = verts[v].getDistance(cpoint);
if (d <= radius)
{
s = -(d * d) / radius;
verts[v].y += time * -strength * 6 * exp(s);
glVertex3f(verts[v].x, verts[v].y + 0.1f, verts[v].z);
}
}
break;
case BrushModes::ERASE:
for (unsigned int c = 0; c < 9; c++)
{
d = verts[c].getDistance(cpoint);
if (d <= radius)
{
s = -(d * d) / radius;
y = time * strength * 3 * exp(s);
col = (char)(y * 255);
cols[c].w -= cols[c].w <= col ? 0 : col;
glVertex3f(verts[c].x, verts[c].y + 0.1f, verts[c].z);
}
}
break;
case BrushModes::RESTORE:
for (unsigned int c = 0; c < 9; c++)
{
d = verts[c].getDistance(cpoint);
if (d <= radius)
{
s = -(d * d) / radius;
y = time * strength * 3 * exp(s);
cols[c].w += (char)((255 - cols[c].w) * y);
glVertex3f(verts[c].x, verts[c].y + 0.1f, verts[c].z);
}
}
break;
case BrushModes::BURN:
for (unsigned int c = 0; c < 9; c++)
{
d = verts[c].getDistance(cpoint);
if (d <= radius)
{
s = -(d * d) / radius;
y = time * strength * 2 * exp(s);
col = (char)(y * 255);
cols[c].x -= cols[c].x < col ? 0 : col;
cols[c].y -= cols[c].y < col ? 0 : col;
cols[c].z -= cols[c].z < col ? 0 : col;
glVertex3f(verts[c].x, verts[c].y + 0.1f, verts[c].z);
}
}
break;
case BrushModes::HEAL:
for (unsigned int c = 0; c < 9; c++)
{
d = verts[c].getDistance(cpoint);
if (d <= radius)
{
s = -(d * d) / radius;
y = time * strength * 2 * exp(s);
cols[c].x += (char) round((255 - cols[c].x) * y);
cols[c].y += (char) round((255 - cols[c].y) * y);
cols[c].z += (char) round((255 - cols[c].z) * y);
glVertex3f(verts[c].x, verts[c].y + 0.1f, verts[c].z);
}
}
break;
case BrushModes::PAINT:
if (verts[4].getDistance(cpoint) <= radius)
tdatabase->changeTileTexture(level, txcoordsIndex, tileiter.current());
break;
case BrushModes::MARKER:
for (unsigned int c = 0; c < 9; c++)
{
d = verts[c].getDistance(cpoint);
if (d <= radius)
{
y = time * opacity;
col = (char)(y * 255);
cols[c].x -= cols[c].x <= col ? 0 : col;
cols[c].y -= cols[c].y <= col ? 0 : col;
cols[c].z -= cols[c].z <= col ? 0 : col;
glVertex3f(verts[c].x, verts[c].y + 0.1f, verts[c].z);
}
}
break;
case BrushModes::PASTEL:
for (unsigned int c = 0; c < 9; c++)
{
d = verts[c].getDistance(cpoint);
if (d <= radius)
{
cols[c].x = char(255 * opacity);
cols[c].y = char(255 * opacity);
cols[c].z = char(255 * opacity);
glVertex3f(verts[c].x, verts[c].y + 0.1f, verts[c].z);
}
}
break;
case BrushModes::ERASETILE:
if (verts[4].getDistance(cpoint) <= radius)
tdatabase->changeTileTexture(level, -1, tileiter.current());
break;
case BrushModes::LOGIC:
if (logicflag != TileTypes::GRASSFIELD)
if (verts[4].getDistance(cpoint) <= radius)
{
lflag = terrainLogic->getFlags(tileiter.current());
terrainLogic->setFlags(tileiter.current(), strategy->getType((lflag & MASK_FLAGS), logicflag));
}
break;
case BrushModes::FLAG:
if (verts[4].getDistance(cpoint) <= radius)
{
lflag = terrainLogic->getFlags(tileiter.current());
terrainLogic->setFlags(tileiter.current(), strategy->getFlags(lflag, logicflag));
}
break;
case BrushModes::ADVANCED:
if (verts[4].getDistance(cpoint) <= radius)
{
BrushMatrixDescriptor* descriptor = &Gateway::getBrushMatrixDescriptor();
if (!descriptor->tileList.isEmpty())
{
int col = tileiter.current() - int(tileiter.current()/area.y) * area.y;
int row = int(tileiter.current()/area.y);
int mx = col % descriptor->dimensions.x;
int my = row % descriptor->dimensions.y;
Tile *mtile = &descriptor->tileList(my * descriptor->dimensions.x + mx);
tdatabase->changeTileTexture(level, mtile->textureID[0], tileiter.current());
controller->clearFlags();
controller->setFlags(mtile->flags);
}
}
break;
case BrushModes::POINTER:
break;
default:
break;
}
tileiter++;
}
glEnd();
glPointSize(1.0f);
if (mode < BrushModes::PAINT)
Gateway::updateSpatialIndex(cpoint, radius);
}
void TerrainBrush::editGrass()
{
if (layer != BrushLayers::GRASS && mode != BrushModes::LOGIC && type != BrushTypes::GRASS)
return;
if (meadowname.isBlank())
return;
Tuple3f *verts;
RangeIterator tileiter;
GrassPatch* patch;
Meadow* meadow;
int meadowindex;
unsigned int lflag;
TerrainVisuals* visuals = Gateway::getTerrainVisuals();
TerrainDatabase* tdatabase = Gateway::getTerrainDatabase();
TerrainPasture* terrainPasture = Gateway::getTerrainPasture();
TerrainLogic* terrainLogic = Gateway::getTerrainLogic();
AVLTreeTIterator <float, Tuple3f, 4> pointIter(pointAVLTree);
++pointIter;
cpoint = pointIter.value();
Tuple2i area(visuals->getArea());
unsigned int xOff = clamp(int(cpoint.x - radius), 0, area.y - 1);
unsigned int yOff = clamp(int(cpoint.z - radius), 0, area.x - 1);
unsigned int zOff = clamp(int(cpoint.x + radius), 0, area.y - 1);
unsigned int wOff = clamp(int(cpoint.z + radius), 0, area.x - 1);
tileiter.set(area.x, Tuple4i(yOff, xOff, wOff, zOff));
while (!tileiter.end())
{
verts = tdatabase->getController(tileiter.current())->getVertices();
if (verts[4].getDistance(cpoint) <= radius)
{
meadowindex = terrainPasture->getMeadowIndex(meadowname);
meadow = terrainPasture->getMeadow(meadowindex);
if (!meadow->containsTileIndex(tileiter.current()))
{
if (patch = terrainPasture->createPatch(meadowindex))
{
patch->position.set(tileiter.current() - int(tileiter.current()/area.y) * area.y, int(tileiter.current()/area.y));
patch->range.set(0x00000000,0x00000000);
patch->color.set(0xff);
}
lflag = terrainLogic->getFlags(tileiter.current());
terrainLogic->setFlags(tileiter.current(), (lflag & MASK_FLAGS) | (TileTypes::GRASSFIELD << 27));
//terrainLogic->setFlags(tileiter.current(), strategy->getType((lflag & MASK_FLAGS), logicflag));
meadow->addTileIndex(tileiter.current());
}
}
tileiter++;
}
}
bool TerrainBrush::intersect(BoundsDescriptor *bounds)
{
Tuple3f ro;
Tuple3f rd;
Tuple3f d;
Tuple3f a;
Tuple3f e;
Tuple3f c;
ro = ray->getOrigin();
rd = ray->getDestination();
d = (rd - ro) * 0.5f;
a.set(fabsf(d.x), fabsf(d.y), fabsf(d.z));
e = bounds->getExtents();
c = ro + d - bounds->getCenterAABB();
if (fabsf(c.x) > e.x + a.x || fabsf(c.y) > e.y + a.y || fabsf(c.z) > e.z + a.z)
return false;
if (fabsf(d.y * c.z - d.z * c.y) > (e.y * a.z + e.z * a.y) ||
fabsf(d.z * c.x - d.x * c.z) > (e.z * a.x + e.x * a.z) ||
fabsf(d.x * c.y - d.y * c.x) > (e.x * a.y + e.y * a.x))
return false;
return true;
}
void TerrainBrush::editWater()
{
if (layer != BrushLayers::WATER)
return;
if (!waterModel)
return;
Tuple3f point;
float distance;
Tuple4f packet;
Array < DistanceObject<unsigned int> > distObjs;
DistanceObject <unsigned int> object;
AVLTreeTIterator <float, Tuple3f, 4> pointIter(pointAVLTree);
++pointIter;
cpoint = pointIter.value();
switch (mode)
{
case BrushModes::VERTEX:
{
if (constant)
waterModel->addVertex(Tuple3f(cpoint.x, cpoint.y + 0.05f, cpoint.z));
}
break;
case BrushModes::TRIANGLE:
{
if (constant)
{
for (unsigned int i = 0; i < waterModel->getTriangleCount(); i++)
{
packet = intersector.intersectTriangles(ray, waterModel->getVertices(), &waterModel->getTriangles()[i], 1);
if (1 == packet.w)
{
point.set(packet.x, packet.y, packet.z);
distance = point.getDistance(ray->getOrigin());
if (2.0f < distance)
{
object.set(distance, i);
distObjs.append(object);
}
}
}
}
if (!distObjs.isEmpty())
{
OCQuickSort(distObjs, 0, distObjs.length());
waterModel->removeTriangle(distObjs(0).getObject());
}
break;
}
}
}
void TerrainBrush::setRay(Ray3D* r)
{
ray = r;
}
void TerrainBrush::setPaintIndex(int index)
{
txcoordsIndex = index;
}
void TerrainBrush::setPaintLayer(int layer)
{
level = layer;
}
void TerrainBrush::enable(bool e)
{
enabled = e;
}
void TerrainBrush::enableConstant(bool enable)
{
constant = enable;
}
void TerrainBrush::setRadius(float r)
{
radius = r;
}
void TerrainBrush::update(float tick)
{
time = tick;
}
void TerrainBrush::setStrength(float s)
{
strength = s;
}
void TerrainBrush::setOpacity(float o)
{
opacity = o;
}
void TerrainBrush::setLogic(unsigned int flags)
{
logicflag = flags;
}
void TerrainBrush::setMode(int m)
{
mode = m;
}
unsigned int TerrainBrush::getMode()
{
return mode;
}
void TerrainBrush::setType(int m)
{
type = m;
}
unsigned int TerrainBrush::getType()
{
return type;
}
void TerrainBrush::setLayer(int m)
{
layer = m;
}
int TerrainBrush::getLayer()
{
return layer;
}
void TerrainBrush::enableGuides(bool enable)
{
showGuides = enable;
}
void TerrainBrush::setMeadowName(const char* name)
{
meadowname = name;
}
void TerrainBrush::setNatureTransformGroup(TransformGroup* group)
{
natureRoot = group;
}
void TerrainBrush::setCharacterTransformGroup(TransformGroup* group)
{
characterRoot = group;
}
void TerrainBrush::setCritterTransformGroup(TransformGroup* group)
{
critterRoot = group;
}
void TerrainBrush::setStructureTransformGroup(TransformGroup* group)
{
structureRoot = group;
}
void TerrainBrush::setVillageTransformGroup(TransformGroup* group)
{
villageRoot = group;
}
Tuple4f TerrainBrush::getCollisionPoint()
{
if (pointAVLTree.isEmpty())
return Tuple4f(0,0,0,0);
return Tuple4f(cpoint.x, cpoint.y, cpoint.z, 1);
}
void TerrainBrush::saveCollisionPoint(bool save)
{
saveCollPoint = save;
}
void TerrainBrush::drawCollisionMark()
{
}
void TerrainBrush::enableLogicFlag(bool enable)
{
if (enable)
strategy = strategies(0);
else
strategy = strategies(1);
}
void TerrainBrush::setWaterModel(Water* water)
{
waterModel = water;
}
void TerrainBrush::reset()
{
natureRoot = 0;
characterRoot = 0;
structureRoot = 0;
critterRoot = 0;
villageRoot = 0;
waterModel = 0;
showGuides = false;
enabled = false;
constant = false;
txcoordsIndex = -1;
level = 0;
meadowname.clear();
radius = 2.0f;
strength = 0.0f;
time = 0.0f;
opacity = 0.0f;
saveCollPoint = false;
logicflag = TileLogic::FLAG_NONE | (TileTypes::UNUSED << 27);
mode = BrushModes::POINTER;
type = BrushTypes::NONE;
layer = BrushLayers::NONE;
strategy = strategies(0);
}
TerrainBrush::~TerrainBrush()
{
strategies.clear();
} | 25,545 | 8,929 |
#ifndef _DEF_IDEMO_HPP
#define _DEF_IDEMO_HPP
#include "src/Omgl3D.hpp"
#include <SFML/Window.hpp>
class IDemo
{
public:
IDemo() : width_screen(800), height_screen(600), running(true)
{
}
virtual ~IDemo() {}
virtual void yourEvent(float elapsedtime, const sf::Event & event) {}
void events(float elapsedtime)
{
sf::Event event;
while( window.GetEvent(event) )
{
if( event.Type == sf::Event::Closed )
{
running = false;
}
if( event.Type == sf::Event::KeyPressed )
{
switch(event.Key.Code)
{
case sf::Key::Escape:
running = false;
break;
default:
break;
}
}
yourEvent(elapsedtime, event);
}
const sf::Input& Input = window.GetInput();
bool LeftKeyDown = Input.IsKeyDown(sf::Key::Left);
bool RightKeyDown = Input.IsKeyDown(sf::Key::Right);
bool UpKeyDown = Input.IsKeyDown(sf::Key::Up);
bool DownKeyDown = Input.IsKeyDown(sf::Key::Down);
bool QKeyDown = Input.IsKeyDown(sf::Key::Q);
bool DKeyDown = Input.IsKeyDown(sf::Key::D);
bool ZKeyDown = Input.IsKeyDown(sf::Key::Z);
bool SKeyDown = Input.IsKeyDown(sf::Key::S);
OMGL3D::MATH::Quaternionf rotate, rotate_x, rotate_y, rotate_z;
OMGL3D::MATH::Vector3f vector;
if( LeftKeyDown )
{
rotate_x = OMGL3D::MATH::Quaternionf::CreateQuaternion(0, 0, 1, -20*elapsedtime);
}
if( RightKeyDown )
{
rotate_x = OMGL3D::MATH::Quaternionf::CreateQuaternion(0, 0, 1, 20*elapsedtime);
}
if( UpKeyDown )
{
rotate_z = OMGL3D::MATH::Quaternionf::CreateQuaternion(1, 0, 0, -20*elapsedtime);
}
if( DownKeyDown )
{
rotate_z = OMGL3D::MATH::Quaternionf::CreateQuaternion(1, 0, 0, 20*elapsedtime);
}
if( QKeyDown )
{
rotate_y = OMGL3D::MATH::Quaternionf::CreateQuaternion(0, 1, 0, -20*elapsedtime);
}
if( DKeyDown )
{
rotate_y = OMGL3D::MATH::Quaternionf::CreateQuaternion(0, 1, 0, 20*elapsedtime);
}
if( ZKeyDown )
{
vector.z = -10*elapsedtime;
}
if( SKeyDown )
{
vector.z = 10*elapsedtime;
}
rotate = rotate_x * rotate_y * rotate_z;
//position = rotate.getMatrix4();
position *= rotate.GetMatrix4();
position *= vector;
}
virtual void init()=0;
virtual void run()=0;
void start()
{
init();
sf::Clock clock;
while( running )
{
elapsedtime = clock.GetElapsedTime();
clock.Reset();
events(elapsedtime);
run();
}
}
protected:
unsigned int width_screen, height_screen;
bool running;
float elapsedtime;
sf::Window window;
OMGL3D::MATH::Matrix4f position;
};
#endif
| 3,139 | 1,092 |
// ============================================================================
// Copyright (c) 2011-2012 J.C. Moyer
//
// 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 "TVShader.h"
#include "TerminalRenderer.h"
#include "TProgram.h"
#include <GL/glew.h>
namespace halt {
const char* TVGLSLShaderSource =
"#version 120 \n"
"uniform mat4 tvs_Projection; \n"
" \n"
"attribute vec2 tvs_TexCoord; \n"
"attribute vec4 tvs_Vertex; \n"
"attribute vec4 tvs_Color; \n"
" \n"
"varying vec2 tfs_TexCoord; \n"
"varying vec4 tfs_Color; \n"
" \n"
"void main() { \n"
" gl_Position = tvs_Projection * tvs_Vertex; \n"
" tfs_TexCoord = tvs_TexCoord; \n"
" tfs_Color = tvs_Color; \n"
"} \n";
const char* TVS_PROJECTION_MAT = "tvs_Projection";
const char* VERTEX_ATTRIBUTE_NAME = "tvs_Vertex";
const char* TEXCOORD_ATTRIBUTE_NAME = "tvs_TexCoord";
const char* COLOR_ATTRIBUTE_NAME = "tvs_Color";
TVShader::TVShader(TProgram* owner) {
handle = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(handle, 1, &TVGLSLShaderSource, 0);
glCompileShader(handle);
}
TVShader::~TVShader() {
if (handle) glDeleteShader(handle);
}
void TVShader::Enable(bool state, unsigned int vertex_attrib, unsigned int tex_coord_atrrib, unsigned int color_attrib) {
if (state) {
glEnableVertexAttribArray(vertex_attrib);
glVertexAttribPointer(vertex_attrib, 2, GL_UNSIGNED_SHORT, 0, sizeof(TerminalVertex), (void*)0);
glEnableVertexAttribArray(tex_coord_atrrib);
glVertexAttribPointer(tex_coord_atrrib, 2, GL_FLOAT, 0, sizeof(TerminalVertex), (void*)4);
glEnableVertexAttribArray(color_attrib);
glVertexAttribPointer(color_attrib, 4, GL_UNSIGNED_BYTE, 1, sizeof(TerminalVertex), (void*)12);
} else {
glDisableVertexAttribArray(vertex_attrib);
glDisableVertexAttribArray(tex_coord_atrrib);
glDisableVertexAttribArray(color_attrib);
}
}
}
| 3,765 | 1,207 |
#include "MeanNormalLikelihood.h"
// MeanNormalLikelihood::MeanNormalLikelihood()
//
// PURPOSE:
// Derived class onstructor.
//
// INPUT:
// observations: array containing the dependent variable values
// uncertainties: array containing the uncertainties of the observations
// model: object specifying the model to be used.
//
MeanNormalLikelihood::MeanNormalLikelihood(const RefArrayXd observations, const RefArrayXd uncertainties, Model &model)
: Likelihood(observations, model),
uncertainties(uncertainties)
{
double normalizeFactor;
assert(observations.size() == uncertainties.size());
normalizeFactor = sqrt(observations.size()/uncertainties.pow(-2).sum());
normalizedUncertainties = uncertainties/normalizeFactor;
weights = normalizedUncertainties.pow(-2);
} // END MeanNormalLikelihood::MeanNormalLikelihood()
// MeanNormalLikelihood::~MeanNormalLikelihood()
//
// PURPOSE:
// Derived class destructor.
//
MeanNormalLikelihood::~MeanNormalLikelihood()
{
} // END MeanNormalLikelihood::~MeanNormalLikelihood()
// MeanNormalLikelihood::getNormalizedUncertainties();
//
// PURPOSE:
// Get private data member normalizedUncertainties.
//
// OUTPUT:
// uncertainties: one-dimensional array containing the
// uncertainties on the dependent variable values.
//
ArrayXd MeanNormalLikelihood::getNormalizedUncertainties()
{
return normalizedUncertainties;
} // END MeanNormalLikelihood::getNormalizedUncertainties()
// MeanNormalLikelihood::logValue()
//
// PURPOSE:
// Compute the natural logarithm of the mean normal likelihood for
// a given set of observations, uncertainties and predictions.
// The mean normal likelihood is a normal likelihood whose uncertainties
// have been integrated away by means of a Jeffrey's prior.
// For more details cf. Froehlich H.-E. et al. 2009, A&A, 506, 263.
//
// INPUT:
// modelParameters: a one-dimensional array containing the actual
// values of the free parameters that describe the model.
//
// OUTPUT:
// a double number containing the natural logarithm of the
// mean likelihood
//
double MeanNormalLikelihood::logValue(RefArrayXd modelParameters)
{
unsigned long n = observations.size();
double lambda0;
double lambda;
ArrayXd argument;
ArrayXd predictions;
predictions.resize(n);
predictions.setZero();
model.predict(predictions, modelParameters);
argument = (observations - predictions);
argument = argument.square()*weights;
lambda0 = lgammal(n/2.) - log(2) - (n/2.)*log(Functions::PI) + 0.5*weights.log().sum();
lambda = lambda0 - (n/2.)*log(argument.sum());
return lambda;
}
| 2,738 | 870 |
/****************************************************************************/
// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo
// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others.
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0/
// This Source Code may also be made available under the following Secondary
// Licenses when the conditions for such availability set forth in the Eclipse
// Public License 2.0 are satisfied: GNU General Public License, version 2
// or later which is available at
// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
/****************************************************************************/
/// @file GNEBusStop.cpp
/// @author Pablo Alvarez Lopez
/// @date Nov 2015
///
// A lane area vehicles can halt at (GNE version)
/****************************************************************************/
#include <foreign/fontstash/fontstash.h>
#include <netedit/GNENet.h>
#include <netedit/GNEUndoList.h>
#include <netedit/GNEViewNet.h>
#include <netedit/changes/GNEChange_Attribute.h>
#include <utils/options/OptionsCont.h>
#include <utils/gui/globjects/GLIncludes.h>
#include <utils/gui/div/GLHelper.h>
#include <utils/vehicle/SUMORouteHandler.h>
#include "GNEBusStop.h"
// ===========================================================================
// method definitions
// ===========================================================================
GNEBusStop::GNEBusStop(const std::string& id, GNELane* lane, GNENet* net, const double startPos, const double endPos, const int parametersSet,
const std::string& name, const std::vector<std::string>& lines, int personCapacity, double parkingLength, bool friendlyPosition, bool blockMovement) :
GNEStoppingPlace(id, net, GLO_BUS_STOP, SUMO_TAG_BUS_STOP, lane, startPos, endPos, parametersSet, name, friendlyPosition, blockMovement),
myLines(lines),
myPersonCapacity(personCapacity),
myParkingLength(parkingLength)
{ }
GNEBusStop::~GNEBusStop() {}
void
GNEBusStop::updateGeometry() {
// Get value of option "lefthand"
double offsetSign = OptionsCont::getOptions().getBool("lefthand") ? -1 : 1;
// Update common geometry of stopping place
setStoppingPlaceGeometry(getParentLanes().front()->getParentEdge()->getNBEdge()->getLaneWidth(getParentLanes().front()->getIndex()) * 0.5);
// Obtain a copy of the shape
PositionVector tmpShape = myAdditionalGeometry.getShape();
// Move shape to side
tmpShape.move2side(myNet->getViewNet()->getVisualisationSettings().stoppingPlaceSettings.stoppingPlaceSignOffset * offsetSign);
// Get position of the sign
mySignPos = tmpShape.getLineCenter();
// update block icon position
myBlockIcon.updatePositionAndRotation();
// update child demand elements geometry
for (const auto& i : getChildDemandElements()) {
// special case for person trips
if (i->getTagProperty().isPersonTrip()) {
// update previous and next person plan
GNEDemandElement* previousDemandElement = i->getParentDemandElements().front()->getPreviousChildDemandElement(i);
if (previousDemandElement) {
previousDemandElement->updatePartialGeometry(getParentLanes().front());
}
GNEDemandElement* nextDemandElement = i->getParentDemandElements().front()->getNextChildDemandElement(i);
if (nextDemandElement) {
nextDemandElement->updatePartialGeometry(getParentLanes().front());
}
}
i->updatePartialGeometry(getParentLanes().front());
}
}
Boundary
GNEBusStop::getCenteringBoundary() const {
return myAdditionalGeometry.getShape().getBoxBoundary().grow(10);
}
void
GNEBusStop::drawGL(const GUIVisualizationSettings& s) const {
// Obtain exaggeration of the draw
const double busStopExaggeration = s.addSize.getExaggeration(s, this);
// first check if additional has to be drawn
if (s.drawAdditionals(busStopExaggeration) && myNet->getViewNet()->getDataViewOptions().showAdditionals()) {
// declare colors
RGBColor baseColor, signColor;
// set colors
if (mySpecialColor) {
baseColor = *mySpecialColor;
signColor = baseColor.changedBrightness(-32);
} else if (drawUsingSelectColor()) {
baseColor = s.colorSettings.selectedAdditionalColor;
signColor = baseColor.changedBrightness(-32);
} else {
baseColor = s.stoppingPlaceSettings.busStopColor;
signColor = s.stoppingPlaceSettings.busStopColorSign;
}
// Start drawing adding an gl identificator
glPushName(getGlID());
// Add a draw matrix
glPushMatrix();
// translate to front
myNet->getViewNet()->drawTranslateFrontAttributeCarrier(this, GLO_BUS_STOP);
// set base color
GLHelper::setColor(baseColor);
// Draw the area using shape, shapeRotations, shapeLengths and value of exaggeration
GNEGeometry::drawGeometry(myNet->getViewNet(), myAdditionalGeometry, s.stoppingPlaceSettings.busStopWidth * busStopExaggeration);
// draw detail
if (s.drawDetail(s.detailSettings.stoppingPlaceDetails, busStopExaggeration)) {
// draw lines
drawLines(s, myLines, baseColor);
// draw sign
drawSign(s, busStopExaggeration, baseColor, signColor, "H");
// draw lock icon
myBlockIcon.drawIcon(s, busStopExaggeration);
}
// pop draw matrix
glPopMatrix();
// Draw name if isn't being drawn for selecting
drawName(getPositionInView(), s.scale, s.addName);
// Pop name
glPopName();
// draw connection betwen access
drawConnectionAccess(s, baseColor);
// draw additional name
drawAdditionalName(s);
// check if dotted contours has to be drawn
if (s.drawDottedContour() || myNet->getViewNet()->getInspectedAttributeCarrier() == this) {
GNEGeometry::drawDottedContourShape(true, s, myAdditionalGeometry.getShape(), s.stoppingPlaceSettings.busStopWidth, busStopExaggeration);
}
if (s.drawDottedContour() || myNet->getViewNet()->getFrontAttributeCarrier() == this) {
GNEGeometry::drawDottedContourShape(false, s, myAdditionalGeometry.getShape(), s.stoppingPlaceSettings.busStopWidth, busStopExaggeration);
}
// draw child demand elements
for (const auto& demandElement : getChildDemandElements()) {
if (!demandElement->getTagProperty().isPlacedInRTree()) {
demandElement->drawGL(s);
}
}
}
}
std::string
GNEBusStop::getAttribute(SumoXMLAttr key) const {
switch (key) {
case SUMO_ATTR_ID:
return getID();
case SUMO_ATTR_LANE:
return getParentLanes().front()->getID();
case SUMO_ATTR_STARTPOS:
if (myParametersSet & STOPPINGPLACE_STARTPOS_SET) {
return toString(myStartPosition);
} else {
return "";
}
case SUMO_ATTR_ENDPOS:
if (myParametersSet & STOPPINGPLACE_ENDPOS_SET) {
return toString(myEndPosition);
} else {
return "";
}
case SUMO_ATTR_NAME:
return myAdditionalName;
case SUMO_ATTR_FRIENDLY_POS:
return toString(myFriendlyPosition);
case SUMO_ATTR_LINES:
return joinToString(myLines, " ");
case SUMO_ATTR_PERSON_CAPACITY:
return toString(myPersonCapacity);
case SUMO_ATTR_PARKING_LENGTH:
return toString(myParkingLength);
case GNE_ATTR_BLOCK_MOVEMENT:
return toString(myBlockMovement);
case GNE_ATTR_SELECTED:
return toString(isAttributeCarrierSelected());
case GNE_ATTR_PARAMETERS:
return getParametersStr();
default:
throw InvalidArgument(getTagStr() + " doesn't have an attribute of type '" + toString(key) + "'");
}
}
void
GNEBusStop::setAttribute(SumoXMLAttr key, const std::string& value, GNEUndoList* undoList) {
if (value == getAttribute(key)) {
return; //avoid needless changes, later logic relies on the fact that attributes have changed
}
switch (key) {
case SUMO_ATTR_ID:
case SUMO_ATTR_LANE:
case SUMO_ATTR_STARTPOS:
case SUMO_ATTR_ENDPOS:
case SUMO_ATTR_NAME:
case SUMO_ATTR_FRIENDLY_POS:
case SUMO_ATTR_LINES:
case SUMO_ATTR_PERSON_CAPACITY:
case SUMO_ATTR_PARKING_LENGTH:
case GNE_ATTR_BLOCK_MOVEMENT:
case GNE_ATTR_SELECTED:
case GNE_ATTR_PARAMETERS:
undoList->p_add(new GNEChange_Attribute(this, key, value));
break;
default:
throw InvalidArgument(getTagStr() + " doesn't have an attribute of type '" + toString(key) + "'");
}
}
bool
GNEBusStop::isValid(SumoXMLAttr key, const std::string& value) {
switch (key) {
case SUMO_ATTR_ID:
return isValidAdditionalID(value);
case SUMO_ATTR_LANE:
if (myNet->retrieveLane(value, false) != nullptr) {
return true;
} else {
return false;
}
case SUMO_ATTR_STARTPOS:
if (value.empty()) {
return true;
} else if (canParse<double>(value)) {
return SUMORouteHandler::isStopPosValid(parse<double>(value), myEndPosition, getParentLanes().front()->getParentEdge()->getNBEdge()->getFinalLength(), POSITION_EPS, myFriendlyPosition);
} else {
return false;
}
case SUMO_ATTR_ENDPOS:
if (value.empty()) {
return true;
} else if (canParse<double>(value)) {
return SUMORouteHandler::isStopPosValid(myStartPosition, parse<double>(value), getParentLanes().front()->getParentEdge()->getNBEdge()->getFinalLength(), POSITION_EPS, myFriendlyPosition);
} else {
return false;
}
case SUMO_ATTR_NAME:
return SUMOXMLDefinitions::isValidAttribute(value);
case SUMO_ATTR_FRIENDLY_POS:
return canParse<bool>(value);
case SUMO_ATTR_LINES:
return canParse<std::vector<std::string> >(value);
case SUMO_ATTR_PERSON_CAPACITY:
return canParse<int>(value) && (parse<int>(value) > 0 || parse<int>(value) == -1);
case SUMO_ATTR_PARKING_LENGTH:
return canParse<double>(value) && (parse<double>(value) >= 0);
case GNE_ATTR_BLOCK_MOVEMENT:
return canParse<bool>(value);
case GNE_ATTR_SELECTED:
return canParse<bool>(value);
case GNE_ATTR_PARAMETERS:
return Parameterised::areParametersValid(value);
default:
throw InvalidArgument(getTagStr() + " doesn't have an attribute of type '" + toString(key) + "'");
}
}
// ===========================================================================
// private
// ===========================================================================
void
GNEBusStop::setAttribute(SumoXMLAttr key, const std::string& value) {
switch (key) {
case SUMO_ATTR_ID:
myNet->getAttributeCarriers()->updateID(this, value);
// Change IDs of all access children
for (const auto& access : getChildAdditionals()) {
access->setMicrosimID(getID());
}
break;
case SUMO_ATTR_LANE:
replaceAdditionalParentLanes(value);
break;
case SUMO_ATTR_STARTPOS:
if (!value.empty()) {
myStartPosition = parse<double>(value);
myParametersSet |= STOPPINGPLACE_STARTPOS_SET;
} else {
myParametersSet &= ~STOPPINGPLACE_STARTPOS_SET;
}
break;
case SUMO_ATTR_ENDPOS:
if (!value.empty()) {
myEndPosition = parse<double>(value);
myParametersSet |= STOPPINGPLACE_ENDPOS_SET;
} else {
myParametersSet &= ~STOPPINGPLACE_ENDPOS_SET;
}
break;
case SUMO_ATTR_NAME:
myAdditionalName = value;
break;
case SUMO_ATTR_FRIENDLY_POS:
myFriendlyPosition = parse<bool>(value);
break;
case SUMO_ATTR_LINES:
myLines = GNEAttributeCarrier::parse<std::vector<std::string> >(value);
break;
case SUMO_ATTR_PERSON_CAPACITY:
myPersonCapacity = GNEAttributeCarrier::parse<int>(value);
break;
case SUMO_ATTR_PARKING_LENGTH:
myParkingLength = GNEAttributeCarrier::parse<double>(value);
break;
case GNE_ATTR_BLOCK_MOVEMENT:
myBlockMovement = parse<bool>(value);
break;
case GNE_ATTR_SELECTED:
if (parse<bool>(value)) {
selectAttributeCarrier();
} else {
unselectAttributeCarrier();
}
break;
case GNE_ATTR_PARAMETERS:
setParametersStr(value);
break;
default:
throw InvalidArgument(getTagStr() + " doesn't have an attribute of type '" + toString(key) + "'");
}
}
void
GNEBusStop::drawConnectionAccess(const GUIVisualizationSettings& s, const RGBColor& color) const {
if (!s.drawForPositionSelection && !s.drawForRectangleSelection) {
// Add a draw matrix for details
glPushMatrix();
// move to GLO_BUS_STOP
glTranslated(0, 0, GLO_BUS_STOP);
// set color
GLHelper::setColor(color);
// draw lines between BusStops and Access
for (const auto& access : getChildAdditionals()) {
GLHelper::drawBoxLine(access->getAdditionalGeometry().getPosition(),
RAD2DEG(myBlockIcon.getPosition().angleTo2D(access->getAdditionalGeometry().getPosition())) - 90,
myBlockIcon.getPosition().distanceTo2D(access->getAdditionalGeometry().getPosition()), .05);
}
// pop draw matrix
glPopMatrix();
}
}
/****************************************************************************/
| 14,678 | 4,245 |
#include<iostream>
using namespace std;
int main(){
int mat[3][3], i, j;
float determinant = 0;
cout<<"Enter elements of matrix row wise:\n";
for(i = 0; i < 3; i++)
for(j = 0; j < 3; j++)
cin>>mat[i][j];
printf("\nGiven matrix is:");
for(i = 0; i < 3; i++){
cout<<"\n";
for(j = 0; j < 3; j++)
cout<<mat[i][j]<<"\t";
}
//finding determinant
for(i = 0; i < 3; i++)
determinant = determinant + (mat[0][i] * (mat[1][(i+1)%3] * mat[2][(i+2)%3] - mat[1][(i+2)%3] * mat[2][(i+1)%3]));
cout<<"\n\ndeterminant: "<<determinant;
cout<<"\n\nInverse of matrix is: \n";
for(i = 0; i < 3; i++){
for(j = 0; j < 3; j++)
cout<<((mat[(j+1)%3][(i+1)%3] * mat[(j+2)%3][(i+2)%3]) - (mat[(j+1)%3][(i+2)%3] * mat[(j+2)%3][(i+1)%3]))/ determinant<<"\t";
cout<<"\n";
}
return 0;
}
| 771 | 407 |
// T3ModulesOutputDlg.cpp : implementation file
//
#include "stdafx.h"
#include "T3000.h"
#include "T3ModulesOutputDlg.h"
#include "afxdialogex.h"
#include "global_function.h"
// CT3ModulesOutputDlg dialog
DWORD WINAPI _ReadMultiRegisters_T3_Output(LPVOID pParam)
{
CT3ModulesOutputDlg* pFrame=(CT3ModulesOutputDlg*)(pParam);
CString g_strT3000LogString;
int heatbeat = 0;
while(pFrame->IsWindowVisible ())
{
if (!is_connect())
{
Sleep(1000);
continue;
}
if (pFrame->m_isstop)
{
//
heatbeat ++;
Sleep(1000);
if (heatbeat >10)
{
pFrame->m_isstop = FALSE;
heatbeat =0;
}
continue;
}
for(int i=0; i<4; i++)
{
int multy_ret = 0;
if (pFrame->m_isstop)
{
break;
}
multy_ret = Read_Multi(g_tstat_id,&product_register_value[i*100],i*100,100);
Sleep(100);
if(multy_ret<0)
break;
}
PostMessage(g_hwnd_now,WM_REFRESH_BAC_INPUT_LIST,0,0);
}
return 0;
return 0;
}
IMPLEMENT_DYNAMIC(CT3ModulesOutputDlg, CFormView)
CT3ModulesOutputDlg::CT3ModulesOutputDlg()
: CFormView(CT3ModulesOutputDlg::IDD)
{
hFirstThread = NULL;
m_isstop = FALSE;
}
CT3ModulesOutputDlg::~CT3ModulesOutputDlg()
{
if(hFirstThread != NULL)
TerminateThread(hFirstThread, 0);
}
void CT3ModulesOutputDlg::DoDataExchange(CDataExchange* pDX)
{
CFormView::DoDataExchange(pDX);
DDX_Control(pDX, IDC_LIST_T3OUTPUTS, m_outputlist);
}
#ifdef _DEBUG
void CT3ModulesOutputDlg::AssertValid() const
{
CFormView::AssertValid();
}
#ifndef _WIN32_WCE
void CT3ModulesOutputDlg::Dump(CDumpContext& dc) const
{
CFormView::Dump(dc);
}
#endif
#endif //_DEBUG
BEGIN_MESSAGE_MAP(CT3ModulesOutputDlg, CFormView)
ON_MESSAGE(WM_REFRESH_BAC_INPUT_LIST,Fresh_Input_List)
ON_MESSAGE(WM_LIST_ITEM_CHANGED,Change_Input_Item)
ON_NOTIFY(NM_CLICK, IDC_LIST_T3OUTPUTS, &CT3ModulesOutputDlg::OnNMClickList_output)
ON_NOTIFY(NM_DBLCLK, IDC_LIST_T3OUTPUTS, &CT3ModulesOutputDlg::OnNMDblclkListT3outputs)
END_MESSAGE_MAP()
// CT3ModulesOutputDlg message handlers
void CT3ModulesOutputDlg::Fresh()
{
CString strTemp;
g_hwnd_now = this->m_hWnd;
m_sn = m_sn=product_register_value[0]+product_register_value[1]*256
+product_register_value[2]*256*256+product_register_value[3]*256*256*256;
m_outputlist.ShowWindow(SW_HIDE);
m_outputlist.DeleteAllItems();
while(m_outputlist.DeleteColumn(0));
if (product_register_value[7] == PM_T34AO)
{
m_outputlist.ModifyStyle(0,LVS_SINGLESEL|LVS_REPORT|LVS_SHOWSELALWAYS);
m_outputlist.SetExtendedStyle(m_outputlist.GetExtendedStyle() |LVS_EX_GRIDLINES&(~LVS_EX_FULLROWSELECT));
m_outputlist.InsertColumn(0, _T("Label"), 180, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByDigit);
m_outputlist.InsertColumn(1, _T("Switch Status"), 100, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByString);
m_outputlist.InsertColumn(2, _T("Value"), 90, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByString);
for(int i=1; i<9; i++)
{
strTemp.Format(_T("Digit Output%d"),i);
m_outputlist.InsertItem(i-1,strTemp);
//strTemp.Format(_T("%d"),product_register_value[100+i-1]);
if (product_register_value[100+i-1] == 0)
{
strTemp = _T("Off");
}
else
{
strTemp = _T("On");
}
m_outputlist.SetItemText(i-1,2,strTemp);
}
for(int i=9; i<13; i++)
{
strTemp.Format(_T("Analog Output%d"),i);
m_outputlist.InsertItem(i-1,strTemp);
// strTemp.Format(_T("%d"),product_register_value[108+(i-8)-1]);
if (product_register_value[108+(i-8)-1] == 0)
{
strTemp = _T("Off");
}
else
{
strTemp = _T("On");
}
m_outputlist.SetItemText(i-1,2,strTemp);
}
bitset<16> BitSwitchValue(product_register_value[116]);
int SwitchValue[12];
for (int i=0; i<4; i++)
{
SwitchValue[i]=BitSwitchValue[2*i]+BitSwitchValue[2*i+1]*2;
}
bitset<16> BitSwitchValue1(product_register_value[117]);
for (int i=4; i<8; i++)
{
SwitchValue[i]=BitSwitchValue1[2*(i-4)]+BitSwitchValue1[2*(i-4)+1]*2;
}
bitset<16> BitSwitchValue2(product_register_value[118]);
for (int i=8; i<12; i++)
{
SwitchValue[i]=BitSwitchValue2[2*(i-8)]+BitSwitchValue2[2*(i-8)+1]*2;
}
for(int i = 1; i<13; i++)
{
m_outputlist.SetItemText(i-1,1,STRING_SWITCH_STATUS[SwitchValue[i-1]]);
if (SwitchValue[i-1] == 0)
{
m_outputlist.SetItemText(i-1,2,L"Off");
}
else if (SwitchValue[i-1] == 1)
{
m_outputlist.SetItemText(i-1,2,L"On");
}
else
{
if (i<9)
{
if (product_register_value[100+i-1] == 0)
{
strTemp = _T("Off");
}
else
{
strTemp = _T("On");
}
}
else
{
strTemp.Format(_T("%d"),product_register_value[100+i-1]);
}
m_outputlist.SetItemText(i-1,2,strTemp);
}
}
}
else if (product_register_value[7] == PM_T3IOA)
{
m_outputlist.ModifyStyle(0,LVS_SINGLESEL|LVS_REPORT|LVS_SHOWSELALWAYS);
m_outputlist.SetExtendedStyle(m_outputlist.GetExtendedStyle() |LVS_EX_GRIDLINES&(~LVS_EX_FULLROWSELECT));
m_outputlist.InsertColumn(0, _T("Label"), 180, ListCtrlEx::EditBox, LVCFMT_CENTER, ListCtrlEx::SortByDigit);
m_outputlist.InsertColumn(2, _T("Switch Status"), 100, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByString);
m_outputlist.InsertColumn(1, _T("Value"), 90, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByString);
bitset<16> BitSwitchValue(product_register_value[116]);
int SwitchValue[8];
for (int i=0; i<8; i++)
{
SwitchValue[i]=BitSwitchValue[2*i]+BitSwitchValue[2*i+1]*2;
}
for(int i=1; i<9; i++)
{
strTemp= Get_Table_Name(m_sn,_T("Output"),i);
m_outputlist.InsertItem(i,strTemp);
// strTemp.Format(_T("%d"),product_register_value[100+i-1]);
if (product_register_value[100+i-1] == 0)
{
strTemp = _T("Off");
}
else
{
strTemp = _T("On");
}
m_outputlist.SetItemText(i-1,1,strTemp);
m_outputlist.SetItemText(i-1,2,STRING_SWITCH_STATUS[SwitchValue[i-1]]);
if (SwitchValue[i-1] == 0)
{
m_outputlist.SetItemText(i-1,1,L"Off");
}
if (SwitchValue[i-1] == 1)
{
m_outputlist.SetItemText(i-1,1,L"On");
}
}
}
else if (product_register_value[7] == PM_T38AI8AO6DO)
{
m_outputlist.ModifyStyle(0,LVS_SINGLESEL|LVS_REPORT|LVS_SHOWSELALWAYS);
m_outputlist.SetExtendedStyle(m_outputlist.GetExtendedStyle() |LVS_EX_GRIDLINES&(~LVS_EX_FULLROWSELECT));
m_outputlist.InsertColumn(0, _T("Label"), 180, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByDigit);
m_outputlist.InsertColumn(2, _T("Switch Status"), 100, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByString);
m_outputlist.InsertColumn(1, _T("Value"), 90, ListCtrlEx::EditBox, LVCFMT_CENTER, ListCtrlEx::SortByString);
bitset<16> BitSwitchValue1(product_register_value[114]);
bitset<16> BitSwitchValue2(product_register_value[115]);
int SwitchValue[16];
for (int i=0; i<8; i++)
{
SwitchValue[i]=BitSwitchValue1[2*i]+BitSwitchValue1[2*i+1]*2;
SwitchValue[8+i]=BitSwitchValue2[2*i]+BitSwitchValue2[2*i+1]*2;
}
for(int i=1; i<15; i++)
{
if (i<9)
{
strTemp= Get_Table_Name(m_sn,_T("Analog_Output"),i);
m_outputlist.InsertItem(i,strTemp);
if (SwitchValue[i-1] == 0)
{
m_outputlist.SetItemText(i-1,1,L"Off");
}
else if (SwitchValue[i-1] == 1)
{
m_outputlist.SetItemText(i-1,1,L"On");
}
else
{
// if (product_register_value[100+i-1] == 0)
// {
// strTemp = _T("Off");
// }
// else
// {
// strTemp = _T("On");
// }
strTemp.Format(_T("%d"),product_register_value[100+i-1]);
}
m_outputlist.SetItemText(i-1,1,strTemp);
}
else
{
strTemp= Get_Table_Name(m_sn,_T("Digital_Output"),i);
m_outputlist.InsertItem(i,strTemp);
if (SwitchValue[i-1] == 0)
{
m_outputlist.SetItemText(i-1,1,L"Off");
}
else if (SwitchValue[i-1] == 1)
{
m_outputlist.SetItemText(i-1,1,L"On");
}
else
{
if (product_register_value[100+i-1] == 0)
{
strTemp = _T("Off");
}
else
{
strTemp = _T("On");
}
}
m_outputlist.SetItemText(i-1,1,strTemp);
}
m_outputlist.SetItemText(i-1,2,STRING_SWITCH_STATUS[SwitchValue[i-1]]);
}
}
else if (product_register_value[7] == PM_T38I13O)
{
m_outputlist.ModifyStyle(0,LVS_SINGLESEL|LVS_REPORT|LVS_SHOWSELALWAYS);
m_outputlist.SetExtendedStyle(m_outputlist.GetExtendedStyle() |LVS_EX_GRIDLINES&(~LVS_EX_FULLROWSELECT));
m_outputlist.InsertColumn(0, _T("Label"), 180, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByDigit);
m_outputlist.InsertColumn(1, _T("Output Value"), 100, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByString);
m_outputlist.InsertColumn(2, _T("Light Switch"), 90, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByString);
m_outputlist.InsertColumn(3, _T("Auto/Manual"), 90, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByString);
m_outputlist.InsertColumn(4, _T("Switch Status"), 100, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByString);
for(int i=1; i<14; i++)
{
strTemp = Get_Table_Name(m_sn,_T("Output"),i);
m_outputlist.InsertItem(i-1,strTemp);
}
bitset<16> BitSwitchValue(product_register_value[116]);
int SwitchValue[13];
for (int i=0; i<8; i++)
{
SwitchValue[i]=BitSwitchValue[2*i]+BitSwitchValue[2*i+1]*2;
}
bitset<16> BitSwitchValue2(product_register_value[117]);
for (int i=8; i<13; i++)
{
SwitchValue[i]=BitSwitchValue2[2*(i-8)]+BitSwitchValue2[2*(i-8)+1]*2;
}
CString CstresultDO;
for(int i = 1; i<=13; i++)
{
// CstresultDO.Format(_T("%d"),product_register_value[100+i-1]);
if (product_register_value[100+i-1] == 0)
{
CstresultDO = _T("Off");
}
else
{
CstresultDO = _T("On");
}
m_outputlist.SetItemText(i-1,1,CstresultDO);
if (product_register_value[216+i-1]>0)
{
CstresultDO=Get_Table_Name(m_sn,_T("Input"),product_register_value[216+i-1]);
}
else
{
CstresultDO=_T("UNUSED");
}
m_outputlist.SetItemText(i-1,2,CstresultDO);
if (((product_register_value[215]>>(i-1))&0x01)==1)
{
CstresultDO=_T("Manual");
}
else
{
CstresultDO=_T("Auto");
}
m_outputlist.SetItemText(i-1,3,CstresultDO);
m_outputlist.SetItemText(i-1,4,STRING_SWITCH_STATUS[SwitchValue[i-1]]);
if (SwitchValue[i-1] == 0)
{
m_outputlist.SetItemText(i-1,1,L"Off");
}
if (SwitchValue[i-1] == 1)
{
m_outputlist.SetItemText(i-1,1,L"On");
}
}
}
else if (product_register_value[7] == PM_T36CT)
{
m_outputlist.ModifyStyle(0,LVS_SINGLESEL|LVS_REPORT|LVS_SHOWSELALWAYS);
m_outputlist.SetExtendedStyle(m_outputlist.GetExtendedStyle() |LVS_EX_GRIDLINES&(~LVS_EX_FULLROWSELECT));
m_outputlist.InsertColumn(0, _T("Label"), 180, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByDigit);
m_outputlist.InsertColumn(2, _T("Switch Status"), 100, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByString);
m_outputlist.InsertColumn(1, _T("Value"), 90, ListCtrlEx::EditBox, LVCFMT_CENTER, ListCtrlEx::SortByString);
for(int i=1; i<6; i++)
{
strTemp= Get_Table_Name(m_sn,_T("Output"),i);
m_outputlist.InsertItem(i,strTemp);
}
CString CstresultDO;
int b0,b1,b;
for(int i = 1; i<=5; i++)
{
CstresultDO.Format(_T("%d"),product_register_value[100+i-1]);
m_outputlist.SetItemText(i-1,2,CstresultDO);
b0=Get_Bit_FromRegister(product_register_value[124],2*(i-1)+1);
b1=Get_Bit_FromRegister(product_register_value[124],2*(i-1)+2);
b=b1*2+b0;
if (i==5)
{
b0=Get_Bit_FromRegister(product_register_value[124],1);
b1=Get_Bit_FromRegister(product_register_value[124],2);
b=b1*2+b0;
}
if (b==0)
{
CstresultDO=_T("OFF");
}
else if (b==1)
{
CstresultDO=_T("ON");
}
else if (b==2)
{
CstresultDO=_T("AUTO");
}
else
{
CstresultDO=_T("");
}
m_outputlist.SetItemText(i-1,1,CstresultDO);
}
}
m_outputlist.ShowWindow(SW_SHOW);
if(hFirstThread != NULL)
TerminateThread(hFirstThread, 0);
hFirstThread=NULL;
if (!hFirstThread)
{
hFirstThread = CreateThread(NULL,NULL,_ReadMultiRegisters_T3_Output,this,NULL,0);
}
}
LRESULT CT3ModulesOutputDlg::Fresh_Input_List(WPARAM wParam,LPARAM lParam)
{
m_sn=product_register_value[0]+product_register_value[1]*256+product_register_value[2]*256*256+product_register_value[3]*256*256*256;
CString strTemp;
int fresh_type = (int)wParam;
int fresh_row =(int) lParam;
if (fresh_type == 0)
{
m_outputlist.DeleteAllItems();
if (product_register_value[7] == PM_T34AO)
{
for(int i=1; i<9; i++)
{
strTemp.Format(_T("Digit Output%d"),i);
m_outputlist.InsertItem(i-1,strTemp);
// strTemp.Format(_T("%d"),product_register_value[100+i-1]);
if (product_register_value[100+i-1] == 0)
{
strTemp = _T("Off");
}
else
{
strTemp = _T("On");
}
m_outputlist.SetItemText(i-1,2,strTemp);
}
for(int i=9; i<13; i++)
{
strTemp.Format(_T("Analog Output%d"),i);
m_outputlist.InsertItem(i-1,strTemp);
strTemp.Format(_T("%d"),product_register_value[108+(i-8)-1]);
if (product_register_value[108+(i-8)-1] == 0)
{
strTemp = _T("Off");
}
else
{
strTemp = _T("On");
}
m_outputlist.SetItemText(i-1,2,strTemp);
}
bitset<16> BitSwitchValue(product_register_value[116]);
int SwitchValue[12];
for (int i=0; i<4; i++)
{
SwitchValue[i]=BitSwitchValue[2*i]+BitSwitchValue[2*i+1]*2;
}
bitset<16> BitSwitchValue1(product_register_value[117]);
for (int i=4; i<8; i++)
{
SwitchValue[i]=BitSwitchValue1[2*(i-4)]+BitSwitchValue1[2*(i-4)+1]*2;
}
bitset<16> BitSwitchValue2(product_register_value[118]);
for (int i=8; i<12; i++)
{
SwitchValue[i]=BitSwitchValue2[2*(i-8)]+BitSwitchValue2[2*(i-8)+1]*2;
}
for(int i = 1; i<13; i++)
{
m_outputlist.SetItemText(i-1,1,STRING_SWITCH_STATUS[SwitchValue[i-1]]);
if (SwitchValue[i-1] == 0)
{
m_outputlist.SetItemText(i-1,2,L"Off");
}
else if (SwitchValue[i-1] == 1)
{
m_outputlist.SetItemText(i-1,2,L"On");
}
else
{
if (i<9)
{
if (product_register_value[100+i-1] == 0)
{
strTemp = _T("Off");
}
else
{
strTemp = _T("On");
}
}
else
{
strTemp.Format(_T("%d"),product_register_value[100+i-1]);
}
m_outputlist.SetItemText(i-1,2,strTemp);
}
}
}
else if (product_register_value[7] == PM_T3IOA)
{
bitset<16> BitSwitchValue(product_register_value[116]);
int SwitchValue[8];
for (int i=0; i<8; i++)
{
SwitchValue[i]=BitSwitchValue[2*i]+BitSwitchValue[2*i+1]*2;
}
for(int i=1; i<9; i++)
{
strTemp= Get_Table_Name(m_sn,_T("Output"),i);
m_outputlist.InsertItem(i,strTemp);
// strTemp.Format(_T("%d"),product_register_value[100+i-1]);
if (product_register_value[100+i-1] == 0)
{
strTemp = _T("Off");
}
else
{
strTemp = _T("On");
}
m_outputlist.SetItemText(i-1,1,strTemp);
m_outputlist.SetItemText(i-1,2,STRING_SWITCH_STATUS[SwitchValue[i-1]]);
if (SwitchValue[i-1] == 0)
{
m_outputlist.SetItemText(i-1,1,L"Off");
}
if (SwitchValue[i-1] == 1)
{
m_outputlist.SetItemText(i-1,1,L"On");
}
}
}
else if (product_register_value[7] == PM_T38I13O)
{
for(int i=1; i<14; i++)
{
strTemp = Get_Table_Name(m_sn,_T("Output"),i);
m_outputlist.InsertItem(i-1,strTemp);
}
bitset<16> BitSwitchValue(product_register_value[116]);
int SwitchValue[13];
for (int i=0; i<8; i++)
{
SwitchValue[i]=BitSwitchValue[2*i]+BitSwitchValue[2*i+1]*2;
}
bitset<16> BitSwitchValue2(product_register_value[117]);
for (int i=8; i<13; i++)
{
SwitchValue[i]=BitSwitchValue2[2*(i-8)]+BitSwitchValue2[2*(i-8)+1]*2;
}
CString CstresultDO;
for(int i = 1; i<=13; i++)
{
//CstresultDO.Format(_T("%d"),product_register_value[100+i-1]);
if (product_register_value[100+i-1] == 0)
{
strTemp = _T("Off");
}
else
{
strTemp = _T("On");
}
m_outputlist.SetItemText(i-1,1,strTemp);
if (product_register_value[216+i-1]>0)
{
CstresultDO=Get_Table_Name(m_sn,_T("Input"),product_register_value[216+i-1]);
}
else
{
CstresultDO=_T("UNUSED");
}
m_outputlist.SetItemText(i-1,2,CstresultDO);
if (((product_register_value[215]>>(i-1))&0x01)==1)
{
CstresultDO=_T("Manual");
}
else
{
CstresultDO=_T("Auto");
}
m_outputlist.SetItemText(i-1,3,CstresultDO);
m_outputlist.SetItemText(i-1,4,STRING_SWITCH_STATUS[SwitchValue[i-1]]);
if (SwitchValue[i-1] == 0)
{
m_outputlist.SetItemText(i-1,1,L"Off");
}
if (SwitchValue[i-1] == 1)
{
m_outputlist.SetItemText(i-1,1,L"On");
}
}
}
else if (product_register_value[7] == PM_T36CT)
{
for(int i=1; i<6; i++)
{
strTemp= Get_Table_Name(m_sn,_T("Output"),i);
m_outputlist.InsertItem(i,strTemp);
}
CString CstresultDO;
int b0,b1,b;
for(int i = 1; i<=5; i++)
{
CstresultDO.Format(_T("%d"),product_register_value[100+i-1]);
m_outputlist.SetItemText(i-1,2,CstresultDO);
b0=Get_Bit_FromRegister(product_register_value[124],2*(i-1)+1);
b1=Get_Bit_FromRegister(product_register_value[124],2*(i-1)+2);
b=b1*2+b0;
if (i==5)
{
b0=Get_Bit_FromRegister(product_register_value[124],1);
b1=Get_Bit_FromRegister(product_register_value[124],2);
b=b1*2+b0;
}
if (b==0)
{
CstresultDO=_T("OFF");
}
else if (b==1)
{
CstresultDO=_T("ON");
}
else if (b==2)
{
CstresultDO=_T("AUTO");
}
else
{
CstresultDO=_T("");
}
m_outputlist.SetItemText(i-1,1,CstresultDO);
}
}
else if (product_register_value[7] == PM_T38AI8AO6DO)
{
bitset<16> BitSwitchValue1(product_register_value[114]);
bitset<16> BitSwitchValue2(product_register_value[115]);
int SwitchValue[16];
for (int i=0; i<8; i++)
{
SwitchValue[i]=BitSwitchValue1[2*i]+BitSwitchValue1[2*i+1]*2;
SwitchValue[8+i]=BitSwitchValue2[2*i]+BitSwitchValue2[2*i+1]*2;
}
for(int i=1; i<15; i++)
{
if (i<9)
{
strTemp= Get_Table_Name(m_sn,_T("Analog_Output"),i);
m_outputlist.InsertItem(i,strTemp);
if (SwitchValue[i-1] == 0)
{
m_outputlist.SetItemText(i-1,1,L"Off");
}
else if (SwitchValue[i-1] == 1)
{
m_outputlist.SetItemText(i-1,1,L"On");
}
else
{
// if (product_register_value[100+i-1] == 0)
// {
// strTemp = _T("Off");
// }
// else
// {
// strTemp = _T("On");
// }
strTemp.Format(_T("%d"),product_register_value[100+i-1]);
}
m_outputlist.SetItemText(i-1,1,strTemp);
}
else
{
strTemp= Get_Table_Name(m_sn,_T("Digital_Output"),i);
m_outputlist.InsertItem(i,strTemp);
if (SwitchValue[i-1] == 0)
{
m_outputlist.SetItemText(i-1,1,L"Off");
}
else if (SwitchValue[i-1] == 1)
{
m_outputlist.SetItemText(i-1,1,L"On");
}
else
{
if (product_register_value[100+i-1] == 0)
{
strTemp = _T("Off");
}
else
{
strTemp = _T("On");
}
}
m_outputlist.SetItemText(i-1,1,strTemp);
}
m_outputlist.SetItemText(i-1,2,STRING_SWITCH_STATUS[SwitchValue[i-1]]);
}
}
}
return 0;
}
LRESULT CT3ModulesOutputDlg::Change_Input_Item(WPARAM wParam,LPARAM lParam)
{
int lRow = (int)wParam;
int lCol = (int)lParam;
CString strText = m_outputlist.GetItemText (lRow,lCol);
if (product_register_value[7] == PM_T34AO)
{
if (lCol == 2)
{
bitset<16> BitSwitchValue(product_register_value[116]);
int SwitchValue[12];
for (int i=0; i<4; i++)
{
SwitchValue[i]=BitSwitchValue[2*i]+BitSwitchValue[2*i+1]*2;
}
bitset<16> BitSwitchValue1(product_register_value[117]);
for (int i=4; i<8; i++)
{
SwitchValue[i]=BitSwitchValue1[2*(i-4)]+BitSwitchValue1[2*(i-4)+1]*2;
}
bitset<16> BitSwitchValue2(product_register_value[118]);
for (int i=8; i<12; i++)
{
SwitchValue[i]=BitSwitchValue2[2*(i-8)]+BitSwitchValue2[2*(i-8)+1]*2;
}
}
}
else if (product_register_value[7] == PM_T3IOA)
{
}
else if (product_register_value[7] == PM_T38I13O)
{
}
else if (product_register_value[7] == PM_T36CT)
{
}
else if (product_register_value[7] == PM_T38AI8AO6DO)
{
if (lCol == 1)
{
bitset<16> BitSwitchValue1(product_register_value[114]);
bitset<16> BitSwitchValue2(product_register_value[115]);
int SwitchValue[16];
for (int i=0; i<8; i++)
{
SwitchValue[i]=BitSwitchValue1[2*i]+BitSwitchValue1[2*i+1]*2;
SwitchValue[8+i]=BitSwitchValue2[2*i]+BitSwitchValue2[2*i+1]*2;
}
if (SwitchValue[lRow] ==2)
{
int OutputValue = _wtoi (strText);
if (OutputValue!=product_register_value[100+lRow])
{
if (lRow<8)
{
int ret = write_one (g_tstat_id,100+lRow,OutputValue,1);
if (ret>0)
{
product_register_value[100+lRow] = OutputValue;
}
}
}
PostMessage (WM_REFRESH_BAC_INPUT_LIST,0,0);
}
else
{
m_outputlist.Set_Edit (false);
return 0;
}
}
}
return 0;
}
/*
@1:Different Product responce to the different functionality
@2:
*/
void CT3ModulesOutputDlg::OnNMClickList_output(NMHDR *pNMHDR, LRESULT *pResult)
{
LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR);
CString temp_cstring;
long lRow,lCol;
m_outputlist.Set_Edit(true);
DWORD dwPos=GetMessagePos();//Get which line is click by user.Set the check box, when user enter Insert it will jump to program dialog
CPoint point( GET_X_LPARAM(dwPos), GET_Y_LPARAM(dwPos));
m_outputlist.ScreenToClient(&point);
LVHITTESTINFO lvinfo;
lvinfo.pt=point;
lvinfo.flags=LVHT_ABOVE;
int nItem=m_outputlist.SubItemHitTest(&lvinfo);
BOOL Is_Range = FALSE;
int Range_Address = -1;
int Value_Address = -1;
int Value_Length = 0;
lRow = lvinfo.iItem;
lCol = lvinfo.iSubItem;
m_isstop = TRUE;
if(lRow>m_outputlist.GetItemCount()) //如果点击区超过最大行号,则点击是无效的
{
return;
}
if(lRow<0)
{
return;
}
if (product_register_value[7] == PM_T34AO)
{
bitset<16> BitSwitchValue(product_register_value[116]);
int SwitchValue[12];
for (int i=0; i<4; i++)
{
SwitchValue[i]=BitSwitchValue[2*i]+BitSwitchValue[2*i+1]*2;
}
bitset<16> BitSwitchValue1(product_register_value[117]);
for (int i=4; i<8; i++)
{
SwitchValue[i]=BitSwitchValue1[2*(i-4)]+BitSwitchValue1[2*(i-4)+1]*2;
}
bitset<16> BitSwitchValue2(product_register_value[118]);
for (int i=8; i<12; i++)
{
SwitchValue[i]=BitSwitchValue2[2*(i-8)]+BitSwitchValue2[2*(i-8)+1]*2;
}
if (lCol == 2)
{ // m_isstop =TRUE;
m_outputlist.Set_Edit (false);
if (SwitchValue[lRow] == 2)
{
if (product_register_value[100+lRow] == 0)
{
int ret = write_one (g_tstat_id,100+lRow,1,1);
if (ret > 0)
{
product_register_value[100+lRow] = 1;
m_outputlist.SetItemText (lRow,lCol,L"On");
}
}
else
{
int ret = write_one (g_tstat_id,100+lRow,0,1);
if (ret > 0)
{
product_register_value[100+lRow] = 0;
m_outputlist.SetItemText (lRow,lCol,L"Off");
}
}
}
}
}
else if (product_register_value[7] == PM_T3IOA)
{
bitset<16> BitSwitchValue(product_register_value[116]);
int SwitchValue[8];
for (int i=0; i<8; i++)
{
SwitchValue[i]=BitSwitchValue[2*i]+BitSwitchValue[2*i+1]*2;
}
if (lCol == 1)
{
if (SwitchValue[lRow] == 2)
{
if (product_register_value[100+lRow] == 0)
{
int ret = write_one (g_tstat_id,100+lRow,1,1);
if (ret > 0)
{
product_register_value[100+lRow] = 1;
m_outputlist.SetItemText (lRow,lCol,L"On");
}
}
else
{
int ret = write_one (g_tstat_id,100+lRow,0,1);
if (ret > 0)
{
product_register_value[100+lRow] = 0;
m_outputlist.SetItemText (lRow,lCol,L"Off");
}
}
}
}
}
else if (product_register_value[7] == PM_T38AI8AO6DO)
{
bitset<16> BitSwitchValue1(product_register_value[114]);
bitset<16> BitSwitchValue2(product_register_value[115]);
int SwitchValue[16];
for (int i=0; i<8; i++)
{
SwitchValue[i]=BitSwitchValue1[2*i]+BitSwitchValue1[2*i+1]*2;
SwitchValue[8+i]=BitSwitchValue2[2*i]+BitSwitchValue2[2*i+1]*2;
}
if (lCol == 1)
{
if (SwitchValue[lRow] == 2)
{
if (lRow>7)
{
if (product_register_value[100+lRow] == 0)
{
int ret = write_one (g_tstat_id,100+lRow,1,1);
if (ret > 0)
{
product_register_value[100+lRow] = 1;
m_outputlist.SetItemText (lRow,lCol,L"On");
}
}
else
{
int ret = write_one (g_tstat_id,100+lRow,0,1);
if (ret > 0)
{
product_register_value[100+lRow] = 0;
m_outputlist.SetItemText (lRow,lCol,L"Off");
}
}
}
}
}
}
else if (product_register_value[7] == PM_T38I13O)
{
bitset<16> BitSwitchValue(product_register_value[116]);
int SwitchValue[13];
for (int i=0; i<8; i++)
{
SwitchValue[i]=BitSwitchValue[2*i]+BitSwitchValue[2*i+1]*2;
}
bitset<16> BitSwitchValue2(product_register_value[117]);
for (int i=8; i<13; i++)
{
SwitchValue[i]=BitSwitchValue2[2*(i-8)]+BitSwitchValue2[2*(i-8)+1]*2;
}
if (lCol == 1)
{
if (SwitchValue[lRow] == 2)
{
if (product_register_value[100+lRow] == 0)
{
int ret = write_one (g_tstat_id,100+lRow,1,1);
if (ret > 0)
{
product_register_value[100+lRow] = 1;
m_outputlist.SetItemText (lRow,lCol,L"On");
}
}
else
{
int ret = write_one (g_tstat_id,100+lRow,0,1);
if (ret > 0)
{
product_register_value[100+lRow] = 0;
m_outputlist.SetItemText (lRow,lCol,L"Off");
}
}
}
}
}
else if (product_register_value[7] == PM_T36CT)
{
}
}
void CT3ModulesOutputDlg::OnNMDblclkListT3outputs(NMHDR *pNMHDR, LRESULT *pResult)
{
LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR);
*pResult = 0;
}
BOOL CT3ModulesOutputDlg::PreTranslateMessage(MSG* pMsg)
{
if(pMsg->message==WM_KEYDOWN && pMsg->wParam==VK_RETURN)
{
CRect list_rect,win_rect;
m_outputlist.GetWindowRect(list_rect);
ScreenToClient(&list_rect);
::GetWindowRect(this->m_hWnd,win_rect);
m_outputlist.Set_My_WindowRect(win_rect);
m_outputlist.Set_My_ListRect(list_rect);
m_outputlist.Get_clicked_mouse_position();
return TRUE;
}
return CFormView::PreTranslateMessage(pMsg);
}
| 32,877 | 13,041 |
#ifndef __FadalightMesh_PatchInfo_h
#define __FadalightMesh_PatchInfo_h
#include "Alat/vector.hpp"
#include "Alat/armadillo.hpp"
/*--------------------------------------------------------------------------*/
namespace FadalightMesh
{
class PatchInfo
{
public:
~PatchInfo();
PatchInfo();
PatchInfo( const PatchInfo& patchinfo);
PatchInfo& operator=( const PatchInfo& patchinfo);
std::string getClassName() const;
PatchInfo* clone() const;
alat::Vector<alat::armaivec> cells, edgesinner, edgesouter, nodes;
arma::field<arma::mat> sidecoeffs;
arma::field<arma::imat> sideindices;
};
}
/*--------------------------------------------------------------------------*/
#endif
| 693 | 224 |
//
// Mat4x4.h
// DataStructures
//
// Created by James Landess on 11/11/16.
// Copyright (c) 2016 James Landess. All rights reserved.
//
#ifndef DataStructures_Mat4x4_h
#define DataStructures_Mat4x4_h
#include "StaticArray.hpp"
#include "Vec4.hpp"
#include "Mat2x4.hpp"
#include "Mat3x4.hpp"
#include "Mat4x3.hpp"
#include "TypeTraits/StaticallySized.h"
namespace LD
{
namespace Detail
{
template<typename T>
class tMat4x4
{
private:
tVec4<T> Rows[4];
public:
inline tMat4x4();
inline tMat4x4(const typename TypeAid<T, 16>::CoreType & a);
inline tMat4x4(const typename TypeAid<T, 16>::CoreType & a0, const typename TypeAid<T, 16>::CoreType & b0, const typename TypeAid<T, 16>::CoreType & c0,const typename TypeAid<T, 16>::CoreType & d0,
const typename TypeAid<T, 16>::CoreType & a1, const typename TypeAid<T, 16>::CoreType & b1, const typename TypeAid<T, 16>::CoreType & c1,const typename TypeAid<T, 16>::CoreType & d1,
const typename TypeAid<T, 16>::CoreType & a2, const typename TypeAid<T, 16>::CoreType & b2, const typename TypeAid<T, 16>::CoreType & c2,const typename TypeAid<T, 16>::CoreType & d2,
const typename TypeAid<T, 16>::CoreType & a3, const typename TypeAid<T, 16>::CoreType & b3, const typename TypeAid<T, 16>::CoreType & c3,const typename TypeAid<T, 16>::CoreType & d3);
inline tMat4x4(const tVec4<T> &a, const tVec4<T> & b, const tVec4<T> & c, const tVec4<T> & d);
inline tMat4x4(const tMat2x2<T> & a);
inline tMat4x4(const tMat3x3<T> & a);
inline tVec4<T> & operator [] (const PDP::UInteger & index);
inline const tVec4<T> & operator [] (const PDP::UInteger & index) const;
inline tMat4x4 & operator = (const typename TypeAid<T, 16>::CoreType & a);
inline tMat4x4 & operator = (const tMat2x2<T> & object);
inline tMat4x4 & operator = (const tMat3x3<T> & object);
};
template<typename T>
tMat4x4<T>::tMat4x4()
{
this->Rows[0] = this->Rows[1] = this->Rows[2] = this->Rows[3] = 0;
}
template<typename T>
tMat4x4<T>::tMat4x4(const typename TypeAid<T, 16>::CoreType & a)
{
this->Rows[0] = this->Rows[1] = this->Rows[2] = this->Rows[3] = a;
}
template<typename T>
tMat4x4<T>::tMat4x4(const typename TypeAid<T, 16>::CoreType & a0, const typename TypeAid<T, 16>::CoreType & b0, const typename TypeAid<T, 16>::CoreType & c0,const typename TypeAid<T, 16>::CoreType & d0,
const typename TypeAid<T, 16>::CoreType & a1, const typename TypeAid<T, 16>::CoreType & b1, const typename TypeAid<T, 16>::CoreType & c1,const typename TypeAid<T, 16>::CoreType & d1,
const typename TypeAid<T, 16>::CoreType & a2, const typename TypeAid<T, 16>::CoreType & b2, const typename TypeAid<T, 16>::CoreType & c2,const typename TypeAid<T, 16>::CoreType & d2,
const typename TypeAid<T, 16>::CoreType & a3, const typename TypeAid<T, 16>::CoreType & b3, const typename TypeAid<T, 16>::CoreType & c3,const typename TypeAid<T, 16>::CoreType & d3)
{
this->Rows[0] = tVec4<T>(a0,b0,c0,d0);
this->Rows[1] = tVec4<T>(a1,b1,c1,d1);
this->Rows[2] = tVec4<T>(a2,b2,c2,d2);
this->Rows[3] = tVec4<T>(a3,b3,c3,d3);
}
template<typename T>
tMat4x4<T>::tMat4x4(const tVec4<T> &a, const tVec4<T> & b, const tVec4<T> & c, const tVec4<T> & d)
{
this->Rows[0] = a;
this->Rows[1] = b;
this->Rows[2] = c;
this->Rows[3] = d;
}
template<typename T>
tVec4<T> & tMat4x4<T>::operator[](const PDP::UInteger &index)
{
return this->Rows[index];
}
template<typename T>
const tVec4<T> & tMat4x4<T>::operator[](const PDP::UInteger &index) const
{
return this->Rows[index];
}
template<typename T>
tMat4x4<T> & tMat4x4<T>::operator=(const typename TypeAid<T, 16>::CoreType &a)
{
this->Rows[0] = tVec4<T>(a,0,0,0);
this->Rows[1] = tVec4<T>(0,a,0,0);
this->Rows[2] = tVec4<T>(0,0,a,0);
this->Rows[3] = tVec4<T>(0,0,0,a);
return (*this);
}
template <typename U, typename T>
inline tMat4x4<T>& operator+= (tMat4x4<T> & a,const typename TypeAid<U, 16>::CoreType &s)
{
a[0] += s;
a[1] += s;
a[2] += s;
a[3] += s;
return a;
}
template <typename U, typename T>
inline tMat4x4<T>& operator+= (tMat4x4<U> & a, const tMat4x4<T> & b )
{
a[0] += b[0];
a[1] += b[1];
a[2] += b[2];
a[3] += b[3];
return a;
}
template <typename U, typename T>
inline tMat4x4<T> & operator-= (tMat4x4<T> & a,const typename TypeAid<U, 16>::CoreType &s)
{
a[0] -= s;
a[1] -= s;
a[2] -= s;
a[3] -= s;
return a;
}
template <typename U, typename T>
inline tMat4x4<T> & operator-= (tMat4x4<U> & a, const tMat4x4<T> & m)
{
a[0] -= m[0];
a[1] -= m[1];
a[2] -= m[2];
a[3] -= m[3];
return a;
}
template <typename U, typename T>
inline tMat4x4<T> & operator*= (tMat4x4<T> & a,const typename TypeAid<U, 16>::CoreType &s)
{
a[0] *= s;
a[1] *= s;
a[2] *= s;
a[3] *= s;
return a;
}
template <typename U, typename T>
inline tMat4x4<T> & operator*= (tMat4x4<U> & a, const tMat4x4<T> & m)
{
return (a = a * m);
}
template <typename U, typename T>
inline tMat4x4<T> & operator /= (tMat4x4<T> & a,const typename TypeAid<U, 16>::CoreType &s)
{
a[0] /= s;
a[1] /= s;
a[2] /= s;
a[3] /= s;
return a;
}
template <typename T>
struct compute_inversetMat4x4
{
inline static tMat4x4<T> call( const tMat4x4<T> & m)
{
const T & Coef00 = m[2][2] * m[3][3] - m[3][2] * m[2][3];
const T & Coef02 = m[1][2] * m[3][3] - m[3][2] * m[1][3];
const T & Coef03 = m[1][2] * m[2][3] - m[2][2] * m[1][3];
const T & Coef04 = m[2][1] * m[3][3] - m[3][1] * m[2][3];
const T & Coef06 = m[1][1] * m[3][3] - m[3][1] * m[1][3];
const T & Coef07 = m[1][1] * m[2][3] - m[2][1] * m[1][3];
const T & Coef08 = m[2][1] * m[3][2] - m[3][1] * m[2][2];
const T & Coef10 = m[1][1] * m[3][2] - m[3][1] * m[1][2];
const T & Coef11 = m[1][1] * m[2][2] - m[2][1] * m[1][2];
const T & Coef12 = m[2][0] * m[3][3] - m[3][0] * m[2][3];
const T & Coef14 = m[1][0] * m[3][3] - m[3][0] * m[1][3];
const T & Coef15 = m[1][0] * m[2][3] - m[2][0] * m[1][3];
const T & Coef16 = m[2][0] * m[3][2] - m[3][0] * m[2][2];
const T & Coef18 = m[1][0] * m[3][2] - m[3][0] * m[1][2];
const T & Coef19 = m[1][0] * m[2][2] - m[2][0] * m[1][2];
const T & Coef20 = m[2][0] * m[3][1] - m[3][0] * m[2][1];
const T & Coef22 = m[1][0] * m[3][1] - m[3][0] * m[1][1];
const T & Coef23 = m[1][0] * m[2][1] - m[2][0] * m[1][1];
const tVec4<T> Fac0(Coef00, Coef00, Coef02, Coef03);
const tVec4<T> Fac1(Coef04, Coef04, Coef06, Coef07);
const tVec4<T> Fac2(Coef08, Coef08, Coef10, Coef11);
const tVec4<T> Fac3(Coef12, Coef12, Coef14, Coef15);
const tVec4<T> Fac4(Coef16, Coef16, Coef18, Coef19);
const tVec4<T> Fac5(Coef20, Coef20, Coef22, Coef23);
const tVec4<T> Vec0(m[1][0], m[0][0], m[0][0], m[0][0]);
const tVec4<T> Vec1(m[1][1], m[0][1], m[0][1], m[0][1]);
const tVec4<T> Vec2(m[1][2], m[0][2], m[0][2], m[0][2]);
const tVec4<T> Vec3(m[1][3], m[0][3], m[0][3], m[0][3]);
const tVec4<T> Inv0(Vec1 * Fac0 - Vec2 * Fac1 + Vec3 * Fac2);
const tVec4<T> Inv1(Vec0 * Fac0 - Vec2 * Fac3 + Vec3 * Fac4);
const tVec4<T> Inv2(Vec0 * Fac1 - Vec1 * Fac3 + Vec3 * Fac5);
const tVec4<T> Inv3(Vec0 * Fac2 - Vec1 * Fac4 + Vec2 * Fac5);
const tVec4<T> SignA(+1, -1, +1, -1);
const tVec4<T> SignB(-1, +1, -1, +1);
const tMat4x4<T> Inverse(Inv0 * SignA, Inv1 * SignB, Inv2 * SignA, Inv3 * SignB);
const tVec4<T> Row0(Inverse[0][0], Inverse[1][0], Inverse[2][0], Inverse[3][0]);
const tVec4<T> Dot0(m[0] * Row0);
const T Dot1 = (Dot0.x + Dot0.y) + (Dot0.z + Dot0.w);
const T OneOverDeterminant = static_cast<T>(1) / Dot1;
return Inverse * OneOverDeterminant;
}
};
template <typename U, typename T>
inline tMat4x4<T> & operator/= (tMat4x4<U> & a, const tMat4x4<T> & m)
{
return (a = a* compute_inversetMat4x4<T>::call(m));
}
template <typename T>
inline tMat4x4<T> & operator++ (tMat4x4<T> & m)
{
m[0];
m[1];
m[2];
m[3];
return m;
}
template <typename T>
inline tMat4x4<T> & operator-- (tMat4x4<T> & m)
{
m[0];
m[1];
m[2];
m[3];
return m;
}
template <typename T>
inline tMat4x4<T> & operator++(tMat4x4<T> & m,int)
{
++m;
return m;
}
template <typename T>
inline tMat4x4<T> & operator--(tMat4x4<T> & m, int)
{
--m;
return m;
}
// Binary operators
template <typename T, typename U>
inline tMat4x4<T> operator+
(
tMat4x4<T> const & m,
const typename TypeAid<U, 16>::CoreType &s
)
{
return tMat4x4<T>(
m[0] + s,
m[1] + s,
m[2] + s,
m[3] + s);
}
template <typename T, typename U>
inline tMat4x4<T> operator+
(
const typename TypeAid<T, 16>::CoreType &s,
tMat4x4<U> const & m
)
{
return tMat4x4<T>(
m[0] + s,
m[1] + s,
m[2] + s,
m[3] + s);
}
template <typename T, typename U>
inline tMat4x4<T> operator+
(
tMat4x4<T> const & m1,
tMat4x4<U> const & m2
)
{
return tMat4x4<T>(
m1[0] + m2[0],
m1[1] + m2[1],
m1[2] + m2[2],
m1[3] + m2[3]);
}
template <typename T, typename U>
inline tMat4x4<T> operator-
(
tMat4x4<T> const & m,
const typename TypeAid<U, 16>::CoreType &s
)
{
return tMat4x4<T>(
m[0] - s,
m[1] - s,
m[2] - s,
m[3] - s);
}
template <typename T, typename U>
inline tMat4x4<T> operator-
(
const typename TypeAid<T, 16>::CoreType &s,
tMat4x4<U> const & m
)
{
return tMat4x4<T>(
s - m[0],
s - m[1],
s - m[2],
s - m[3]);
}
template <typename T>
inline tMat4x4<T> operator-
(
tMat4x4<T> const &m1,
tMat4x4<T> const &m2
)
{
return tMat4x4<T>(
m1[0] - m2[0],
m1[1] - m2[1],
m1[2] - m2[2],
m1[3] - m2[3]);
}
template <typename T, typename U>
inline tMat4x4<T> operator*
(
tMat4x4<T> const & m,
const typename TypeAid<U, 16>::CoreType &s
)
{
return tMat4x4<T>(
m[0] * s,
m[1] * s,
m[2] * s,
m[3] * s);
}
template <typename T, typename U>
inline tMat4x4<T> operator*
(
const typename TypeAid<U, 16>::CoreType &s,
tMat4x4<T> const & m
)
{
return tMat4x4<T>(
m[0] * s,
m[1] * s,
m[2] * s,
m[3] * s);
}
template <typename T, typename U>
inline tVec4<T> operator*
(
tMat4x4<T> const & m,
tVec4<U> const & v
)
{
tVec4<T> const Mov0(v[0]);
tVec4<T> const Mov1(v[1]);
tVec4<T> const Mul0 = m[0] * Mov0;
tVec4<T> const Mul1 = m[1] * Mov1;
tVec4<T> const Add0 = Mul0 + Mul1;
tVec4<T> const Mov2(v[2]);
tVec4<T> const Mov3(v[3]);
tVec4<T> const Mul2 = m[2] * Mov2;
tVec4<T> const Mul3 = m[3] * Mov3;
tVec4<T> const Add1 = Mul2 + Mul3;
tVec4<T> const Add2 = Add0 + Add1;
return Add2;
}
template <typename T, typename U>
inline tVec4<T> operator*
(
tVec4<T> const & v,
tMat4x4<T> const & m
)
{
return tMat4x4<T>(
m[0][0] * v[0] + m[0][1] * v[1] + m[0][2] * v[2] + m[0][3] * v[3],
m[1][0] * v[0] + m[1][1] * v[1] + m[1][2] * v[2] + m[1][3] * v[3],
m[2][0] * v[0] + m[2][1] * v[1] + m[2][2] * v[2] + m[2][3] * v[3],
m[3][0] * v[0] + m[3][1] * v[1] + m[3][2] * v[2] + m[3][3] * v[3]);
}
template <typename T, typename U>
inline tMat2x4<T> operator*
(
tMat4x4<T> const & m1,
tMat2x4<U> const & m2
)
{
return tMat2x4<T>(
m1[0][0] * m2[0][0] + m1[1][0] * m2[0][1] + m1[2][0] * m2[0][2] + m1[3][0] * m2[0][3],
m1[0][1] * m2[0][0] + m1[1][1] * m2[0][1] + m1[2][1] * m2[0][2] + m1[3][1] * m2[0][3],
m1[0][2] * m2[0][0] + m1[1][2] * m2[0][1] + m1[2][2] * m2[0][2] + m1[3][2] * m2[0][3],
m1[0][3] * m2[0][0] + m1[1][3] * m2[0][1] + m1[2][3] * m2[0][2] + m1[3][3] * m2[0][3],
m1[0][0] * m2[1][0] + m1[1][0] * m2[1][1] + m1[2][0] * m2[1][2] + m1[3][0] * m2[1][3],
m1[0][1] * m2[1][0] + m1[1][1] * m2[1][1] + m1[2][1] * m2[1][2] + m1[3][1] * m2[1][3],
m1[0][2] * m2[1][0] + m1[1][2] * m2[1][1] + m1[2][2] * m2[1][2] + m1[3][2] * m2[1][3],
m1[0][3] * m2[1][0] + m1[1][3] * m2[1][1] + m1[2][3] * m2[1][2] + m1[3][3] * m2[1][3]);
}
template <typename T, typename U>
inline tMat4x4<T> operator*(tMat4x4<T> const & m1, tMat4x4<U> const & m2)
{
tMat4x4<T> t; // write to temp
for (PDP::UShort i=0; i < 4; i++)
{
for (PDP::UShort j=0; j < 4; j++)
{
t[i][j] = m1[i][0]*m2[0][j] + m1[i][1]*m2[1][j] + m1[i][2]*m2[2][j] + m1[i][3]*m2[3][j];
}
}
return t;
}
template <typename T, typename U>
inline tMat3x4<T> operator*
(
tMat4x4<T> const & m1,
tMat3x4<U> const & m2
)
{
return tMat3x4<T>(
m1[0][0] * m2[0][0] + m1[1][0] * m2[0][1] + m1[2][0] * m2[0][2] + m1[3][0] * m2[0][3],
m1[0][1] * m2[0][0] + m1[1][1] * m2[0][1] + m1[2][1] * m2[0][2] + m1[3][1] * m2[0][3],
m1[0][2] * m2[0][0] + m1[1][2] * m2[0][1] + m1[2][2] * m2[0][2] + m1[3][2] * m2[0][3],
m1[0][3] * m2[0][0] + m1[1][3] * m2[0][1] + m1[2][3] * m2[0][2] + m1[3][3] * m2[0][3],
m1[0][0] * m2[1][0] + m1[1][0] * m2[1][1] + m1[2][0] * m2[1][2] + m1[3][0] * m2[1][3],
m1[0][1] * m2[1][0] + m1[1][1] * m2[1][1] + m1[2][1] * m2[1][2] + m1[3][1] * m2[1][3],
m1[0][2] * m2[1][0] + m1[1][2] * m2[1][1] + m1[2][2] * m2[1][2] + m1[3][2] * m2[1][3],
m1[0][3] * m2[1][0] + m1[1][3] * m2[1][1] + m1[2][3] * m2[1][2] + m1[3][3] * m2[1][3],
m1[0][0] * m2[2][0] + m1[1][0] * m2[2][1] + m1[2][0] * m2[2][2] + m1[3][0] * m2[2][3],
m1[0][1] * m2[2][0] + m1[1][1] * m2[2][1] + m1[2][1] * m2[2][2] + m1[3][1] * m2[2][3],
m1[0][2] * m2[2][0] + m1[1][2] * m2[2][1] + m1[2][2] * m2[2][2] + m1[3][2] * m2[2][3],
m1[0][3] * m2[2][0] + m1[1][3] * m2[2][1] + m1[2][3] * m2[2][2] + m1[3][3] * m2[2][3]);
}
template <typename T, typename U>
inline tMat4x4<T> operator*
(
tVec4<T> const & m1,
tMat4x4<U> const & m2
)
{
tMat4x4<T> const SrcA0 = m1[0];
tVec4<T> const SrcA1 = m1[1];
tVec4<T> const SrcA2 = m1[2];
tVec4<T> const SrcA3 = m1[3];
tVec4<T> const SrcB0 = m2[0];
tVec4<T> const SrcB1 = m2[1];
tVec4<T> const SrcB2 = m2[2];
tVec4<T> const SrcB3 = m2[3];
tVec4<T> Result(0);
Result[0] = SrcA0 * SrcB0[0] + SrcA1 * SrcB0[1] + SrcA2 * SrcB0[2] + SrcA3 * SrcB0[3];
Result[1] = SrcA0 * SrcB1[0] + SrcA1 * SrcB1[1] + SrcA2 * SrcB1[2] + SrcA3 * SrcB1[3];
Result[2] = SrcA0 * SrcB2[0] + SrcA1 * SrcB2[1] + SrcA2 * SrcB2[2] + SrcA3 * SrcB2[3];
Result[3] = SrcA0 * SrcB3[0] + SrcA1 * SrcB3[1] + SrcA2 * SrcB3[2] + SrcA3 * SrcB3[3];
return Result;
}
template <typename T, typename U>
inline tMat4x4<T> operator/
(
tMat4x4<T> const & m,
typename TypeAid<U, 16>::CoreType const & s
)
{
return tMat4x4<T>(
m[0] / s,
m[1] / s,
m[2] / s,
m[3] / s);
}
template <typename T, typename U>
inline tMat4x4<T> operator/
(
typename TypeAid<T, 16>::CoreType const & s,
tMat4x4<U> const & m
)
{
return tMat4x4<T>(
s / m[0],
s / m[1],
s / m[2],
s / m[3]);
}
template <typename T, typename U>
inline tVec4<T> operator/
(
tMat4x4<T> const & m,
tVec4<U> const & v
)
{
return compute_inversetMat4x4<T>::call(m)*v;
}
template <typename T, typename U>
inline tVec4<T> operator/
(
tVec4<T> const & v,
tMat4x4<U> const & m
)
{
return v * compute_inversetMat4x4<U>::call(m);
}
template <typename T, typename U>
inline tMat4x4<T> operator/
(
tMat4x4<T> const & m1,
tMat4x4<U> const & m2
)
{
tMat4x4<T> m1_copy(m1);
return m1_copy /= m2;
}
// Unary constant operators
template <typename T>
inline tMat4x4<T> const operator-
(
tMat4x4<T> const & m
)
{
return tMat4x4<T>(
-m[0],
-m[1],
-m[2],
-m[3]);
}
template <typename T>
inline tMat4x4<T> const operator++
(
tMat4x4<T> const & m,
int
)
{
return tMat4x4<T>(
m[0] + static_cast<T>(1),
m[1] + static_cast<T>(1),
m[2] + static_cast<T>(1),
m[3] + static_cast<T>(1));
}
template <typename T>
inline tMat4x4<T> const operator--
(
tMat4x4<T> const & m,
int
)
{
return tMat4x4<T>(
m[0] - static_cast<T>(1),
m[1] - static_cast<T>(1),
m[2] - static_cast<T>(1),
m[3] - static_cast<T>(1));
}
//////////////////////////////////////
// Boolean operators
template <typename T, typename U>
inline bool operator==
(
tMat4x4<T> const & m1,
tMat4x4<U> const & m2
)
{
return (m1[0] == m2[0]) && (m1[1] == m2[1]) && (m1[2] == m2[2]) && (m1[3] == m2[3]);
}
template <typename T, typename U>
inline bool operator!=
(
tMat4x4<T> const & m1,
tMat4x4<U> const & m2
)
{
return (m1[0] != m2[0]) || (m1[1] != m2[1]) || (m1[2] != m2[2]) || (m1[3] != m2[3]);
}
template <typename T, typename U>
inline tMat4x3<T> operator*
(
tMat4x3<T> const & m1,
tMat4x4<U> const & m2
)
{
return tMat4x3<T>(
m1[0][0] * m2[0][0] + m1[1][0] * m2[0][1] + m1[2][0] * m2[0][2] + m1[3][0] * m2[0][3],
m1[0][1] * m2[0][0] + m1[1][1] * m2[0][1] + m1[2][1] * m2[0][2] + m1[3][1] * m2[0][3],
m1[0][2] * m2[0][0] + m1[1][2] * m2[0][1] + m1[2][2] * m2[0][2] + m1[3][2] * m2[0][3],
m1[0][0] * m2[1][0] + m1[1][0] * m2[1][1] + m1[2][0] * m2[1][2] + m1[3][0] * m2[1][3],
m1[0][1] * m2[1][0] + m1[1][1] * m2[1][1] + m1[2][1] * m2[1][2] + m1[3][1] * m2[1][3],
m1[0][2] * m2[1][0] + m1[1][2] * m2[1][1] + m1[2][2] * m2[1][2] + m1[3][2] * m2[1][3],
m1[0][0] * m2[2][0] + m1[1][0] * m2[2][1] + m1[2][0] * m2[2][2] + m1[3][0] * m2[2][3],
m1[0][1] * m2[2][0] + m1[1][1] * m2[2][1] + m1[2][1] * m2[2][2] + m1[3][1] * m2[2][3],
m1[0][2] * m2[2][0] + m1[1][2] * m2[2][1] + m1[2][2] * m2[2][2] + m1[3][2] * m2[2][3],
m1[0][0] * m2[3][0] + m1[1][0] * m2[3][1] + m1[2][0] * m2[3][2] + m1[3][0] * m2[3][3],
m1[0][1] * m2[3][0] + m1[1][1] * m2[3][1] + m1[2][1] * m2[3][2] + m1[3][1] * m2[3][3],
m1[0][2] * m2[3][0] + m1[1][2] * m2[3][1] + m1[2][2] * m2[3][2] + m1[3][2] * m2[3][3]);
}
template <typename T, typename U>
inline tMat4x4<T> operator*
(
tMat3x4<T> const & m1,
tMat4x3<U> const & m2
)
{
const T & SrcA00 = m1[0][0];
const T & SrcA01 = m1[0][1];
const T & SrcA02 = m1[0][2];
const T & SrcA03 = m1[0][3];
const T & SrcA10 = m1[1][0];
const T & SrcA11 = m1[1][1];
const T & SrcA12 = m1[1][2];
const T & SrcA13 = m1[1][3];
const T & SrcA20 = m1[2][0];
const T & SrcA21 = m1[2][1];
const T & SrcA22 = m1[2][2];
const T & SrcA23 = m1[2][3];
const T & SrcB00 = m2[0][0];
const T & SrcB01 = m2[0][1];
const T & SrcB02 = m2[0][2];
const T & SrcB10 = m2[1][0];
const T & SrcB11 = m2[1][1];
const T & SrcB12 = m2[1][2];
const T & SrcB20 = m2[2][0];
const T & SrcB21 = m2[2][1];
const T & SrcB22 = m2[2][2];
const T & SrcB30 = m2[3][0];
const T & SrcB31 = m2[3][1];
const T & SrcB32 = m2[3][2];
tMat4x4<T> Result(T(0));
Result[0][0] = SrcA00 * SrcB00 + SrcA10 * SrcB01 + SrcA20 * SrcB02;
Result[0][1] = SrcA01 * SrcB00 + SrcA11 * SrcB01 + SrcA21 * SrcB02;
Result[0][2] = SrcA02 * SrcB00 + SrcA12 * SrcB01 + SrcA22 * SrcB02;
Result[0][3] = SrcA03 * SrcB00 + SrcA13 * SrcB01 + SrcA23 * SrcB02;
Result[1][0] = SrcA00 * SrcB10 + SrcA10 * SrcB11 + SrcA20 * SrcB12;
Result[1][1] = SrcA01 * SrcB10 + SrcA11 * SrcB11 + SrcA21 * SrcB12;
Result[1][2] = SrcA02 * SrcB10 + SrcA12 * SrcB11 + SrcA22 * SrcB12;
Result[1][3] = SrcA03 * SrcB10 + SrcA13 * SrcB11 + SrcA23 * SrcB12;
Result[2][0] = SrcA00 * SrcB20 + SrcA10 * SrcB21 + SrcA20 * SrcB22;
Result[2][1] = SrcA01 * SrcB20 + SrcA11 * SrcB21 + SrcA21 * SrcB22;
Result[2][2] = SrcA02 * SrcB20 + SrcA12 * SrcB21 + SrcA22 * SrcB22;
Result[2][3] = SrcA03 * SrcB20 + SrcA13 * SrcB21 + SrcA23 * SrcB22;
Result[3][0] = SrcA00 * SrcB30 + SrcA10 * SrcB31 + SrcA20 * SrcB32;
Result[3][1] = SrcA01 * SrcB30 + SrcA11 * SrcB31 + SrcA21 * SrcB32;
Result[3][2] = SrcA02 * SrcB30 + SrcA12 * SrcB31 + SrcA22 * SrcB32;
Result[3][3] = SrcA03 * SrcB30 + SrcA13 * SrcB31 + SrcA23 * SrcB32;
return Result;
}
template <typename T, typename U>
inline tMat4x2<T> operator*
(
tMat4x2<T> const & m1,
tMat4x4<U> const & m2
)
{
return tMat4x2<T>(
m1[0][0] * m2[0][0] + m1[1][0] * m2[0][1] + m1[2][0] * m2[0][2] + m1[3][0] * m2[0][3],
m1[0][1] * m2[0][0] + m1[1][1] * m2[0][1] + m1[2][1] * m2[0][2] + m1[3][1] * m2[0][3],
m1[0][0] * m2[1][0] + m1[1][0] * m2[1][1] + m1[2][0] * m2[1][2] + m1[3][0] * m2[1][3],
m1[0][1] * m2[1][0] + m1[1][1] * m2[1][1] + m1[2][1] * m2[1][2] + m1[3][1] * m2[1][3],
m1[0][0] * m2[2][0] + m1[1][0] * m2[2][1] + m1[2][0] * m2[2][2] + m1[3][0] * m2[2][3],
m1[0][1] * m2[2][0] + m1[1][1] * m2[2][1] + m1[2][1] * m2[2][2] + m1[3][1] * m2[2][3],
m1[0][0] * m2[3][0] + m1[1][0] * m2[3][1] + m1[2][0] * m2[3][2] + m1[3][0] * m2[3][3],
m1[0][1] * m2[3][0] + m1[1][1] * m2[3][1] + m1[2][1] * m2[3][2] + m1[3][1] * m2[3][3]);
}
template <typename T, typename U>
inline tMat4x4<T> operator*
(
tMat2x4<T> const & m1,
tMat4x2<U> const & m2
)
{
const T & SrcA00 = m1[0][0];
const T & SrcA01 = m1[0][1];
const T & SrcA02 = m1[0][2];
const T & SrcA03 = m1[0][3];
const T & SrcA10 = m1[1][0];
const T & SrcA11 = m1[1][1];
const T & SrcA12 = m1[1][2];
const T & SrcA13 = m1[1][3];
const T & SrcB00 = m2[0][0];
const T & SrcB01 = m2[0][1];
const T & SrcB10 = m2[1][0];
const T & SrcB11 = m2[1][1];
const T & SrcB20 = m2[2][0];
const T & SrcB21 = m2[2][1];
const T & SrcB30 = m2[3][0];
const T & SrcB31 = m2[3][1];
tMat4x4<T> Result(T(0));
Result[0][0] = SrcA00 * SrcB00 + SrcA10 * SrcB01;
Result[0][1] = SrcA01 * SrcB00 + SrcA11 * SrcB01;
Result[0][2] = SrcA02 * SrcB00 + SrcA12 * SrcB01;
Result[0][3] = SrcA03 * SrcB00 + SrcA13 * SrcB01;
Result[1][0] = SrcA00 * SrcB10 + SrcA10 * SrcB11;
Result[1][1] = SrcA01 * SrcB10 + SrcA11 * SrcB11;
Result[1][2] = SrcA02 * SrcB10 + SrcA12 * SrcB11;
Result[1][3] = SrcA03 * SrcB10 + SrcA13 * SrcB11;
Result[2][0] = SrcA00 * SrcB20 + SrcA10 * SrcB21;
Result[2][1] = SrcA01 * SrcB20 + SrcA11 * SrcB21;
Result[2][2] = SrcA02 * SrcB20 + SrcA12 * SrcB21;
Result[2][3] = SrcA03 * SrcB20 + SrcA13 * SrcB21;
Result[3][0] = SrcA00 * SrcB30 + SrcA10 * SrcB31;
Result[3][1] = SrcA01 * SrcB30 + SrcA11 * SrcB31;
Result[3][2] = SrcA02 * SrcB30 + SrcA12 * SrcB31;
Result[3][3] = SrcA03 * SrcB30 + SrcA13 * SrcB31;
return Result;
}
}
typedef Detail::tMat4x4<PDP::UInteger> UMat4x4;
typedef Detail::tMat4x4<PDP::Integer> IMat4x4;
typedef Detail::tMat4x4<float> Mat4x4;
typedef Detail::tMat4x4<double> DMat4x4;
typedef Detail::tMat4x4<unsigned short> USMat4x4;
typedef Detail::tMat4x4<short> SMat4x4;
//typedef Detail::tMat4x4<PDP::Half> HMat4x4;
}
namespace LD
{
namespace Detail
{
template<typename T>
struct StaticallySized<LD::Detail::tMat4x4<T>>: public LD::Detail::IntegralConstant<bool,true>
{
};
}
}
#endif
| 30,358 | 12,902 |
// Copyright (c) 2019 Álvaro Ceballos
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt
#ifndef CYNODELIC_METAFLAGS_TEST_PARSER_DEFAULT_PARAMETERS_EXTRA_ARGS_IN_BETWEEN_HPP
#define CYNODELIC_METAFLAGS_TEST_PARSER_DEFAULT_PARAMETERS_EXTRA_ARGS_IN_BETWEEN_HPP
CYNODELIC_TESTER_TEST_CASE(parser_default_parameters_extra_args_in_between);
CYNODELIC_TESTER_SECTION(parser_default_parameters_extra_args_in_between,all_long_flags_called)
{
using prs = mfl::parser<
mfl::flag<STRING_("first,f"),STRING_("..."),mfl::i32_arg<>>,
mfl::flag<STRING_("second,s"),STRING_("..."),mfl::i32_arg<>,mfl::i32_arg<>>,
mfl::flag<STRING_("third,t"),STRING_("..."),mfl::i32_arg<>,mfl::i32_arg<>,mfl::i32_arg<>>
>;
argv_maker test_argv(
"test",
"--first",
"1",
"extra_args",
"431","33",
"--second",
"1","2",
"__XYZ__",
"--third",
"1","2","3"
);
prs::parse(static_cast<int>(test_argv.size()),test_argv.data());
CYNODELIC_TESTER_CHECK_EQUALS(prs::starts_at(),1);
CYNODELIC_TESTER_CHECK_EQUALS(prs::last_parsed_argument_position(),13);
CYNODELIC_TESTER_CHECK_EQUALS(prs::finished_at(),13);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--first",0)),1);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--second",0)),1);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--second",1)),2);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--third",0)),1);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--third",1)),2);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--third",2)),3);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-f",0)),1);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-s",0)),1);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-s",1)),2);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-t",0)),1);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-t",1)),2);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-t",2)),3);
CYNODELIC_TESTER_CHECK_TRUE((WAS_CALLED(prs,"--first")));
CYNODELIC_TESTER_CHECK_TRUE((WAS_CALLED(prs,"--second")));
CYNODELIC_TESTER_CHECK_TRUE((WAS_CALLED(prs,"--third")));
}
CYNODELIC_TESTER_SECTION(parser_default_parameters_extra_args_in_between,single_long_flag_called)
{
using prs = mfl::parser<
mfl::flag<STRING_("first,f"),STRING_("..."),mfl::i32_arg<>>,
mfl::flag<STRING_("second,s"),STRING_("..."),mfl::i32_arg<>,mfl::i32_arg<>>,
mfl::flag<STRING_("third,t"),STRING_("..."),mfl::i32_arg<>,mfl::i32_arg<>,mfl::i32_arg<>>
>;
argv_maker test_argv(
"test",
"aaaaaaaaaa",
"12345",
"--first",
"12"
);
prs::parse(static_cast<int>(test_argv.size()),test_argv.data());
CYNODELIC_TESTER_MESSAGE
<< "prs::finished_at() = " << prs::finished_at();
CYNODELIC_TESTER_CHECK_EQUALS(prs::starts_at(),1);
CYNODELIC_TESTER_CHECK_EQUALS(prs::last_parsed_argument_position(),4);
CYNODELIC_TESTER_CHECK_EQUALS(prs::finished_at(),4);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--first",0,0)),12);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--second",0,0)),0);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--second",1,0)),0);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--third",0,0)),0);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--third",1,0)),0);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--third",2,0)),0);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-f",0,0)),12);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-s",0,0)),0);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-s",1,0)),0);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-t",0,0)),0);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-t",1,0)),0);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-t",2,0)),0);
CYNODELIC_TESTER_CHECK_TRUE((WAS_CALLED(prs,"--first")));
CYNODELIC_TESTER_CHECK_FALSE((WAS_CALLED(prs,"--second")));
CYNODELIC_TESTER_CHECK_FALSE((WAS_CALLED(prs,"--third")));
}
CYNODELIC_TESTER_SECTION(parser_default_parameters_extra_args_in_between,two_long_flags_called)
{
using prs = mfl::parser<
mfl::flag<STRING_("first,f"),STRING_("..."),mfl::i32_arg<>>,
mfl::flag<STRING_("second,s"),STRING_("..."),mfl::i32_arg<>,mfl::i32_arg<>>,
mfl::flag<STRING_("third,t"),STRING_("..."),mfl::i32_arg<>,mfl::i32_arg<>,mfl::i32_arg<>>
>;
argv_maker test_argv(
"test",
"--first",
"963",
"AAA",
"--extra_arg",
"--second",
"34","56"
);
prs::parse(static_cast<int>(test_argv.size()),test_argv.data());
CYNODELIC_TESTER_MESSAGE
<< "prs::finished_at() = " << prs::finished_at();
CYNODELIC_TESTER_CHECK_EQUALS(prs::starts_at(),1);
CYNODELIC_TESTER_CHECK_EQUALS(prs::last_parsed_argument_position(),7);
CYNODELIC_TESTER_CHECK_EQUALS(prs::finished_at(),7);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--first",0,0)),963);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--second",0,0)),34);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--second",1,0)),56);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--third",0,0)),0);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--third",1,0)),0);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--third",2,0)),0);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-f",0,0)),963);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-s",0,0)),34);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-s",1,0)),56);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-t",0,0)),0);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-t",1,0)),0);
CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-t",2,0)),0);
CYNODELIC_TESTER_CHECK_TRUE((WAS_CALLED(prs,"--first")));
CYNODELIC_TESTER_CHECK_TRUE((WAS_CALLED(prs,"--second")));
CYNODELIC_TESTER_CHECK_FALSE((WAS_CALLED(prs,"--third")));
}
#endif // CYNODELIC_METAFLAGS_TEST_PARSER_DEFAULT_PARAMETERS_EXTRA_ARGS_IN_BETWEEN_HPP
| 5,614 | 2,957 |
/*
Source File : Trace.cpp
Copyright 2011 Gal Kahana PDFWriter
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 "Trace.h"
#include "Log.h"
#include "SafeBufferMacrosDefs.h"
#include <stdio.h>
#include <stdarg.h>
Trace& Trace::DefaultTrace(){
static Trace default_trace;
return default_trace;
}
Trace::Trace(void)
{
mLog = NULL;
mLogFilePath = "Log.txt";
mShouldLog = false;
}
Trace::~Trace(void)
{
delete mLog;
}
void Trace::SetLogSettings(const std::string& inLogFilePath,bool inShouldLog,bool inPlaceUTF8Bom)
{
mShouldLog = inShouldLog;
mPlaceUTF8Bom = inPlaceUTF8Bom;
mLogFilePath = inLogFilePath;
mLogStream = NULL;
if(mLog != NULL)
{
delete mLog;
mLog = NULL;
//if(mShouldLog)
// mLog = new Log(mLogFilePath,inPlaceUTF8Bom);
}
}
void Trace::SetLogSettings(IByteWriter* inLogStream,bool inShouldLog)
{
mShouldLog = inShouldLog;
mLogStream = inLogStream;
mPlaceUTF8Bom = false;
if(mLog != NULL)
{
delete mLog;
mLog = NULL;
if(mShouldLog)
mLog = new Log(mLogStream);
}
}
void Trace::TraceToLog(const char* inFormat,...)
{
if(mShouldLog)
{
if(NULL == mLog)
{
if(mLogStream)
mLog = new Log(mLogStream);
else
mLog = new Log(mLogFilePath,mPlaceUTF8Bom);
}
va_list argptr;
va_start(argptr, inFormat);
SAFE_VSPRINTF(mBuffer, MAX_TRACE_SIZE,inFormat,argptr);
va_end(argptr);
mLog->LogEntry(std::string(mBuffer));
}
}
void Trace::TraceToLog(const char* inFormat,va_list inList)
{
if(mShouldLog)
{
if(NULL == mLog)
{
if(mLogStream)
mLog = new Log(mLogStream);
else
mLog = new Log(mLogFilePath,mPlaceUTF8Bom);
}
SAFE_VSPRINTF(mBuffer, MAX_TRACE_SIZE,inFormat,inList);
mLog->LogEntry(std::string(mBuffer));
}
}
| 2,242 | 916 |
/***************************************************************************
* Copyright (C) by GFZ Potsdam *
* *
* You can redistribute and/or modify this program under the *
* terms of the SeisComP Public License. *
* *
* 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 *
* SeisComP Public License for more details. *
***************************************************************************/
#include <seiscomp3/gui/map/rectangularprojection.h>
#include <seiscomp3/gui/map/texturecache.ipp>
#include <seiscomp3/math/geo.h>
#include <math.h>
#include <iostream>
#define deg2rad(d) (M_PI*(d)/180.0)
#define rad2deg(d) (180.0*(d)/M_PI)
#define HALF_PI (M_PI/2)
const qreal ooPi = 1.0 / M_PI;
namespace Seiscomp {
namespace Gui {
namespace Map {
REGISTER_PROJECTION_INTERFACE(RectangularProjection, "Rectangular");
namespace {
const qreal ooLat = 1.0 / 90.0;
const qreal ooLon = 1.0 / 180.0;
bool checkPrecision(double val, int scale) {
double sval = val*scale;
return fabs(sval-round(sval)) < 1E-8;
}
QString lat2String(qreal lat) {
if ( checkPrecision(lat, 1) )
return QString("%1%2").arg(abs((int)lat)).arg(lat < 0?" S":lat > 0?" N":"");
else if ( checkPrecision(lat, 10) )
return QString("%1%2").arg(fabs(lat), 0, 'f', 1).arg(lat < 0?" S":lat > 0?" N":"");
else if ( checkPrecision(lat, 100) )
return QString("%1%2").arg(fabs(lat), 0, 'f', 2).arg(lat < 0?" S":lat > 0?" N":"");
else if ( checkPrecision(lat, 1000) )
return QString("%1%2").arg(fabs(lat), 0, 'f', 3).arg(lat < 0?" S":lat > 0?" N":"");
else if ( checkPrecision(lat, 10000) )
return QString("%1%2").arg(fabs(lat), 0, 'f', 4).arg(lat < 0?" S":lat > 0?" N":"");
else
return QString("%1%2").arg(fabs(lat), 0, 'f', 5).arg(lat < 0?" S":lat > 0?" N":"");
}
QString lon2String(qreal lon) {
lon = fmod(lon, 360.0);
if ( lon < 0 ) lon += 360.0;
if ( lon > 180.0 ) lon -= 360.0;
if ( checkPrecision(lon, 1) )
return QString("%1%2").arg(abs((int)lon)).arg(lon < 0?" W":lon > 0?" E":"");
else if ( checkPrecision(lon, 10) )
return QString("%1%2").arg(fabs(lon), 0, 'f', 1).arg(lon < 0?" W":lon > 0?" E":"");
else if ( checkPrecision(lon, 100) )
return QString("%1%2").arg(fabs(lon), 0, 'f', 2).arg(lon < 0?" W":lon > 0?" E":"");
else if ( checkPrecision(lon, 1000) )
return QString("%1%2").arg(fabs(lon), 0, 'f', 3).arg(lon < 0?" W":lon > 0?" E":"");
else if ( checkPrecision(lon, 10000) )
return QString("%1%2").arg(fabs(lon), 0, 'f', 4).arg(lon < 0?" W":lon > 0?" E":"");
else
return QString("%1%2").arg(fabs(lon), 0, 'f', 5).arg(lon < 0?" W":lon > 0?" E":"");
}
}
RectangularProjection::RectangularProjection()
: Projection() {
_enableLowZoom = false;
}
void RectangularProjection::setLowZoomEnabled(bool e) {
_enableLowZoom = e;
}
bool RectangularProjection::isRectangular() const {
return true;
}
bool RectangularProjection::wantsGridAntialiasing() const {
return false;
}
template <typename PROC>
void RectangularProjection::render(QImage &img, TextureCache *cache) {
_screenRadius = std::min(_width*0.25, _height*0.5);
QSize size(img.size());
qreal radius = _screenRadius * _radius;
double dt;
qreal visibleRadius;
if ( !_enableLowZoom ) {
if ( radius < _halfWidth )
radius = _width*0.25;
if ( radius < _halfHeight )
radius = _height*0.5;
visibleRadius = radius / _screenRadius;
}
else
visibleRadius = _radius;
dt = 1.0 / qreal(radius-1);
setVisibleRadius(visibleRadius);
QPoint center = QPoint(_halfWidth, _halfHeight);
int fromY, toY;
fromY = 0;
toY = size.height();
qreal iyf = center.y() * dt;
if ( iyf > 1.0 ) {
if ( _enableLowZoom ) {
fromY = (iyf - 1.0) * radius;
toY = img.height() - fromY;
}
iyf = 1.0;
}
QRgb *data = (QRgb *)img.bits();
int centerX = center.x();
qreal upY = _center.y() + iyf;
qreal downY = upY - (toY - fromY) * dt;
if ( downY < -1.0 ) {
downY = -1.0;
upY = downY + (toY - fromY) * dt;
_visibleCenter.setY((upY + downY) * 0.5);
}
if ( upY > 1.0 ) {
upY = 1.0;
downY = upY - (toY - fromY) * dt;
_visibleCenter.setY((upY + downY) * 0.5);
}
data += fromY * img.width();
qreal y = upY;
//qreal ixf = (qreal)centerX / radius;
qreal ixf = 2.0;
qint64 pxf = qint64(ixf*radius);
qint64 fx, tx;
fx = centerX - pxf;
tx = centerX + pxf;
if ( fx < 0 ) {
ixf += fx * dt;
fx = 0;
}
// Clip to left border
if ( tx < 2 ) tx = 0;
// Clip to right border
if ( tx >= size.width()-2 ) tx = size.width()-1;
int fromX = (int)fx;
int toX = (int)tx;
if ( cache == NULL ) return;
qreal pixelRatio = 2.0*_scale / cache->tileHeight();
if ( cache->isMercatorProjected() )
pixelRatio *= 2;
if ( pixelRatio < 1 ) pixelRatio = 1;
int level = (int)(log(pixelRatio) / log(2.0) + 0.7);
if ( level > cache->maxLevel() )
level = cache->maxLevel();
qreal leftX = 2.0*_center.x() - ixf;
qreal rightX = 2.0*_center.x() + ixf;
int pixels = toX - fromX + 1;
Coord leftTu;
Coord rightTu;
leftTu.value = (leftX*0.5+1.0) * Coord::value_type(Coord::fraction_half_max);
rightTu.value = (rightX*0.5+1.0) * Coord::value_type(Coord::fraction_half_max);
if ( cache->isMercatorProjected() ) {
for ( int i = fromY; i < toY; ++i, y -= dt ) {
if ( y <= -1.0 ) y = -1.0 + dt;
Coord tv;
qreal lat = y;
if ( lat > 0.94 ) lat = 0.94;
else if ( lat < -0.94 ) lat = -0.94;
lat = ooPi*asinh(tan(lat*HALF_PI));
tv.value = (1.0f-lat) * Coord::value_type(Coord::fraction_half_max);
PROC::fetch(cache, data[fromX], leftTu, tv, level);
PROC::fetch(cache, data[toX], rightTu, tv, level);
// Shift only by 30 bits to keep the sign bit in the lower 32 bit
Coord::value_type xDelta = rightTu.value - leftTu.value;
qint64 stepU = (qint64(xDelta) << 30) / pixels;
qint64 stepper;
Coord lon;
stepper = qint64(leftTu.value) << 30;
stepper += stepU;
for ( int k = 1; k < pixels; ++k ) {
lon.value = stepper >> 30;
PROC::fetch(cache, data[fromX + k], lon, tv, level);
stepper += stepU;
}
data += size.width();
}
}
else {
for ( int i = fromY; i < toY; ++i, y -= dt ) {
if ( y <= -1.0 ) y = -1.0 + dt;
Coord tv;
tv.value = (1.0-y) * Coord::value_type(Coord::fraction_half_max);
PROC::fetch(cache, data[fromX], leftTu, tv, level);
PROC::fetch(cache, data[toX], rightTu, tv, level);
// Shift only by 30 bits to keep the sign bit in the lower 32 bit
Coord::value_type xDelta = rightTu.value - leftTu.value;
qint64 stepU = (qint64(xDelta) << 30) / pixels;
qint64 stepper;
Coord lon;
stepper = qint64(leftTu.value) << 30;
stepper += stepU;
for ( int k = 1; k < pixels; ++k ) {
lon.value = stepper >> 30;
PROC::fetch(cache, data[fromX + k], lon, tv, level);
stepper += stepU;
}
data += size.width();
}
}
}
void RectangularProjection::render(QImage& img, bool highQuality, TextureCache *cache) {
if ( highQuality )
render<BilinearFilter>(img, cache);
else
render<NearestFilter>(img, cache);
}
bool RectangularProjection::project(QPoint &screenCoords, const QPointF &geoCoords) const {
qreal x = geoCoords.x() * ooLon;
qreal lat = geoCoords.y();
if ( lat > 90.0 ) {
lat = 180.0 - lat;
x += 1.0;
if ( x > 1.0 ) x -= 2.0;
}
else if ( lat < -90.0 ) {
lat = -180.0 - lat;
x += 1.0;
if ( x > 1.0 ) x -= 2.0;
}
qreal y = lat * ooLat;
x = (x - _visibleCenter.x()) * _halfMapWidth;
y = (y - _visibleCenter.y()) * _scale;
if ( x > _halfMapWidth )
x -= _mapWidth;
if ( x < -_halfMapWidth )
x += _mapWidth;
screenCoords.setX(_halfWidth + x);
screenCoords.setY(_halfHeight - y);
return true;
}
bool RectangularProjection::unproject(QPointF &geoCoords, const QPoint &screenCoords) const {
qreal x = screenCoords.x() - _halfWidth;
qreal y = _halfHeight - screenCoords.y();
if ( x < -_halfMapWidth || x > _halfMapWidth ) return false;
if ( y < -_scale || y > _scale ) return false;
x = x / (qreal)_halfMapWidth + _visibleCenter.x();
y = y / (qreal)_scale + _visibleCenter.y();
x *= 180.0;
y *= 90.0;
if ( x < -180.0 ) x += 360.0;
if ( x > 180.0 ) x -= 360.0;
geoCoords.setX(x);
geoCoords.setY(y);
return true;
}
void RectangularProjection::centerOn(const QPointF &geoCoords) {
qreal x = geoCoords.x() * ooLon;
qreal y = geoCoords.y() * ooLat;
if ( x < -1.0 ) x += 2.0;
if ( x > 1.0 ) x -= 2.0;
if ( y < -1.0 ) y = -1.0;
if ( y > 1.0 ) y = 1.0;
_center = QPointF(x,y);
_visibleCenter = _center;
}
int RectangularProjection::lineSteps(const QPointF &p0, const QPointF &p1) {
// Calculate the distance between p0 and p1 in pixels and
// divide its manhattanLength by 20
double dist, azi1, azi2;
Math::Geo::delazi(p0.y(), p0.x(), p1.y(), p1.x(), &dist, &azi1, &azi2);
if ( azi1 > 359.0 && azi1 < 1.0 && azi1 > 179.0 && azi1 < 180.0 )
return 1;
//return dist * pixelPerDegree() * (1.0 / 20.0);
return 20;
}
void RectangularProjection::drawImage(QImage &buffer, const QRectF &geoReference,
const QImage &image, bool highQuality) {
if ( image.format() != QImage::Format_RGB32 &&
image.format() != QImage::Format_ARGB32 )
return;
bool useAlpha = image.format() == QImage::Format_ARGB32;
QPoint p00, p11;
qreal minLat, maxLat;
qreal minLon, maxLon;
minLat = geoReference.top();
maxLat = geoReference.bottom();
minLon = geoReference.left();
maxLon = geoReference.right();
if ( minLat > maxLat ) std::swap(minLat, maxLat);
project(p00, QPointF(minLon, minLat));
project(p11, QPointF(maxLon, maxLat));
bool wrap = fabs(maxLon - minLon) >= 360.;
int x0 = p00.x();
int x1 = p11.x();
int y0 = p00.y();
int y1 = p11.y();
// X can be wrapped, so we have to check more cases
if ( geoReference.width() < 180.0f ) {
if ( x0 >= _width ) {
if ( x1 < 0 || x1 >= _width ) return;
}
if ( x1 < 0 ) {
if ( x0 < 0 || x0 >= _width ) return;
}
}
if ( y0 > y1 ) std::swap(y0,y1);
// Y has no wrapping, so the checks are more simply
if ( y0 >= _height ) return;
if ( y1 < 0 ) return;
bool drawTwoParts = false;
// Quick hack just for testing
// TODO: This special case has to be handled.
if ( x0 >= x1 || wrap ) {
drawTwoParts = true;
if ( x0 >= x1 ) x0 -= _mapWidth;
else if ( wrap ) x0 = x1 - _mapWidth;
}
int scaledWidth = x1-x0+1;
int scaledHeight = y1-y0+1;
Coord ratioX, ratioY;
ratioX.parts.hi = image.width();
ratioX.parts.lo = 0;
ratioY.parts.hi = image.height();
ratioY.parts.lo = 0;
ratioX.value /= scaledWidth;
ratioY.value /= scaledHeight;
while ( true ) {
int width = image.width();
int height = image.height();
Coord xofs, yofs;
int x0c = x0,
y0c = y0,
x1c = x1;
// Something has to be painted
const QRgb *data = (const QRgb*)image.bits();
QRgb *targetData = (QRgb*)buffer.bits();
int targetWidth = buffer.width();
if ( x0c < 0 ) {
xofs.value = ratioX.value * -x0c;
x0c = 0;
}
else
xofs.value = 0;
if ( x1c >= _width )
x1c = _width-1;
if ( y0c < 0 ) {
yofs.value = ratioY.value * -y0c;
height -= yofs.parts.hi;
data += image.width() * yofs.parts.hi;
y0c = 0;
}
else
yofs.value = 0;
if ( y1 >= _height )
y1 = _height-1;
targetData += targetWidth * y0c + x0c;
Coord y;
y.parts.hi = 0;
y.parts.lo = yofs.parts.lo;
if ( useAlpha ) {
if ( highQuality ) {
for ( int i = y0c; i <= y1; ++i ) {
QRgb *targetPixel = targetData;
Coord x;
x.value = xofs.value;
for ( int j = x0c; j <= x1c; ++j ) {
QRgb c;
getTexelBilinear(c, data, width, height, x, y);
int alpha = qAlpha(c);
int iAlpha = 255 - alpha;
*targetPixel = qRgb(
(qRed(c)*alpha + qRed(*targetPixel)*iAlpha) >> 8,
(qGreen(c)*alpha + qGreen(*targetPixel)*iAlpha) >> 8,
(qBlue(c)*alpha + qBlue(*targetPixel)*iAlpha) >> 8
);
++targetPixel;
x.value += ratioX.value;
}
targetData += targetWidth;
y.value += ratioY.value;
int skipLines = y.parts.hi;
height -= skipLines;
while ( skipLines ) {
data += width;
--skipLines;
}
y.parts.hi = 0;
}
}
else {
for ( int i = y0c; i <= y1; ++i ) {
QRgb *targetPixel = targetData;
Coord x;
x.value = xofs.value;
for ( int j = x0c; j <= x1c; ++j ) {
QRgb c = data[x.parts.hi];
int alpha = qAlpha(c);
int iAlpha = 255 - alpha;
*targetPixel = qRgb(
(qRed(c)*alpha + qRed(*targetPixel)*iAlpha) >> 8,
(qGreen(c)*alpha + qGreen(*targetPixel)*iAlpha) >> 8,
(qBlue(c)*alpha + qBlue(*targetPixel)*iAlpha) >> 8
);
++targetPixel;
x.value += ratioX.value;
}
targetData += targetWidth;
y.value += ratioY.value;
int skipLines = y.parts.hi;
while ( skipLines ) {
data += width;
--skipLines;
}
y.parts.hi = 0;
}
}
}
else {
if ( highQuality ) {
for ( int i = y0c; i <= y1; ++i ) {
QRgb *targetPixel = targetData;
Coord x;
x.value = xofs.value;
for ( int j = x0c; j <= x1c; ++j ) {
getTexelBilinear(*targetPixel, data, width, height, x, y);
++targetPixel;
x.value += ratioX.value;
}
targetData += targetWidth;
y.value += ratioY.value;
int skipLines = y.parts.hi;
height -= skipLines;
while ( skipLines ) {
data += width;
--skipLines;
}
y.parts.hi = 0;
}
}
else {
for ( int i = y0c; i <= y1; ++i ) {
QRgb *targetPixel = targetData;
Coord x;
x.value = xofs.value;
for ( int j = x0c; j <= x1c; ++j ) {
*targetPixel = data[x.parts.hi];
++targetPixel;
x.value += ratioX.value;
}
targetData += targetWidth;
y.value += ratioY.value;
int skipLines = y.parts.hi;
while ( skipLines ) {
data += width;
--skipLines;
}
y.parts.hi = 0;
}
}
}
if ( drawTwoParts ) {
x0 += _mapWidth;
x1 += _mapWidth;
drawTwoParts = false;
}
else
break;
}
}
bool RectangularProjection::drawLine(QPainter &p, const QPointF &from, const QPointF &to) {
QPoint x0, x1;
bool x0Visible, x1Visible;
x0Visible = project(x0, from);
x1Visible = project(x1, to);
if ( !x0Visible || !x1Visible )
return false;
qreal degx0 = fmod(from.x(), 360.0);
qreal degx1 = fmod(to.x(), 360.0);
int dir = x1.x() - x0.x();
qreal degdir = degx1 - degx0;
if ( degdir > 180 )
degdir -= 360;
if ( degdir < -180 )
degdir += 360;
if ( (dir * degdir) < 0 ) {
if ( x1.x() > x0.x() ) {
int leftX = _halfWidth - _halfMapWidth;
int leftY = x0.y() + ((leftX - x0.x()) * (x1.y() - x0.y())) / ((x1.x() - _mapWidth) - x0.x());
p.drawLine(x0, QPoint(leftX, leftY));
p.drawLine(QPoint(leftX + _mapWidth, leftY), x1);
}
else {
int rightX = _halfWidth + _halfMapWidth;
int rightY = x0.y() + ((rightX - x0.x()) * (x1.y() - x0.y())) / ((x1.x() + _mapWidth) - x0.x());
p.drawLine(x0, QPoint(rightX, rightY));
p.drawLine(QPoint(rightX - _mapWidth, rightY), x1);
}
}
else
p.drawLine(x0, x1);
return true;
}
void RectangularProjection::moveTo(const QPointF &p) {
Projection::moveTo(p);
_cursorLon = fmod(p.x(), 360.0);
}
bool RectangularProjection::lineTo(QPainter &p, const QPointF &to) {
QPoint x1;
bool x1Visible;
x1Visible = project(x1, to);
qreal degx1 = fmod(to.x(), 360.0);
if ( !_cursorVisible || !x1Visible ) {
_cursorLon = degx1;
_cursor = x1;
_cursorVisible = x1Visible;
return false;
}
int dir = x1.x() - _cursor.x();
qreal degdir = degx1 - _cursorLon;
if ( degdir > 180 )
degdir -= 360;
if ( degdir < -180 )
degdir += 360;
QPoint &x0 = _cursor;
if ( (dir * degdir) < 0 ) {
if ( x1.x() > x0.x() ) {
int leftX = _halfWidth - _halfMapWidth;
int leftY = x0.y() + ((leftX - x0.x()) * (x1.y() - x0.y())) / ((x1.x() - _mapWidth) - x0.x());
p.drawLine(x0, QPoint(leftX, leftY));
p.drawLine(QPoint(leftX + _mapWidth, leftY), x1);
}
else {
int rightX = _halfWidth + _halfMapWidth;
int rightY = x0.y() + ((rightX - x0.x()) * (x1.y() - x0.y())) / ((x1.x() + _mapWidth) - x0.x());
p.drawLine(x0, QPoint(rightX, rightY));
p.drawLine(QPoint(rightX - _mapWidth, rightY), x1);
}
}
else
p.drawLine(x0, x1);
_cursorLon = degx1;
_cursor = x1;
_cursorVisible = x1Visible;
return true;
}
bool RectangularProjection::drawLatCircle(QPainter &p, qreal lon) {
QPoint pp;
if ( project(pp, QPointF(lon, 90)) ) {
if ( pp.x() >= 0 && pp.x() < _width ) {
int top = std::max(0, pp.y());
int bottom = std::min(_height-1, pp.y() + (int)_halfMapWidth);
p.drawLine(pp.x(), top, pp.x(), bottom);
p.drawText(QRect((int)pp.x() + 2, top, _width, _height), Qt::AlignLeft | Qt::AlignTop | Qt::TextSingleLine, lon2String(lon));
return true;
}
}
return false;
}
bool RectangularProjection::drawLonCircle(QPainter &p, qreal lat) {
QPoint pp;
if ( project(pp, QPointF(0, lat)) ) {
if ( pp.y() >= 0 && pp.y() < _height ) {
int left = std::max(0,_halfWidth - (int)(_scale*2));
int right = std::min(_width-1, _halfWidth + (int)(_scale*2));
p.drawLine(left, pp.y(), right, pp.y());
p.drawText(QRect(left, pp.y(), _width, _height), Qt::AlignLeft | Qt::AlignTop | Qt::TextSingleLine, lat2String(lat));
return true;
}
}
return false;
}
}
}
}
| 17,796 | 8,491 |
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/mgn/model/IdentificationHints.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace mgn
{
namespace Model
{
IdentificationHints::IdentificationHints() :
m_awsInstanceIDHasBeenSet(false),
m_fqdnHasBeenSet(false),
m_hostnameHasBeenSet(false),
m_vmPathHasBeenSet(false),
m_vmWareUuidHasBeenSet(false)
{
}
IdentificationHints::IdentificationHints(JsonView jsonValue) :
m_awsInstanceIDHasBeenSet(false),
m_fqdnHasBeenSet(false),
m_hostnameHasBeenSet(false),
m_vmPathHasBeenSet(false),
m_vmWareUuidHasBeenSet(false)
{
*this = jsonValue;
}
IdentificationHints& IdentificationHints::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("awsInstanceID"))
{
m_awsInstanceID = jsonValue.GetString("awsInstanceID");
m_awsInstanceIDHasBeenSet = true;
}
if(jsonValue.ValueExists("fqdn"))
{
m_fqdn = jsonValue.GetString("fqdn");
m_fqdnHasBeenSet = true;
}
if(jsonValue.ValueExists("hostname"))
{
m_hostname = jsonValue.GetString("hostname");
m_hostnameHasBeenSet = true;
}
if(jsonValue.ValueExists("vmPath"))
{
m_vmPath = jsonValue.GetString("vmPath");
m_vmPathHasBeenSet = true;
}
if(jsonValue.ValueExists("vmWareUuid"))
{
m_vmWareUuid = jsonValue.GetString("vmWareUuid");
m_vmWareUuidHasBeenSet = true;
}
return *this;
}
JsonValue IdentificationHints::Jsonize() const
{
JsonValue payload;
if(m_awsInstanceIDHasBeenSet)
{
payload.WithString("awsInstanceID", m_awsInstanceID);
}
if(m_fqdnHasBeenSet)
{
payload.WithString("fqdn", m_fqdn);
}
if(m_hostnameHasBeenSet)
{
payload.WithString("hostname", m_hostname);
}
if(m_vmPathHasBeenSet)
{
payload.WithString("vmPath", m_vmPath);
}
if(m_vmWareUuidHasBeenSet)
{
payload.WithString("vmWareUuid", m_vmWareUuid);
}
return payload;
}
} // namespace Model
} // namespace mgn
} // namespace Aws
| 2,158 | 848 |
#ifndef WPP_VILL_RUNTIME_H
#define WPP_VILL_RUNTIME_H
#include <vector>
#include "wlexer.hpp"
#include "werr.hpp"
#include "errors.hpp"
using namespace wpp;
using namespace wpp::how;
namespace mill{
struct vill_type
{
typedef unsigned char int_u8;
typedef unsigned short int_u16;
typedef unsigned int int_u32;
typedef unsigned __int64 int_u64;
typedef char int_i8;
typedef short int_i16;
typedef int int_i32;
typedef __int64 int_i64;
typedef float float32;
typedef double float64;
typedef long double float80;
typedef char* astring;
typedef wchar_t* string;
typedef unsigned char ubyte;
typedef char byte;
typedef char achar;
typedef wchar_t wchar;
typedef void* obj_ptr;
typedef bool boolean;
};
struct vill_register
{
union
{
vill_type::int_u8 val_u8;
vill_type::int_u16 val_u16;
vill_type::int_u32 val_u32;
vill_type::int_u64 val_u64;
vill_type::int_i8 val_i8;
vill_type::int_i16 val_i16;
vill_type::int_i32 val_i32;
vill_type::int_i64 val_i64;
vill_type::float32 val_f32;
vill_type::float64 val_f64;
vill_type::float80 val_f80;
vill_type::boolean val_bool;
vill_type::obj_ptr val_ptr;
vill_type::string val_string;
vill_type::astring val_astring;
};
};
struct vill_flag_register
{
unsigned int C : 1; //carry
unsigned int Z : 1; //zero
unsigned int S : 1; //sign
unsigned int O : 1; //overflow
};
class vill_runtime
{
public:
static const int void_ptr_size = 4;
public:
std::vector<vill_register>* ptr_registeres;
vill_flag_register flag_register;
int* ptr_stackes;
int* stack_bp;
int* stack_sp;
public:
void set_err_ptr(wErr* err_ptr);
wErr* get_err_ptr();
void error(error::err nError, const wchar_t* str, wtoken& tk);
private:
wErr* err_ptr_;
public:
//std::map<std::wstring /*dll*/,std::map<std::wstring /*alias*/, int>> * ptr_extern_method_;
vill_runtime();
~vill_runtime();
public:
void reset();
//int step_next();
//int step_continue();
};
} //namespace mill
#endif //WPP_VILL_RUNTIME
| 2,041 | 989 |
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qfbvthandler_p.h"
#include <QtCore/private/qcrashhandler_p.h>
#include <QtGui/private/qguiapplication_p.h>
#if defined(Q_OS_LINUX) && !defined(QT_NO_EVDEV)
#define HAS_VT
#endif
#ifdef HAS_VT
#include <sys/ioctl.h>
#include <linux/kd.h>
#ifdef K_OFF
#define KBD_OFF_MODE K_OFF
#else
#define KBD_OFF_MODE K_RAW
#endif
#endif // HAS_VT
QT_BEGIN_NAMESPACE
QFbVtHandler *QFbVtHandler::self = 0;
QFbVtHandler::QFbVtHandler(QObject *parent)
: QObject(parent), m_tty(-1)
{
Q_ASSERT(!self);
self = this;
#ifdef HAS_VT
if (!isatty(0))
return;
m_tty = 0;
::ioctl(m_tty, KDGKBMODE, &m_oldKbdMode);
if (!qgetenv("QT_QPA_ENABLE_TERMINAL_KEYBOARD").toInt()) {
::ioctl(m_tty, KDSKBMODE, KBD_OFF_MODE);
QGuiApplicationPrivate *appd = QGuiApplicationPrivate::instance();
Q_ASSERT(appd);
QSegfaultHandler::initialize(appd->argv, appd->argc);
QSegfaultHandler::installCrashHandler(crashHandler);
}
#endif
}
QFbVtHandler::~QFbVtHandler()
{
self->cleanup();
self = 0;
}
void QFbVtHandler::cleanup()
{
if (m_tty == -1)
return;
#ifdef HAS_VT
::ioctl(m_tty, KDSKBMODE, m_oldKbdMode);
#endif
}
void QFbVtHandler::crashHandler()
{
Q_ASSERT(self);
self->cleanup();
}
QT_END_NAMESPACE
| 3,257 | 1,105 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file contains stubs for some Chrome for Android specific code that is
// needed to compile some tests.
#include "chrome/browser/android/tab_android.h"
// static
TabAndroid* TabAndroid::FromWebContents(content::WebContents* web_contents) {
return NULL;
}
// static
TabAndroid* TabAndroid::GetNativeTab(JNIEnv* env, jobject obj) {
return NULL;
}
| 529 | 162 |
#include "JWModules.hpp"
RACK_PLUGIN_MODEL_DECLARE(JW_Modules, BlankPanelSmall);
RACK_PLUGIN_MODEL_DECLARE(JW_Modules, BlankPanelMedium);
RACK_PLUGIN_MODEL_DECLARE(JW_Modules, BlankPanelLarge);
RACK_PLUGIN_MODEL_DECLARE(JW_Modules, Cat);
RACK_PLUGIN_MODEL_DECLARE(JW_Modules, BouncyBalls);
RACK_PLUGIN_MODEL_DECLARE(JW_Modules, FullScope);
RACK_PLUGIN_MODEL_DECLARE(JW_Modules, GridSeq);
RACK_PLUGIN_MODEL_DECLARE(JW_Modules, Quantizer);
RACK_PLUGIN_MODEL_DECLARE(JW_Modules, MinMax);
RACK_PLUGIN_MODEL_DECLARE(JW_Modules, NoteSeq);
RACK_PLUGIN_MODEL_DECLARE(JW_Modules, SimpleClock);
RACK_PLUGIN_MODEL_DECLARE(JW_Modules, ThingThing);
RACK_PLUGIN_MODEL_DECLARE(JW_Modules, WavHead);
RACK_PLUGIN_MODEL_DECLARE(JW_Modules, XYPad);
RACK_PLUGIN_INIT(JW_Modules) {
RACK_PLUGIN_INIT_ID();
RACK_PLUGIN_INIT_VERSION("0.6.3");
RACK_PLUGIN_INIT_WEBSITE("https://github.com/jeremywen/JW-Modules");
RACK_PLUGIN_MODEL_ADD(JW_Modules, BlankPanelSmall);
RACK_PLUGIN_MODEL_ADD(JW_Modules, BlankPanelMedium);
RACK_PLUGIN_MODEL_ADD(JW_Modules, BlankPanelLarge);
RACK_PLUGIN_MODEL_ADD(JW_Modules, Cat);
RACK_PLUGIN_MODEL_ADD(JW_Modules, BouncyBalls);
RACK_PLUGIN_MODEL_ADD(JW_Modules, FullScope);
RACK_PLUGIN_MODEL_ADD(JW_Modules, GridSeq);
RACK_PLUGIN_MODEL_ADD(JW_Modules, Quantizer);
RACK_PLUGIN_MODEL_ADD(JW_Modules, MinMax);
RACK_PLUGIN_MODEL_ADD(JW_Modules, NoteSeq);
RACK_PLUGIN_MODEL_ADD(JW_Modules, SimpleClock);
RACK_PLUGIN_MODEL_ADD(JW_Modules, ThingThing);
RACK_PLUGIN_MODEL_ADD(JW_Modules, WavHead);
RACK_PLUGIN_MODEL_ADD(JW_Modules, XYPad);
}
| 1,565 | 774 |
#pragma once
#ifndef GEODE_CACHEABLEBUILTINS_H_
#define GEODE_CACHEABLEBUILTINS_H_
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/** @file CacheableBuiltins.hpp
* @brief Contains generic template definitions for Cacheable types
* and instantiations for built-in types.
*/
#include <cstring>
#include "Cacheable.hpp"
#include "CacheableKey.hpp"
#include "Serializer.hpp"
#include "CacheableKeys.hpp"
#include "CacheableString.hpp"
namespace apache {
namespace geode {
namespace client {
/** sprintf implementation. */
extern int gf_sprintf(char* buffer, const char* fmt, ...);
/** snprintf implementation. */
extern int gf_snprintf(char* buffer, int32_t maxLength, const char* fmt, ...);
/** Template CacheableKey class for primitive types. */
template <typename TObj, int8_t TYPEID, const char* TYPENAME,
const char* SPRINTFSYM, int32_t STRSIZE>
class CacheableKeyType : public CacheableKey {
protected:
TObj m_value;
inline CacheableKeyType()
: m_value(apache::geode::client::serializer::zeroObject<TObj>()) {}
inline CacheableKeyType(const TObj value) : m_value(value) {}
public:
/** Gets the contained value. */
inline TObj value() const { return m_value; }
// Cacheable methods
/** Serialize this object to given <code>DataOutput</code>. */
virtual void toData(DataOutput& output) const {
apache::geode::client::serializer::writeObject(output, m_value);
}
/** Deserialize this object from given <code>DataInput</code>. */
virtual Serializable* fromData(DataInput& input) {
apache::geode::client::serializer::readObject(input, m_value);
return this;
}
/**
* Return the classId of the instance being serialized.
*
* This is used by deserialization to determine what instance
* type to create and deserialize into.
*/
virtual int32_t classId() const { return 0; }
/**
* Return the typeId byte of the instance being serialized.
*
* This is used by deserialization to determine what instance
* type to create and deserialize into.
*/
virtual int8_t typeId() const { return TYPEID; }
/** Return a string representation of the object. */
virtual CacheableStringPtr toString() const {
char buffer[STRSIZE + 1];
gf_sprintf(buffer, SPRINTFSYM, m_value);
return CacheableString::create(buffer);
}
// CacheableKey methods
/** Return the hashcode for this key. */
virtual int32_t hashcode() const {
return apache::geode::client::serializer::hashcode(m_value);
}
/** Return true if this key matches other. */
virtual bool operator==(const CacheableKey& other) const {
if (other.typeId() != TYPEID) {
return false;
}
const CacheableKeyType& otherValue =
static_cast<const CacheableKeyType&>(other);
return apache::geode::client::serializer::equals(m_value,
otherValue.m_value);
}
/** Return true if this key matches other key value. */
inline bool operator==(const TObj other) const {
return apache::geode::client::serializer::equals(m_value, other);
}
/**
* Copy the string form of the object into a char* buffer for
* logging purposes.
*/
virtual int32_t logString(char* buffer, int32_t maxLength) const {
char fmt[64];
gf_sprintf(fmt, "%s( %s )", TYPENAME, SPRINTFSYM);
return gf_snprintf(buffer, maxLength, fmt, m_value);
}
/**
* Return the size in bytes of the instance being serialized.
*
* This is used to determine whether the cache is using up more
* physical memory than it has been configured to use. The method can
* return zero if the user does not require the ability to control
* cache memory utilization.
*/
virtual uint32_t objectSize() const { return sizeof(CacheableKeyType); }
};
// Forward declaration for SharedArrayPtr
template <typename TObj, int8_t TYPEID>
class SharedArrayPtr;
/** Function to copy an array from source to destination. */
template <typename TObj>
inline void copyArray(TObj* dest, const TObj* src, int32_t length) {
std::memcpy(dest, src, length * sizeof(TObj));
}
/**
* Function to copy an array of <code>SharedPtr</code>s from
* source to destination.
*/
template <typename TObj>
inline void copyArray(SharedPtr<TObj>* dest, const SharedPtr<TObj>* src,
int32_t length) {
for (int32_t index = 0; index < length; index++) {
dest[index] = src[index];
}
}
/**
* Function to copy an array of <code>SharedArrayPtr</code>s from
* source to destination.
*/
template <typename TObj, int8_t TYPEID>
inline void copyArray(SharedArrayPtr<TObj, TYPEID>* dest,
const SharedArrayPtr<TObj, TYPEID>* src, int32_t length) {
for (int32_t index = 0; index < length; index++) {
dest[index] = src[index];
}
}
/** Template class for array of primitive types. */
template <typename TObj, int8_t TYPEID>
class CacheableArrayType : public Cacheable {
protected:
TObj* m_value;
int32_t m_length;
inline CacheableArrayType() : m_value(NULL), m_length(0) {}
inline CacheableArrayType(int32_t length) : m_length(length) {
if (length > 0) {
GF_NEW(m_value, TObj[length]);
}
}
inline CacheableArrayType(TObj* value, int32_t length)
: m_value(value), m_length(length) {}
inline CacheableArrayType(const TObj* value, int32_t length, bool copy)
: m_value(NULL), m_length(length) {
if (length > 0) {
GF_NEW(m_value, TObj[length]);
copyArray(m_value, value, length);
}
}
virtual ~CacheableArrayType() { GF_SAFE_DELETE_ARRAY(m_value); }
private:
// Private to disable copy constructor and assignment operator.
CacheableArrayType(const CacheableArrayType& other)
: m_value(other.m_value), m_length(other.m_length) {}
CacheableArrayType& operator=(const CacheableArrayType& other) {
return *this;
}
public:
/** Get the underlying array. */
inline const TObj* value() const { return m_value; }
/** Get the length of the array. */
inline int32_t length() const { return m_length; }
/** Get the element at given index. */
inline TObj operator[](uint32_t index) const {
if (static_cast<int32_t>(index) >= m_length) {
throw OutOfRangeException(
"CacheableArray::operator[]: Index out of range.");
}
return m_value[index];
}
// Cacheable methods
/** Serialize this object to the given <code>DataOutput</code>. */
virtual void toData(DataOutput& output) const {
apache::geode::client::serializer::writeObject(output, m_value, m_length);
}
/** Deserialize this object from the given <code>DataInput</code>. */
virtual Serializable* fromData(DataInput& input) {
GF_SAFE_DELETE_ARRAY(m_value);
apache::geode::client::serializer::readObject(input, m_value, m_length);
return this;
}
/**
* Return the classId of the instance being serialized.
*
* This is used by deserialization to determine what instance
* type to create and deserialize into.
*/
virtual int32_t classId() const { return 0; }
/**
* Return the typeId byte of the instance being serialized.
*
* This is used by deserialization to determine what instance
* type to create and deserialize into.
*/
virtual int8_t typeId() const { return TYPEID; }
/**
* Return the size in bytes of the instance being serialized.
*
* This is used to determine whether the cache is using up more
* physical memory than it has been configured to use. The method can
* return zero if the user does not require the ability to control
* cache memory utilization.
*/
virtual uint32_t objectSize() const {
return static_cast<uint32_t>(
sizeof(CacheableArrayType) +
apache::geode::client::serializer::objectSize(m_value, m_length));
}
};
/**
* Template class for CacheableArrayType SharedPtr's that adds [] operator
*/
template <typename TObj, int8_t TYPEID>
class SharedArrayPtr : public SharedPtr<CacheableArrayType<TObj, TYPEID> > {
private:
typedef CacheableArrayType<TObj, TYPEID> TArray;
public:
/** Default constructor. */
inline SharedArrayPtr() : SharedPtr<CacheableArrayType<TObj, TYPEID> >() {}
/** Constructor, given a pointer to array. */
inline SharedArrayPtr(const TArray* ptr)
: SharedPtr<CacheableArrayType<TObj, TYPEID> >(ptr) {}
/** Constructor, given a null SharedBase. */
inline SharedArrayPtr(const NullSharedBase* ptr)
: SharedPtr<CacheableArrayType<TObj, TYPEID> >(ptr) {}
/** Constructor, given another SharedArrayPtr. */
inline SharedArrayPtr(const SharedArrayPtr& other)
: SharedPtr<CacheableArrayType<TObj, TYPEID> >(other) {}
/** Constructor, given another kind of SharedArrayPtr. */
template <typename TOther, int8_t OTHERID>
inline SharedArrayPtr(const SharedArrayPtr<TOther, OTHERID>& other)
: SharedPtr<CacheableArrayType<TObj, TYPEID> >(other) {}
/** Constructor, given another SharedPtr. */
template <typename TOther>
inline SharedArrayPtr(const SharedPtr<TOther>& other)
: SharedPtr<CacheableArrayType<TObj, TYPEID> >(other) {}
/** Get the element at given index. */
inline TObj operator[](uint32_t index) const {
return SharedPtr<CacheableArrayType<TObj, TYPEID> >::ptr()->operator[](
index);
}
/** Deserialize self */
inline Serializable* fromData(DataInput& input) {
return SharedPtr<CacheableArrayType<TObj, TYPEID> >::ptr()->fromData(input);
}
};
/** Template class for container Cacheable types. */
template <typename TBase, int8_t TYPEID>
class CacheableContainerType : public Cacheable, public TBase {
protected:
inline CacheableContainerType() : TBase() {}
inline CacheableContainerType(const int32_t n) : TBase(n) {}
public:
// Cacheable methods
/** Serialize this object to the given <code>DataOutput</code>. */
virtual void toData(DataOutput& output) const {
apache::geode::client::serializer::writeObject(output, *this);
}
/** Deserialize this object from the given <code>DataInput</code>. */
virtual Serializable* fromData(DataInput& input) {
apache::geode::client::serializer::readObject(input, *this);
return this;
}
/**
* Return the classId of the instance being serialized.
*
* This is used by deserialization to determine what instance
* type to create and deserialize into.
*/
virtual int32_t classId() const { return 0; }
/**
* Return the typeId byte of the instance being serialized.
*
* This is used by deserialization to determine what instance
* type to create and deserialize into.
*/
virtual int8_t typeId() const { return TYPEID; }
/**
* Return the size in bytes of the instance being serialized.
*
* This is used to determine whether the cache is using up more
* physical memory than it has been configured to use. The method can
* return zero if the user does not require the ability to control
* cache memory utilization.
*/
virtual uint32_t objectSize() const {
return static_cast<uint32_t>(
sizeof(CacheableContainerType) +
apache::geode::client::serializer::objectSize(*this));
}
};
#ifdef _SOLARIS
#define TEMPLATE_EXPORT template class
#else
#ifdef BUILD_CPPCACHE
#define TEMPLATE_EXPORT template class CPPCACHE_EXPORT
#else
#define TEMPLATE_EXPORT extern template class CPPCACHE_EXPORT
#endif
#endif
// Disable extern template warning on MSVC compiler
#ifdef _MSC_VER
#pragma warning(disable : 4231)
#endif
#define _GF_CACHEABLE_KEY_TYPE_DEF_(p, k, sz) \
extern const char tName_##k[]; \
extern const char tStr_##k[]; \
TEMPLATE_EXPORT \
CacheableKeyType<p, GeodeTypeIds::k, tName_##k, tStr_##k, sz>; \
typedef CacheableKeyType<p, GeodeTypeIds::k, tName_##k, tStr_##k, sz> _##k; \
class CPPCACHE_EXPORT k; \
typedef SharedPtr<k> k##Ptr;
// use a class instead of typedef for bug #283
#define _GF_CACHEABLE_KEY_TYPE_(p, k, sz) \
class CPPCACHE_EXPORT k : public _##k { \
protected: \
inline k() : _##k() {} \
inline k(const p value) : _##k(value) {} \
\
public: \
/** Factory function registered with serialization registry. */ \
static Serializable* createDeserializable() { return new k(); } \
/** Factory function to create a new default instance. */ \
inline static k##Ptr create() { return k##Ptr(new k()); } \
/** Factory function to create an instance with the given value. */ \
inline static k##Ptr create(const p value) { \
return k##Ptr(new k(value)); \
} \
}; \
inline CacheableKeyPtr createKey(const p value) { return k::create(value); } \
inline CacheablePtr createValue(const p value) { return k::create(value); }
#define _GF_CACHEABLE_ARRAY_TYPE_DEF_(p, c) \
TEMPLATE_EXPORT CacheableArrayType<p, GeodeTypeIds::c>; \
typedef CacheableArrayType<p, GeodeTypeIds::c> _##c; \
class CPPCACHE_EXPORT c; \
typedef SharedArrayPtr<p, GeodeTypeIds::c> c##Ptr;
// use a class instead of typedef for bug #283
#define _GF_CACHEABLE_ARRAY_TYPE_(p, c) \
class CPPCACHE_EXPORT c : public _##c { \
protected: \
inline c() : _##c() {} \
inline c(int32_t length) : _##c(length) {} \
inline c(p* value, int32_t length) : _##c(value, length) {} \
inline c(const p* value, int32_t length, bool copy) \
: _##c(value, length, true) {} \
\
private: \
/* Private to disable copy constructor and assignment operator. */ \
c(const c& other); \
c& operator=(const c& other); \
\
public: \
/** Factory function registered with serialization registry. */ \
static Serializable* createDeserializable() { return new c(); } \
/** Factory function to create a new default instance. */ \
inline static c##Ptr create() { return c##Ptr(new c()); } \
/** Factory function to create a cacheable array of given size. */ \
inline static c##Ptr create(int32_t length) { \
return c##Ptr(new c(length)); \
} \
/** Create a cacheable array copying from the given array. */ \
inline static c##Ptr create(const p* value, int32_t length) { \
return (value != NULL ? c##Ptr(new c(value, length, true)) : NULLPTR); \
} \
/** \ \
* \ \
* \ \ \
* Create a cacheable array taking ownership of the given array \ \
* \ \
* \ \ \
* without creating a copy. \ \
* \ \
* \ \ \
* \ \
* \ \
* \ \ \
* Note that the application has to ensure that the given array is \ \
* \ \
* \ \ \
* not deleted (apart from this class) and is allocated on the heap \ \
* \ \
* \ \ \
* using the "new" operator. \ \
* \ \
* \ \ \
*/ \
inline static c##Ptr createNoCopy(p* value, int32_t length) { \
return (value != NULL ? c##Ptr(new c(value, length)) : NULLPTR); \
} \
};
#define _GF_CACHEABLE_CONTAINER_TYPE_DEF_(p, c) \
TEMPLATE_EXPORT CacheableContainerType<p, GeodeTypeIds::c>; \
typedef CacheableContainerType<p, GeodeTypeIds::c> _##c; \
class CPPCACHE_EXPORT c; \
typedef SharedPtr<c> c##Ptr;
// use a class instead of typedef for bug #283
#define _GF_CACHEABLE_CONTAINER_TYPE_(p, c) \
class CPPCACHE_EXPORT c : public _##c { \
protected: \
inline c() : _##c() {} \
inline c(const int32_t n) : _##c(n) {} \
\
public: \
/** Iterator for this type. */ \
typedef p::Iterator Iterator; \
/** Factory function registered with serialization registry. */ \
static Serializable* createDeserializable() { return new c(); } \
/** Factory function to create a default instance. */ \
inline static c##Ptr create() { return c##Ptr(new c()); } \
/** Factory function to create an instance with the given size. */ \
inline static c##Ptr create(const int32_t n) { return c##Ptr(new c(n)); } \
};
// Instantiations for the built-in CacheableKeys
_GF_CACHEABLE_KEY_TYPE_DEF_(bool, CacheableBoolean, 3);
/**
* An immutable wrapper for booleans that can serve as
* a distributable key object for caching.
*/
_GF_CACHEABLE_KEY_TYPE_(bool, CacheableBoolean, 3);
_GF_CACHEABLE_ARRAY_TYPE_DEF_(bool, BooleanArray);
/**
* An immutable wrapper for array of booleans that can serve as
* a distributable object for caching.
*/
_GF_CACHEABLE_ARRAY_TYPE_(bool, BooleanArray);
_GF_CACHEABLE_KEY_TYPE_DEF_(uint8_t, CacheableByte, 15);
/**
* An immutable wrapper for bytes that can serve as
* a distributable key object for caching.
*/
_GF_CACHEABLE_KEY_TYPE_(uint8_t, CacheableByte, 15);
_GF_CACHEABLE_KEY_TYPE_DEF_(double, CacheableDouble, 63);
/**
* An immutable wrapper for doubles that can serve as
* a distributable key object for caching.
*/
_GF_CACHEABLE_KEY_TYPE_(double, CacheableDouble, 63);
_GF_CACHEABLE_KEY_TYPE_DEF_(float, CacheableFloat, 63);
/**
* An immutable wrapper for floats that can serve as
* a distributable key object for caching.
*/
_GF_CACHEABLE_KEY_TYPE_(float, CacheableFloat, 63);
_GF_CACHEABLE_KEY_TYPE_DEF_(int16_t, CacheableInt16, 15);
/**
* An immutable wrapper for 16-bit integers that can serve as
* a distributable key object for caching.
*/
_GF_CACHEABLE_KEY_TYPE_(int16_t, CacheableInt16, 15);
_GF_CACHEABLE_KEY_TYPE_DEF_(int32_t, CacheableInt32, 15);
/**
* An immutable wrapper for 32-bit integers that can serve as
* a distributable key object for caching.
*/
_GF_CACHEABLE_KEY_TYPE_(int32_t, CacheableInt32, 15);
_GF_CACHEABLE_KEY_TYPE_DEF_(int64_t, CacheableInt64, 31);
/**
* An immutable wrapper for 64-bit integers that can serve as
* a distributable key object for caching.
*/
_GF_CACHEABLE_KEY_TYPE_(int64_t, CacheableInt64, 31);
_GF_CACHEABLE_KEY_TYPE_DEF_(wchar_t, CacheableWideChar, 3);
/**
* An immutable wrapper for wide-characters that can serve as
* a distributable key object for caching.
*/
_GF_CACHEABLE_KEY_TYPE_(wchar_t, CacheableWideChar, 3);
_GF_CACHEABLE_ARRAY_TYPE_DEF_(wchar_t, CharArray);
/**
* An immutable wrapper for array of wide-characters that can serve as
* a distributable object for caching.
*/
_GF_CACHEABLE_ARRAY_TYPE_(wchar_t, CharArray);
// Instantiations for array built-in Cacheables
_GF_CACHEABLE_ARRAY_TYPE_DEF_(uint8_t, CacheableBytes);
/**
* An immutable wrapper for byte arrays that can serve as
* a distributable object for caching.
*/
_GF_CACHEABLE_ARRAY_TYPE_(uint8_t, CacheableBytes);
_GF_CACHEABLE_ARRAY_TYPE_DEF_(double, CacheableDoubleArray);
/**
* An immutable wrapper for array of doubles that can serve as
* a distributable object for caching.
*/
_GF_CACHEABLE_ARRAY_TYPE_(double, CacheableDoubleArray);
_GF_CACHEABLE_ARRAY_TYPE_DEF_(float, CacheableFloatArray);
/**
* An immutable wrapper for array of floats that can serve as
* a distributable object for caching.
*/
_GF_CACHEABLE_ARRAY_TYPE_(float, CacheableFloatArray);
_GF_CACHEABLE_ARRAY_TYPE_DEF_(int16_t, CacheableInt16Array);
/**
* An immutable wrapper for array of 16-bit integers that can serve as
* a distributable object for caching.
*/
_GF_CACHEABLE_ARRAY_TYPE_(int16_t, CacheableInt16Array);
_GF_CACHEABLE_ARRAY_TYPE_DEF_(int32_t, CacheableInt32Array);
/**
* An immutable wrapper for array of 32-bit integers that can serve as
* a distributable object for caching.
*/
_GF_CACHEABLE_ARRAY_TYPE_(int32_t, CacheableInt32Array);
_GF_CACHEABLE_ARRAY_TYPE_DEF_(int64_t, CacheableInt64Array);
/**
* An immutable wrapper for array of 64-bit integers that can serve as
* a distributable object for caching.
*/
_GF_CACHEABLE_ARRAY_TYPE_(int64_t, CacheableInt64Array);
_GF_CACHEABLE_ARRAY_TYPE_DEF_(CacheableStringPtr, CacheableStringArray);
/**
* An immutable wrapper for array of strings that can serve as
* a distributable object for caching.
*/
_GF_CACHEABLE_ARRAY_TYPE_(CacheableStringPtr, CacheableStringArray);
// Instantiations for container types (Vector/HashMap/HashSet) Cacheables
_GF_CACHEABLE_CONTAINER_TYPE_DEF_(_VectorOfCacheable, CacheableVector);
/**
* A mutable <code>Cacheable</code> vector wrapper that can serve as
* a distributable object for caching.
*/
_GF_CACHEABLE_CONTAINER_TYPE_(_VectorOfCacheable, CacheableVector);
_GF_CACHEABLE_CONTAINER_TYPE_DEF_(_HashMapOfCacheable, CacheableHashMap);
/**
* A mutable <code>CacheableKey</code> to <code>Serializable</code>
* hash map that can serve as a distributable object for caching.
*/
_GF_CACHEABLE_CONTAINER_TYPE_(_HashMapOfCacheable, CacheableHashMap);
_GF_CACHEABLE_CONTAINER_TYPE_DEF_(_HashSetOfCacheableKey, CacheableHashSet);
/**
* A mutable <code>CacheableKey</code> hash set wrapper that can serve as
* a distributable object for caching.
*/
_GF_CACHEABLE_CONTAINER_TYPE_(_HashSetOfCacheableKey, CacheableHashSet);
_GF_CACHEABLE_CONTAINER_TYPE_DEF_(_VectorOfCacheable, CacheableArrayList);
/**
* A mutable <code>Cacheable</code> array list wrapper that can serve as
* a distributable object for caching.
*/
_GF_CACHEABLE_CONTAINER_TYPE_(_VectorOfCacheable, CacheableArrayList);
// linketlist for JSON formattor issue
_GF_CACHEABLE_CONTAINER_TYPE_DEF_(_VectorOfCacheable, CacheableLinkedList);
/**
* A mutable <code>Cacheable</code> array list wrapper that can serve as
* a distributable object for caching.
*/
_GF_CACHEABLE_CONTAINER_TYPE_(_VectorOfCacheable, CacheableLinkedList);
_GF_CACHEABLE_CONTAINER_TYPE_DEF_(_VectorOfCacheable, CacheableStack);
/**
* A mutable <code>Cacheable</code> stack wrapper that can serve as
* a distributable object for caching.
*/
_GF_CACHEABLE_CONTAINER_TYPE_(_VectorOfCacheable, CacheableStack);
_GF_CACHEABLE_CONTAINER_TYPE_DEF_(_HashMapOfCacheable, CacheableHashTable);
/**
* A mutable <code>CacheableKey</code> to <code>Serializable</code>
* hash map that can serve as a distributable object for caching.
*/
_GF_CACHEABLE_CONTAINER_TYPE_(_HashMapOfCacheable, CacheableHashTable);
_GF_CACHEABLE_CONTAINER_TYPE_DEF_(_HashMapOfCacheable,
CacheableIdentityHashMap);
/**
* A mutable <code>CacheableKey</code> to <code>Serializable</code>
* hash map that can serve as a distributable object for caching. This is
* provided for compability with java side, though is functionally identical
* to <code>CacheableHashMap</code> i.e. does not provide the semantics of
* java <code>IdentityHashMap</code>.
*/
_GF_CACHEABLE_CONTAINER_TYPE_(_HashMapOfCacheable, CacheableIdentityHashMap);
_GF_CACHEABLE_CONTAINER_TYPE_DEF_(_HashSetOfCacheableKey,
CacheableLinkedHashSet);
/**
* A mutable <code>CacheableKey</code> hash set wrapper that can serve as
* a distributable object for caching. This is provided for compability
* with java side, though is functionally identical to
* <code>CacheableHashSet</code> i.e. does not provide the predictable
* iteration semantics of java <code>LinkedHashSet</code>.
*/
_GF_CACHEABLE_CONTAINER_TYPE_(_HashSetOfCacheableKey, CacheableLinkedHashSet);
} // namespace client
} // namespace geode
} // namespace apache
#endif // GEODE_CACHEABLEBUILTINS_H_
| 27,534 | 8,062 |
/*
* This source file is part of ArkGameFrame
* For the latest info, see https://github.com/ArkGame
*
* Copyright (c) 2013-2018 ArkGame authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#pragma once
#include "SDK/Core/AFPlatform.hpp"
#include "SDK/Core/AFNoncopyable.hpp"
namespace ark
{
#if ARK_PLATFORM == PLATFORM_WIN
class AFCReaderWriterLock : public AFNoncopyable
{
public:
explicit AFCReaderWriterLock()
{
m_Readers = 0;
InitializeCriticalSection(&m_Writer);
InitializeCriticalSection(&m_ReaderCount);
m_ClearReadersEvent = CreateEvent(NULL, TRUE, TRUE, NULL);
}
~AFCReaderWriterLock()
{
WaitForSingleObject(m_ClearReadersEvent, INFINITE);
CloseHandle(m_ClearReadersEvent);
DeleteCriticalSection(&m_Writer);
DeleteCriticalSection(&m_ReaderCount);
}
/*Read, reset events */
void ReaderLock(void)
{
EnterCriticalSection(&m_Writer);
EnterCriticalSection(&m_ReaderCount);
if (++m_Readers == 1)
{
::ResetEvent(m_ClearReadersEvent);
}
LeaveCriticalSection(&m_ReaderCount);
LeaveCriticalSection(&m_Writer);
}
void ReaderUnlock(void)
{
EnterCriticalSection(&m_ReaderCount);
if (--m_Readers == 0)
{
::SetEvent(m_ClearReadersEvent);
}
LeaveCriticalSection(&m_ReaderCount);
}
void WriterLock(void)
{
EnterCriticalSection(&m_Writer);
WaitForSingleObject(m_ClearReadersEvent, INFINITE);
}
void WriterUnLock(void)
{
LeaveCriticalSection(&m_Writer);
}
private:
CRITICAL_SECTION m_Writer;
CRITICAL_SECTION m_ReaderCount;
int m_Readers;
HANDLE m_ClearReadersEvent;
};
#else
class AFCReaderWriterLock : public AFNoncopyable
{
public:
AFCReaderWriterLock()
{
::pthread_rwlock_init(&rwlock, NULL);
}
~AFCReaderWriterLock()
{
::pthread_rwlock_destroy(&rwlock);
}
void ReaderLock()
{
::pthread_rwlock_rdlock(&rwlock);
}
void ReaderUnlock(void)
{
::pthread_rwlock_unlock(&rwlock);
}
void WriterLock(void)
{
::pthread_rwlock_wrlock(&rwlock);
}
void WriterUnLock(void)
{
::pthread_rwlock_unlock(&rwlock);
}
private:
pthread_rwlock_t rwlock;
};
#endif
class AFScopeRdLock : public AFNoncopyable
{
public:
explicit AFScopeRdLock(AFCReaderWriterLock& lock) : rwlock(lock)
{
rwlock.ReaderLock();
}
~AFScopeRdLock()
{
rwlock.ReaderUnlock();
}
private:
AFCReaderWriterLock& rwlock;
};
class AFScopeWrLock : public AFNoncopyable
{
public:
explicit AFScopeWrLock(AFCReaderWriterLock& lock) : rwlock(lock)
{
rwlock.WriterLock();
}
~AFScopeWrLock()
{
rwlock.WriterUnLock();
}
private:
AFCReaderWriterLock& rwlock;
};
} | 3,887 | 1,210 |
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define LOG_TAG "Checkpoint"
#include "Checkpoint.h"
#include "VoldUtil.h"
#include "VolumeManager.h"
#include <fstream>
#include <list>
#include <memory>
#include <string>
#include <thread>
#include <vector>
#include <android-base/file.h>
#include <android-base/logging.h>
#include <android-base/parseint.h>
#include <android-base/properties.h>
#include <android-base/unique_fd.h>
#include <android/hardware/boot/1.0/IBootControl.h>
#include <cutils/android_reboot.h>
#include <fcntl.h>
#include <fs_mgr.h>
#include <linux/fs.h>
#include <mntent.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <unistd.h>
using android::base::GetBoolProperty;
using android::base::GetUintProperty;
using android::base::SetProperty;
using android::binder::Status;
using android::fs_mgr::Fstab;
using android::fs_mgr::ReadDefaultFstab;
using android::fs_mgr::ReadFstabFromFile;
using android::hardware::hidl_string;
using android::hardware::boot::V1_0::BoolResult;
using android::hardware::boot::V1_0::CommandResult;
using android::hardware::boot::V1_0::IBootControl;
using android::hardware::boot::V1_0::Slot;
namespace android {
namespace vold {
namespace {
const std::string kMetadataCPFile = "/metadata/vold/checkpoint";
binder::Status error(const std::string& msg) {
PLOG(ERROR) << msg;
return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str()));
}
binder::Status error(int error, const std::string& msg) {
LOG(ERROR) << msg;
return binder::Status::fromServiceSpecificError(error, String8(msg.c_str()));
}
bool setBowState(std::string const& block_device, std::string const& state) {
std::string bow_device = fs_mgr_find_bow_device(block_device);
if (bow_device.empty()) return false;
if (!android::base::WriteStringToFile(state, bow_device + "/bow/state")) {
PLOG(ERROR) << "Failed to write to file " << bow_device + "/bow/state";
return false;
}
return true;
}
} // namespace
Status cp_supportsCheckpoint(bool& result) {
result = false;
for (const auto& entry : fstab_default) {
if (entry.fs_mgr_flags.checkpoint_blk || entry.fs_mgr_flags.checkpoint_fs) {
result = true;
return Status::ok();
}
}
return Status::ok();
}
Status cp_supportsBlockCheckpoint(bool& result) {
result = false;
for (const auto& entry : fstab_default) {
if (entry.fs_mgr_flags.checkpoint_blk) {
result = true;
return Status::ok();
}
}
return Status::ok();
}
Status cp_supportsFileCheckpoint(bool& result) {
result = false;
for (const auto& entry : fstab_default) {
if (entry.fs_mgr_flags.checkpoint_fs) {
result = true;
return Status::ok();
}
}
return Status::ok();
}
Status cp_startCheckpoint(int retry) {
bool result;
if (!cp_supportsCheckpoint(result).isOk() || !result)
return error(ENOTSUP, "Checkpoints not supported");
if (retry < -1) return error(EINVAL, "Retry count must be more than -1");
std::string content = std::to_string(retry + 1);
if (retry == -1) {
sp<IBootControl> module = IBootControl::getService();
if (module) {
std::string suffix;
auto cb = [&suffix](hidl_string s) { suffix = s; };
if (module->getSuffix(module->getCurrentSlot(), cb).isOk()) content += " " + suffix;
}
}
if (!android::base::WriteStringToFile(content, kMetadataCPFile))
return error("Failed to write checkpoint file");
return Status::ok();
}
namespace {
volatile bool isCheckpointing = false;
volatile bool needsCheckpointWasCalled = false;
// Protects isCheckpointing, needsCheckpointWasCalled and code that makes decisions based on status
// of isCheckpointing
std::mutex isCheckpointingLock;
}
Status cp_commitChanges() {
std::lock_guard<std::mutex> lock(isCheckpointingLock);
if (!isCheckpointing) {
return Status::ok();
}
if (android::base::GetProperty("persist.vold.dont_commit_checkpoint", "0") == "1") {
LOG(WARNING)
<< "NOT COMMITTING CHECKPOINT BECAUSE persist.vold.dont_commit_checkpoint IS 1";
return Status::ok();
}
sp<IBootControl> module = IBootControl::getService();
if (module) {
CommandResult cr;
module->markBootSuccessful([&cr](CommandResult result) { cr = result; });
if (!cr.success)
return error(EINVAL, "Error marking booted successfully: " + std::string(cr.errMsg));
LOG(INFO) << "Marked slot as booted successfully.";
// Clears the warm reset flag for next reboot.
if (!SetProperty("ota.warm_reset", "0")) {
LOG(WARNING) << "Failed to reset the warm reset flag";
}
}
// Must take action for list of mounted checkpointed things here
// To do this, we walk the list of mounted file systems.
// But we also need to get the matching fstab entries to see
// the original flags
std::string err_str;
Fstab mounts;
if (!ReadFstabFromFile("/proc/mounts", &mounts)) {
return error(EINVAL, "Failed to get /proc/mounts");
}
// Walk mounted file systems
for (const auto& mount_rec : mounts) {
const auto fstab_rec = GetEntryForMountPoint(&fstab_default, mount_rec.mount_point);
if (!fstab_rec) continue;
if (fstab_rec->fs_mgr_flags.checkpoint_fs) {
if (fstab_rec->fs_type == "f2fs") {
std::string options = mount_rec.fs_options + ",checkpoint=enable";
if (mount(mount_rec.blk_device.c_str(), mount_rec.mount_point.c_str(), "none",
MS_REMOUNT | fstab_rec->flags, options.c_str())) {
return error(EINVAL, "Failed to remount");
}
}
} else if (fstab_rec->fs_mgr_flags.checkpoint_blk) {
if (!setBowState(mount_rec.blk_device, "2"))
return error(EINVAL, "Failed to set bow state");
}
}
SetProperty("vold.checkpoint_committed", "1");
LOG(INFO) << "Checkpoint has been committed.";
isCheckpointing = false;
if (!android::base::RemoveFileIfExists(kMetadataCPFile, &err_str))
return error(err_str.c_str());
return Status::ok();
}
namespace {
void abort_metadata_file() {
std::string oldContent, newContent;
int retry = 0;
struct stat st;
int result = stat(kMetadataCPFile.c_str(), &st);
// If the file doesn't exist, we aren't managing a checkpoint retry counter
if (result != 0) return;
if (!android::base::ReadFileToString(kMetadataCPFile, &oldContent)) {
PLOG(ERROR) << "Failed to read checkpoint file";
return;
}
std::string retryContent = oldContent.substr(0, oldContent.find_first_of(" "));
if (!android::base::ParseInt(retryContent, &retry)) {
PLOG(ERROR) << "Could not parse retry count";
return;
}
if (retry > 0) {
newContent = "0";
if (!android::base::WriteStringToFile(newContent, kMetadataCPFile))
PLOG(ERROR) << "Could not write checkpoint file";
}
}
} // namespace
void cp_abortChanges(const std::string& message, bool retry) {
if (!cp_needsCheckpoint()) return;
if (!retry) abort_metadata_file();
android_reboot(ANDROID_RB_RESTART2, 0, message.c_str());
}
bool cp_needsRollback() {
std::string content;
bool ret;
ret = android::base::ReadFileToString(kMetadataCPFile, &content);
if (ret) {
if (content == "0") return true;
if (content.substr(0, 3) == "-1 ") {
std::string oldSuffix = content.substr(3);
sp<IBootControl> module = IBootControl::getService();
std::string newSuffix;
if (module) {
auto cb = [&newSuffix](hidl_string s) { newSuffix = s; };
module->getSuffix(module->getCurrentSlot(), cb);
if (oldSuffix == newSuffix) return true;
}
}
}
return false;
}
bool cp_needsCheckpoint() {
std::lock_guard<std::mutex> lock(isCheckpointingLock);
// Make sure we only return true during boot. See b/138952436 for discussion
if (needsCheckpointWasCalled) return isCheckpointing;
needsCheckpointWasCalled = true;
bool ret;
std::string content;
sp<IBootControl> module = IBootControl::getService();
if (isCheckpointing) return isCheckpointing;
if (module && module->isSlotMarkedSuccessful(module->getCurrentSlot()) == BoolResult::FALSE) {
isCheckpointing = true;
return true;
}
ret = android::base::ReadFileToString(kMetadataCPFile, &content);
if (ret) {
ret = content != "0";
isCheckpointing = ret;
return ret;
}
return false;
}
bool cp_isCheckpointing() {
return isCheckpointing;
}
namespace {
const std::string kSleepTimeProp = "ro.sys.cp_msleeptime";
const uint32_t msleeptime_default = 1000; // 1 s
const uint32_t max_msleeptime = 3600000; // 1 h
const std::string kMinFreeBytesProp = "ro.sys.cp_min_free_bytes";
const uint64_t min_free_bytes_default = 100 * (1 << 20); // 100 MiB
const std::string kCommitOnFullProp = "ro.sys.cp_commit_on_full";
const bool commit_on_full_default = true;
static void cp_healthDaemon(std::string mnt_pnt, std::string blk_device, bool is_fs_cp) {
struct statvfs data;
uint32_t msleeptime = GetUintProperty(kSleepTimeProp, msleeptime_default, max_msleeptime);
uint64_t min_free_bytes =
GetUintProperty(kMinFreeBytesProp, min_free_bytes_default, (uint64_t)-1);
bool commit_on_full = GetBoolProperty(kCommitOnFullProp, commit_on_full_default);
struct timespec req;
req.tv_sec = msleeptime / 1000;
msleeptime %= 1000;
req.tv_nsec = msleeptime * 1000000;
while (isCheckpointing) {
uint64_t free_bytes = 0;
if (is_fs_cp) {
statvfs(mnt_pnt.c_str(), &data);
free_bytes = ((uint64_t) data.f_bavail) * data.f_frsize;
} else {
std::string bow_device = fs_mgr_find_bow_device(blk_device);
if (!bow_device.empty()) {
std::string content;
if (android::base::ReadFileToString(bow_device + "/bow/free", &content)) {
free_bytes = std::strtoull(content.c_str(), NULL, 10);
}
}
}
if (free_bytes < min_free_bytes) {
if (commit_on_full) {
LOG(INFO) << "Low space for checkpointing. Commiting changes";
cp_commitChanges();
break;
} else {
LOG(INFO) << "Low space for checkpointing. Rebooting";
cp_abortChanges("checkpoint,low_space", false);
break;
}
}
nanosleep(&req, NULL);
}
}
} // namespace
Status cp_prepareCheckpoint() {
// Log to notify CTS - see b/137924328 for context
LOG(INFO) << "cp_prepareCheckpoint called";
std::lock_guard<std::mutex> lock(isCheckpointingLock);
if (!isCheckpointing) {
return Status::ok();
}
Fstab mounts;
if (!ReadFstabFromFile("/proc/mounts", &mounts)) {
return error(EINVAL, "Failed to get /proc/mounts");
}
for (const auto& mount_rec : mounts) {
const auto fstab_rec = GetEntryForMountPoint(&fstab_default, mount_rec.mount_point);
if (!fstab_rec) continue;
if (fstab_rec->fs_mgr_flags.checkpoint_blk) {
android::base::unique_fd fd(
TEMP_FAILURE_RETRY(open(mount_rec.mount_point.c_str(), O_RDONLY | O_CLOEXEC)));
if (fd == -1) {
PLOG(ERROR) << "Failed to open mount point" << mount_rec.mount_point;
continue;
}
struct fstrim_range range = {};
range.len = ULLONG_MAX;
nsecs_t start = systemTime(SYSTEM_TIME_BOOTTIME);
if (ioctl(fd, FITRIM, &range)) {
PLOG(ERROR) << "Failed to trim " << mount_rec.mount_point;
continue;
}
nsecs_t time = systemTime(SYSTEM_TIME_BOOTTIME) - start;
LOG(INFO) << "Trimmed " << range.len << " bytes on " << mount_rec.mount_point << " in "
<< nanoseconds_to_milliseconds(time) << "ms for checkpoint";
setBowState(mount_rec.blk_device, "1");
}
if (fstab_rec->fs_mgr_flags.checkpoint_blk || fstab_rec->fs_mgr_flags.checkpoint_fs) {
std::thread(cp_healthDaemon, std::string(mount_rec.mount_point),
std::string(mount_rec.blk_device),
fstab_rec->fs_mgr_flags.checkpoint_fs == 1)
.detach();
}
}
return Status::ok();
}
namespace {
const int kSectorSize = 512;
typedef uint64_t sector_t;
struct log_entry {
sector_t source; // in sectors of size kSectorSize
sector_t dest; // in sectors of size kSectorSize
uint32_t size; // in bytes
uint32_t checksum;
} __attribute__((packed));
struct log_sector_v1_0 {
uint32_t magic;
uint16_t header_version;
uint16_t header_size;
uint32_t block_size;
uint32_t count;
uint32_t sequence;
uint64_t sector0;
} __attribute__((packed));
// MAGIC is BOW in ascii
const int kMagic = 0x00574f42;
// Partially restored MAGIC is WOB in ascii
const int kPartialRestoreMagic = 0x00424f57;
void crc32(const void* data, size_t n_bytes, uint32_t* crc) {
static uint32_t table[0x100] = {
0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535,
0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD,
0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D,
0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4,
0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C,
0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC,
0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB,
0xB6662D3D,
0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5,
0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D,
0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED,
0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C,
0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074,
0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC,
0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C,
0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B,
0xC0BA6CAD,
0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615,
0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D,
0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D,
0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4,
0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C,
0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C,
0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B,
0x5BDEAE1D,
0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785,
0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D,
0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD,
0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354,
0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC,
0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C,
0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B,
0x2D02EF8D};
for (size_t i = 0; i < n_bytes; ++i) {
*crc ^= ((uint8_t*)data)[i];
*crc = table[(uint8_t)*crc] ^ *crc >> 8;
}
}
// A map of relocations.
// The map must be initialized so that relocations[0] = 0
// During restore, we replay the log records in reverse, copying from dest to
// source
// To validate, we must be able to read the 'dest' sectors as though they had
// been copied but without actually copying. This map represents how the sectors
// would have been moved. To read a sector s, find the index <= s and read
// relocations[index] + s - index
typedef std::map<sector_t, sector_t> Relocations;
void relocate(Relocations& relocations, sector_t dest, sector_t source, int count) {
// Find first one we're equal to or greater than
auto s = --relocations.upper_bound(source);
// Take slice
Relocations slice;
slice[dest] = source - s->first + s->second;
++s;
// Add rest of elements
for (; s != relocations.end() && s->first < source + count; ++s)
slice[dest - source + s->first] = s->second;
// Split range at end of dest
auto dest_end = --relocations.upper_bound(dest + count);
relocations[dest + count] = dest + count - dest_end->first + dest_end->second;
// Remove all elements in [dest, dest + count)
relocations.erase(relocations.lower_bound(dest), relocations.lower_bound(dest + count));
// Add new elements
relocations.insert(slice.begin(), slice.end());
}
// A map of sectors that have been written to.
// The final entry must always be False.
// When we restart the restore after an interruption, we must take care that
// when we copy from dest to source, that the block we copy to was not
// previously copied from.
// i e. A->B C->A; If we replay this sequence, we end up copying C->B
// We must save our partial result whenever we finish a page, or when we copy
// to a location that was copied from earlier (our source is an earlier dest)
typedef std::map<sector_t, bool> Used_Sectors;
bool checkCollision(Used_Sectors& used_sectors, sector_t start, sector_t end) {
auto second_overlap = used_sectors.upper_bound(start);
auto first_overlap = --second_overlap;
if (first_overlap->second) {
return true;
} else if (second_overlap != used_sectors.end() && second_overlap->first < end) {
return true;
}
return false;
}
void markUsed(Used_Sectors& used_sectors, sector_t start, sector_t end) {
auto start_pos = used_sectors.insert_or_assign(start, true).first;
auto end_pos = used_sectors.insert_or_assign(end, false).first;
if (start_pos == used_sectors.begin() || !std::prev(start_pos)->second) {
start_pos++;
}
if (std::next(end_pos) != used_sectors.end() && !std::next(end_pos)->second) {
end_pos++;
}
if (start_pos->first < end_pos->first) {
used_sectors.erase(start_pos, end_pos);
}
}
// Restores the given log_entry's data from dest -> source
// If that entry is a log sector, set the magic to kPartialRestoreMagic and flush.
void restoreSector(int device_fd, Used_Sectors& used_sectors, std::vector<char>& ls_buffer,
log_entry* le, std::vector<char>& buffer) {
log_sector_v1_0& ls = *reinterpret_cast<log_sector_v1_0*>(&ls_buffer[0]);
uint32_t index = le - ((log_entry*)&ls_buffer[ls.header_size]);
int count = (le->size - 1) / kSectorSize + 1;
if (checkCollision(used_sectors, le->source, le->source + count)) {
fsync(device_fd);
lseek64(device_fd, 0, SEEK_SET);
ls.count = index + 1;
ls.magic = kPartialRestoreMagic;
write(device_fd, &ls_buffer[0], ls.block_size);
fsync(device_fd);
used_sectors.clear();
used_sectors[0] = false;
}
markUsed(used_sectors, le->dest, le->dest + count);
if (index == 0 && ls.sequence != 0) {
log_sector_v1_0* next = reinterpret_cast<log_sector_v1_0*>(&buffer[0]);
if (next->magic == kMagic) {
next->magic = kPartialRestoreMagic;
}
}
lseek64(device_fd, le->source * kSectorSize, SEEK_SET);
write(device_fd, &buffer[0], le->size);
if (index == 0) {
fsync(device_fd);
}
}
// Read from the device
// If we are validating, the read occurs as though the relocations had happened
std::vector<char> relocatedRead(int device_fd, Relocations const& relocations, bool validating,
sector_t sector, uint32_t size, uint32_t block_size) {
if (!validating) {
std::vector<char> buffer(size);
lseek64(device_fd, sector * kSectorSize, SEEK_SET);
read(device_fd, &buffer[0], size);
return buffer;
}
std::vector<char> buffer(size);
for (uint32_t i = 0; i < size; i += block_size, sector += block_size / kSectorSize) {
auto relocation = --relocations.upper_bound(sector);
lseek64(device_fd, (sector + relocation->second - relocation->first) * kSectorSize,
SEEK_SET);
read(device_fd, &buffer[i], block_size);
}
return buffer;
}
} // namespace
Status cp_restoreCheckpoint(const std::string& blockDevice, int restore_limit) {
bool validating = true;
std::string action = "Validating";
int restore_count = 0;
for (;;) {
Relocations relocations;
relocations[0] = 0;
Status status = Status::ok();
LOG(INFO) << action << " checkpoint on " << blockDevice;
base::unique_fd device_fd(open(blockDevice.c_str(), O_RDWR | O_CLOEXEC));
if (device_fd < 0) return error("Cannot open " + blockDevice);
log_sector_v1_0 original_ls;
read(device_fd, reinterpret_cast<char*>(&original_ls), sizeof(original_ls));
if (original_ls.magic == kPartialRestoreMagic) {
validating = false;
action = "Restoring";
} else if (original_ls.magic != kMagic) {
return error(EINVAL, "No magic");
}
LOG(INFO) << action << " " << original_ls.sequence << " log sectors";
for (int sequence = original_ls.sequence; sequence >= 0 && status.isOk(); sequence--) {
auto ls_buffer = relocatedRead(device_fd, relocations, validating, 0,
original_ls.block_size, original_ls.block_size);
log_sector_v1_0& ls = *reinterpret_cast<log_sector_v1_0*>(&ls_buffer[0]);
Used_Sectors used_sectors;
used_sectors[0] = false;
if (ls.magic != kMagic && (ls.magic != kPartialRestoreMagic || validating)) {
status = error(EINVAL, "No magic");
break;
}
if (ls.block_size != original_ls.block_size) {
status = error(EINVAL, "Block size mismatch");
break;
}
if ((int)ls.sequence != sequence) {
status = error(EINVAL, "Expecting log sector " + std::to_string(sequence) +
" but got " + std::to_string(ls.sequence));
break;
}
LOG(INFO) << action << " from log sector " << ls.sequence;
for (log_entry* le =
reinterpret_cast<log_entry*>(&ls_buffer[ls.header_size]) + ls.count - 1;
le >= reinterpret_cast<log_entry*>(&ls_buffer[ls.header_size]); --le) {
// This is very noisy - limit to DEBUG only
LOG(VERBOSE) << action << " " << le->size << " bytes from sector " << le->dest
<< " to " << le->source << " with checksum " << std::hex
<< le->checksum;
auto buffer = relocatedRead(device_fd, relocations, validating, le->dest, le->size,
ls.block_size);
uint32_t checksum = le->source / (ls.block_size / kSectorSize);
for (size_t i = 0; i < le->size; i += ls.block_size) {
crc32(&buffer[i], ls.block_size, &checksum);
}
if (le->checksum && checksum != le->checksum) {
status = error(EINVAL, "Checksums don't match");
break;
}
if (validating) {
relocate(relocations, le->source, le->dest, (le->size - 1) / kSectorSize + 1);
} else {
restoreSector(device_fd, used_sectors, ls_buffer, le, buffer);
restore_count++;
if (restore_limit && restore_count >= restore_limit) {
status = error(EAGAIN, "Hit the test limit");
break;
}
}
}
}
if (!status.isOk()) {
if (!validating) {
LOG(ERROR) << "Checkpoint restore failed even though checkpoint validation passed";
return status;
}
LOG(WARNING) << "Checkpoint validation failed - attempting to roll forward";
auto buffer = relocatedRead(device_fd, relocations, false, original_ls.sector0,
original_ls.block_size, original_ls.block_size);
lseek64(device_fd, 0, SEEK_SET);
write(device_fd, &buffer[0], original_ls.block_size);
return Status::ok();
}
if (!validating) break;
validating = false;
action = "Restoring";
}
return Status::ok();
}
Status cp_markBootAttempt() {
std::string oldContent, newContent;
int retry = 0;
struct stat st;
int result = stat(kMetadataCPFile.c_str(), &st);
// If the file doesn't exist, we aren't managing a checkpoint retry counter
if (result != 0) return Status::ok();
if (!android::base::ReadFileToString(kMetadataCPFile, &oldContent))
return error("Failed to read checkpoint file");
std::string retryContent = oldContent.substr(0, oldContent.find_first_of(" "));
if (!android::base::ParseInt(retryContent, &retry))
return error(EINVAL, "Could not parse retry count");
if (retry > 0) {
retry--;
newContent = std::to_string(retry);
if (!android::base::WriteStringToFile(newContent, kMetadataCPFile))
return error("Could not write checkpoint file");
}
return Status::ok();
}
void cp_resetCheckpoint() {
std::lock_guard<std::mutex> lock(isCheckpointingLock);
needsCheckpointWasCalled = false;
}
} // namespace vold
} // namespace android
| 28,079 | 10,976 |
// Copyright (C) 2022 Frank E. Curtis
//
// This code is published under the MIT License.
//
// Author(s) : Frank E. Curtis
#include "testPoint.hpp"
// Main function
int main()
{
return testPointImplementation(1);
}
| 220 | 79 |
#include "UI_Clock.h"
#include "j1App.h"
#include "j1Render.h"
#include "j1Gui.h"
#include "Brofiler\Brofiler.h"
void Clock::setStartValue(int new_start_value)
{
start_value = new_start_value;
}
void Clock::setAlarm(int alarm)
{
alarms.push_back(alarm);
}
void Clock::restartChrono()
{
switch (this->type)
{
case TIMER:
time = start_value;
break;
case STOPWATCH:
time = 0;
break;
}
}
void Clock::BlitElement()
{
BROFILER_CATEGORY("Clock Blit", Profiler::Color::PowderBlue);
time_elapsed = counter.ReadSec();
switch (type)
{
case STOPWATCH:
if (time != time_elapsed)
{
time = time_elapsed;
if (callback != nullptr) //If has callback send event
{
for (int i = 0; i < alarms.size(); i++)
{
if (time == (int)alarms[i])
callback->OnUIEvent(this, STOPWATCH_ALARM);
}
}
std::string secs = std::to_string(time);
//p2SString secs("%04d", time);
if (last_secs != secs)
text->setText(secs);
section = text->section;
last_secs = std::to_string(time);
}
break;
case TIMER:
if (start_value - time_elapsed != time && time != 0)
{
time = start_value - time_elapsed;
if (time == 0 && callback != nullptr) //If has callback send event
callback->OnUIEvent(this, TIMER_ZERO);
//p2SString secs("%d", time);
std::string secs = std::to_string(time);
if (last_secs != secs)
text->setText(secs);
section = text->section;
last_secs = std::to_string(time);
}
break;
}
text->BlitElement();
} | 1,500 | 698 |
#include <Box3D/Renderer/TextureBuffer.hpp>
namespace box3d {
TextureBuffer::TextureBuffer()
{
glGenTextures(1, &this->m_rendererID);
glBindTexture(GL_TEXTURE_2D, this->m_rendererID);
}
TextureBuffer::~TextureBuffer()
{
}
void TextureBuffer::createTexImage2D(box3d::Application& app)
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, app.GetWindow().GetWidth(), app.GetWindow().GetHeight(), 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
}
void TextureBuffer::setTextureAtributes()
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
void TextureBuffer::bind() const
{
glBindTexture(GL_TEXTURE_2D, this->m_rendererID);
}
void TextureBuffer::unbind() const
{
glBindTexture(GL_TEXTURE_2D, 0);
}
}
| 899 | 344 |
#ifndef BOOST_GRAPH_DETAIL_EMPTY_HEADER_HPP_INCLUDED
#define BOOST_GRAPH_DETAIL_EMPTY_HEADER_HPP_INCLUDED
// Copyright 2018 Peter Dimov
//
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0 (See accompanying file
// LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
#endif // #ifndef BOOST_GRAPH_DETAIL_EMPTY_HEADER_HPP_INCLUDED
| 393 | 180 |
// Copyright David Abrahams 2002. Permission to copy, use,
// modify, sell and distribute this software is granted provided this
// copyright notice appears in all copies. This software is provided
// "as is" without express or implied warranty, and with no claim as
// to its suitability for any purpose.
#ifndef INHERITANCE_DWA200216_HPP
# define INHERITANCE_DWA200216_HPP
# include <boost/python/type_id.hpp>
# include <boost/shared_ptr.hpp>
# include <boost/mpl/if.hpp>
# include <boost/type_traits/object_traits.hpp>
# include <boost/type_traits/is_polymorphic.hpp>
# include <boost/detail/workaround.hpp>
namespace boost { namespace python { namespace objects {
typedef type_info class_id;
using python::type_id;
// Types used to get address and id of most derived type
typedef std::pair<void*,class_id> dynamic_id_t;
typedef dynamic_id_t (*dynamic_id_function)(void*);
BOOST_PYTHON_DECL void register_dynamic_id_aux(
class_id static_id, dynamic_id_function get_dynamic_id);
BOOST_PYTHON_DECL void add_cast(
class_id src_t, class_id dst_t, void* (*cast)(void*), bool polymorphic);
BOOST_PYTHON_DECL void* find_static_type(void* p, class_id src, class_id dst);
BOOST_PYTHON_DECL void* find_dynamic_type(void* p, class_id src, class_id dst);
//
// a generator with an execute() function which, given a source type
// and a pointer to an object of that type, returns its most-derived
// /reachable/ type identifier and object pointer.
//
// first, the case where T has virtual functions
template <class T>
struct polymorphic_id_generator
{
static dynamic_id_t execute(void* p_)
{
T* p = static_cast<T*>(p_);
return std::make_pair(dynamic_cast<void*>(p), class_id(typeid(*p)));
}
};
// now, the non-polymorphic case.
template <class T>
struct non_polymorphic_id_generator
{
static dynamic_id_t execute(void* p_)
{
return std::make_pair(p_, python::type_id<T>());
}
};
// Now the generalized selector
template <class T>
struct dynamic_id_generator
{
typedef typename mpl::if_c<
is_polymorphic<T>::value
, polymorphic_id_generator<T>
, non_polymorphic_id_generator<T> >::type type;
};
// Register the dynamic id function for T with the type-conversion
// system.
template <class T>
void register_dynamic_id(T* = 0)
{
typedef typename dynamic_id_generator<T>::type generator;
register_dynamic_id_aux(
python::type_id<T>(), &generator::execute);
}
//
// a generator with an execute() function which, given a void*
// pointing to an object of type Source will attempt to convert it to
// an object of type Target.
//
template <class Source, class Target>
struct dynamic_cast_generator
{
static void* execute(void* source)
{
return dynamic_cast<Target*>(
static_cast<Source*>(source));
}
};
template <class Source, class Target>
struct implicit_cast_generator
{
static void* execute(void* source)
{
Target* result = static_cast<Source*>(source);
return result;
}
};
template <class Source, class Target>
struct cast_generator
{
// It's OK to return false, since we can always cast up with
// dynamic_cast<> if neccessary.
# if BOOST_WORKAROUND(__MWERKS__, <= 0x2407)
BOOST_STATIC_CONSTANT(bool, is_upcast = false);
# else
BOOST_STATIC_CONSTANT(
bool, is_upcast = (
is_base_and_derived<Target,Source>::value
));
# endif
typedef typename mpl::if_c<
is_upcast
# if BOOST_WORKAROUND(__MWERKS__, <= 0x2407)
// grab a few more implicit_cast cases for CodeWarrior
|| !is_polymorphic<Source>::value
|| !is_polymorphic<Target>::value
# endif
, implicit_cast_generator<Source,Target>
, dynamic_cast_generator<Source,Target>
>::type type;
};
template <class Source, class Target>
inline void register_conversion(
// We need this parameter because CWPro7 can't determine
// which is the base reliably.
bool is_downcast = !cast_generator<Source,Target>::is_upcast
// These parameters shouldn't be used, they're an MSVC bug workaround
, Source* = 0, Target* = 0)
{
typedef typename cast_generator<Source,Target>::type generator;
add_cast(python::type_id<Source>()
, python::type_id<Target>()
, &generator::execute
, is_downcast);
}
}}} // namespace boost::python::object
#endif // INHERITANCE_DWA200216_HPP
| 4,459 | 1,465 |
#include <fstream>
#include <sstream>
#include <filesystem>
#include <string>
#include <algorithm>
#include <vector>
#include "backTracking/TOP_Backtracking.hpp"
#include "greedy/GreedyPaths.hpp"
using namespace std;
namespace fs = std::filesystem;
/**
* Struct that represent Chao's results
*/
struct chaoResults {
string file;
double chaoOptimum;
};
/**
* MainBackTracking.cpp is a main that takes all the instances and solve them with the backtracking algorithm. Bacause
* of the long time that takes the backtracking, it is possible to set a maxTime limit that it takes to resolve
* each instance (default value 3 minutes). The main perform a metaheuristic backtracking because it use the greedy
* algorithm (with its parameter maxDeviation) plus some other solutions built to solve the TOP problem.
* the solution are compared with Chao's ones to evaluate the performance and the resoluts of the backtracking algorithm.
* All the outputs are saved in different files to sum up the information and the outputs from which it is obtained
* the best optimum.
*
* Input file:
* paramTimeBt.txt : file in which are contained tthe max time permitted to execute the backtracking algorithm
* on each instance, expressed in second.
* Mandatory info: time for each instance. If not provided, default at 3 minutes.
* The file is located in "parametes_in" directory.
*
* chaoResults.txt : file in which are contained Chao's results, used to compare greedy scores whith Chao's ones.
* The file is located in "parametes_in" directory.
*
* "instances" files : files that contain the instances to solve.
* The files are located in "instances" directory.
*
* Output files:
* SolBacktracking.csv : file in which it is saved for each instance the algorithm results and the comparison whith chao's one.
* The file is located in "solutions" directory.
*
* "outputs/backtracking/[#]" files : for all the instances, it is saved a file which contain the input and the output in standard
* form. Some useful information as the path, the hop and the score obtained are provided.
* The file are located in "outputs/backtracking/[#]" directory.
*
* "outputs/routeHops/backtarcking/[#]" files : for all the instances it is saved the solution obtained if hops form to read and use
* it in the resolution of other algortims (i.e. Local Search).
* The files are located in "outputs/routeHops/backtracking/[#]" directory.
*
* Usage:
* ./MainBackT.exe [version of algorithm]
* - version :
* 1 : if with default parameters
* 2 : if with parameters readed by Greedy output files
*
* @param argc number of items in the command line
* @param argv items in the command line
* @return resolve all the instances and print outputs and parameters in files
*/
int main(int argc, char* argv[]) {
double maxTime = 3.0 * 60.0; // Default Time limit: 3 minutes
int errors = 0, cnt_istances = 0;
bool timeDefault = false;
vector<chaoResults> chaoRes;
string line;
if (argc < 1) {
cerr << argc << " ERROR: insert Backtracking algorithm's version [#1 or #2]" << endl;
return 1;
}
//Open the file conteining the max time for execute the program for each instance
ifstream paramTime("./paramIn/paramTimeBt.txt");
if (!paramTime) {
cerr << " ERROR: Unable to open MaxTime file" << endl;
timeDefault = true;
}
if(!timeDefault) {
while(getline(paramTime, line)) {
std::istringstream iss(line); //Split the input string
std::vector<string> results(std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>());
if (results[0] == "timeMax") {
maxTime = stod(results[1]);
}
else {
continue;
}
}
paramTime.close();
}
cout << "LOG: timeMax limit set to " << maxTime << "s" << endl;
//Open and read the file of Chao's results
ifstream optStream("./paramIn/chaoResults.txt");
if (!optStream) {
throw runtime_error(" ERROR: Unable to open Chao's file");
}
// Read all the lines into chao's file
while(getline(optStream, line)) {
std::istringstream iss(line); //Split the input string
std::vector<string> results(std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>());
chaoRes.push_back({.file = results[0], .chaoOptimum = stod(results[1])}); //Populate the vector of chao's results
}
optStream.close();
//Open and write the file of results for each instance
fs::create_directories("solutions");
string titleFile = "solutions/SolBacktracking#";
titleFile.push_back(*argv[1]);
ofstream solutionsStream(titleFile + ".csv");
if(!solutionsStream) {
throw runtime_error(" ERROR: Unable to open Solution file");
}
if(*argv[1] == '2') {
solutionsStream << "# TimeMax limit set to " << maxTime << "s [Custom parameters] " << endl;
}
else {
solutionsStream << "# TimeMax limit set to " << maxTime << "s [Default parameters] " << endl;
}
for (const auto &file : fs::directory_iterator("./instances")) { //For each instance
TOP_Input in;
string line;
// Default weight parameters
double wProfit = 1.1;
double wTime = 0.7;
double maxDeviation = 1.5; // Max deviation admitted to the path
double wNonCost = 0.0;
if (file.path().extension() != ".txt")
continue;
cerr << "Processing: " << file.path().filename() << endl;
{
ifstream is(file.path());
if (!is) {
++errors;
cerr << " ERROR: Unable to open Instance file" << endl;
continue;
}
is >> in;
in.name = file.path().filename().replace_extension("").string();
}
if(*argv[1] == '2') { // Second version without greedy parameters, otherwise with default parameters
//Open the file conteining the params
// If found param, set it, otherwise use default value
ifstream paramStream(GetGreedyBestParamsPath(in.name));
if (!paramStream) {
throw runtime_error("ERROR: Cannot find Greedy parameter file: run Greedy algorithm or use default parameters");
}
while(getline(paramStream, line)) {
std::istringstream iss(line); //Split the input string
std::vector<string> results(std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>());
if (results[0] == "Profit") { // Skip first line
continue;
}
if (results[2] == "null") { // Default parameters
break;
}
if(results[1] == "wProfit:") {
wProfit = stod(results[2]);
}
else if(results[1] == "wTime:") {
wTime = stod(results[2]);
}
else if(results[1] == "maxDeviation:") {
maxDeviation = stod(results[2]);
}
else if(results[1] == "wNonCost:") {
wNonCost = stod(results[2]);
}
}
paramStream.close();
}
cerr << "LOG: param <" << wProfit << "; " << wTime << "; " << maxDeviation << "; " << wNonCost << ">" << endl;
TOP_Walker tw(in, wProfit, wTime, maxDeviation, wNonCost, 0);
TOP_Checker ck;
Backtrack(tw, ck, maxTime);
{ // Print the output
string titleDir = "outputs/backtracking/#";
titleDir.push_back(*argv[1]);
fs::create_directories(titleDir);
std::ofstream os(titleDir / file.path().filename().replace_extension(".out"));
if (!os) {
++errors;
std::cerr << " ERROR: Unable to open output file" << std::endl;
continue;
}
if (ck.GetBestCost() == 0) {
os << in;
os << "h 0";
}
else {
os << in << ck.GetBest();
}
}
{
string titleDir = "outputs/routeHops/backtracking/#";
titleDir.push_back(*argv[1]);
fs::create_directories(titleDir);
std::ofstream os(titleDir / file.path().filename().replace_extension(".out"));
if (!os) {
++errors;
std::cerr << " ERROR: Unable to open output file" << std::endl;
continue;
}
if (ck.GetBestCost() == 0) {
os << in;
os << "h 0";
}
else {
os << ck.GetBest();
}
}
// Print a ".csv" file with all the scores
if(chaoRes[cnt_istances].file == file.path().filename()) { // Compare with Chao
if(chaoRes[cnt_istances].chaoOptimum == -ck.GetBestCost()) {
solutionsStream << file.path().filename() << "," <<
chaoRes[cnt_istances].chaoOptimum << "," <<
-ck.GetBestCost() << "," << 1.0 << endl;
++cnt_istances;
continue;
}
solutionsStream << file.path().filename() << "," <<
chaoRes[cnt_istances].chaoOptimum << "," << -ck.GetBestCost() << "," <<
-ck.GetBestCost() / chaoRes[cnt_istances].chaoOptimum << endl;
++cnt_istances;
}
else { // New map found
solutionsStream << file.path().filename() << "," << -ck.GetBestCost() << "," << "(new map)" << endl;
}
}
solutionsStream.close();
return 0;
}
| 9,694 | 2,911 |
// -*- mode: c++; indent-tabs-mode: nil; -*-
//
// Copyright (c) 2009-2013 Illumina, Inc.
//
// This software is provided under the terms and conditions of the
// Illumina Open Source Software License 1.
//
// You should have received a copy of the Illumina Open Source
// Software License 1 along with this program. If not, see
// <https://github.com/sequencing/licenses/>
//
/// \file
///
/// an efficient (and slightly unsafe) class for basic tab-delimited files, etc...
///
/// \author Chris Saunders
///
#include "blt_util/blt_exception.hh"
#include "blt_util/istream_line_splitter.hh"
#include <cassert>
#include <cstring>
#include <iostream>
#include <sstream>
void
istream_line_splitter::
write_line(std::ostream& os) const {
for (unsigned i(0); i<_n_word; ++i) {
if (i) os << _sep;
os << word[i];
}
os << "\n";
}
void
istream_line_splitter::
dump(std::ostream& os) const {
os << "\tline_no: " << _line_no << "\n";
os << "\tline: ";
write_line(os);
}
void
istream_line_splitter::
increase_buffer_size() {
assert(_buf_size>1);
const unsigned old_buf_size(_buf_size);
const char* old_buf(_buf);
_buf_size *= 2;
_buf=new char[_buf_size];
memcpy(_buf,old_buf,(old_buf_size-1)*sizeof(char));
delete [] old_buf;
}
static
bool
check_istream(std::istream& is,
unsigned& line_no) {
if (is) {
line_no++;
// regular successful line read:
return true;
}
if (is.eof()) return false;
else if (is.fail()) {
if (is.bad()) {
std::ostringstream oss;
oss << "ERROR: unexpected failure while attempting to read line " << (line_no+1) << "\n";
throw blt_exception(oss.str().c_str());
}
is.clear();
}
// incomplete line read in this case, have to increase buffer size:
return true;
}
bool
istream_line_splitter::
parse_line() {
_n_word=0;
_is.getline(_buf,_buf_size);
const unsigned previous_line_no(_line_no);
if (! check_istream(_is,_line_no)) return false; // normal eof
unsigned buflen(strlen(_buf));
while (((buflen+1) == _buf_size) && (previous_line_no==_line_no)) {
increase_buffer_size();
_is.getline(_buf+buflen,_buf_size-buflen);
if (! check_istream(_is,_line_no)) {
std::ostringstream oss;
oss << "ERROR: Unexpected read failure in parse_line() at line_no: " << _line_no << "\n";
throw blt_exception(oss.str().c_str());
}
buflen=(strlen(_buf));
}
if ((buflen+1) >_buf_size) {
std::ostringstream oss;
oss << "ERROR: Unexpected read failure in parse_line() at line_no: " << _line_no << "\n";
throw blt_exception(oss.str().c_str());
}
if (NULL == _buf) return false;
assert(buflen);
// do a low-level separator parse:
{
char* p(_buf);
word[0]=p;
unsigned i(1);
while (i<_max_word) {
if ((*p == '\n') || (*p == '\0')) break;
if (*p == _sep) {
*p = '\0';
word[i++] = p+1;
}
++p;
}
_n_word=i;
}
return true;
}
| 3,214 | 1,140 |
#ifndef RADIUMENGINE_RENDERTECHNIQUE_HPP
#define RADIUMENGINE_RENDERTECHNIQUE_HPP
#include <Engine/RaEngine.hpp>
#include <Engine/Renderer/RenderTechnique/ShaderConfiguration.hpp>
#include <memory>
#include <map>
#include <functional>
namespace Ra {
namespace Engine {
class ShaderProgram;
class Material;
}
}
namespace Ra {
namespace Engine {
// TODO (Mathias) : Adapt RenderTechnique for multi-material purpose
// TODO transform the folowing ideas and insight into a real doc ...
// --> Interface that must be implemented by a RenderTechnique
// --> depthAmbiant Pass
// This pass must compute the Z of each Fragment and, optionally, the ambiant term
// (see DepthAmbiantPass shader of Forward Renderer)
// --> opaqueLighting Pass
// This pass must compute the lighting of the opaque aspect of the material
// (see BlinnPhong shader of Forward Renderer)
// --> transparentLighting Pass
// This pass must compute the lighting of the transparent aspect of the material
// (see LitOIT shader of Forward Renderer)
//
// --> modify RenderObject so that it is able to activate the required technique for rendering
// This is done but not yet finalized ... main rendering (internal render) is fixed, secondary renderings (ui,
// debug, ...) still have the possibilities to bypass the notion of Technique"
//
// A RenderTechnique correspond to a set shader configuration allowing to manage a Material while rendering.
// The set of configurations must contains what is required to render objects in the following ways :
// 1- depth and ambiant-environment lighting :
// Required for the depth pre-pass of several renderers.
// Must initialise the color. Initialization at 0 or to the base color of the fragments resulting from
// ambiant-Environment lighting
// * Default/Reference : DepthAmbiantPass shaders
// 2- Opaque lighting : THIS ONE IS MANDATORY, EACH MATERIAL MUST AT LEAST BE RENDERABLE AS OPAQUE OBJECT
// Main configuration, computes the resluting color according to a lighting configuration.
// The lighting configuration might contains one or severa sources of different types.
// * Default/Reference : BlinnPhong shaders
// 3- Transparent lighting :
// Same as opaque lighting but for transparent objects
// * Default/Reference LitOIT shaders
// 4- WhatElse ????
//
/* Exemple of use from Forward Renderer
*
* depthAmbiant pass
* Build a RenderParameters object defining the ambiant lighting configuration (envmap or irradiancemap or
* constant factor of base color.
* for each RenderObject
* call ro->render(ambiantLigthingPtarams, renderData(stange name for matrices + time), TECHNIQUE_DEPTH_AMBIANT);
*
* opaqueLighting pass :
* For each light sources set (from 1 to N light sources)
* Build a RenderParameters object defining the lighting configuration.
* For each RenderObject
* call ro->render(ambiantLigthingPtarams, renderData(stange name for matrices + time), TECHNIQUE_LIGHT_OPAQUE);
*
* transparentLighting pass
* For each light sources set (from 1 to N light sources)
* Build a RenderParameters object defining the lighting configuration.
* For each RenderObject
* call ro->render(ambiantLigthingPtarams, renderData(stange name for matrices + time), TECHNIQUE_LIGHT_TRANSPARENT);
*
* Each technique must be configured with its own shaders.
*
* TODO : Default rendertechnique must be renderer dependant ...
*/
class RA_ENGINE_API RenderTechnique
{
public:
enum PassName
{
Z_PREPASS = 1 << 0,
LIGHTING_OPAQUE = 1 << 1,
LIGHTING_TRANSPARENT = 1 << 2,
NO_PASS = 0
};
RenderTechnique();
RenderTechnique(const RenderTechnique &);
~RenderTechnique();
void setConfiguration(const ShaderConfiguration &newConfig, PassName pass = LIGHTING_OPAQUE);
// TODO : do we need all the config or only the basic part ?
ShaderConfiguration getConfiguration(PassName pass = LIGHTING_OPAQUE) const;
const ShaderProgram *getShader(PassName pass = LIGHTING_OPAQUE) const;
void setMaterial(const std::shared_ptr<Material> &material);
const std::shared_ptr<Material> &getMaterial() const;
void resetMaterial(Material *mat);
void updateGL();
bool shaderIsDirty(PassName pass = LIGHTING_OPAQUE) const;
// creates a Radium default rendertechnique :
// Z_PREPASS = DepthDepthAmbientPass
// LIGHTING_OPAQUE = BlinnPhong
// LIGHTING_TRANSPARENT = LitOIT
static Ra::Engine::RenderTechnique createDefaultRenderTechnique();
private:
using ConfigurationSet = std::map<PassName, ShaderConfiguration>;
using ShaderSet = std::map<PassName, const ShaderProgram *>;
ConfigurationSet shaderConfig;
ShaderSet shaders;
std::shared_ptr<Material> material = nullptr;
// Change this if there is more than 8 configurations
unsigned char dirtyBits = (Z_PREPASS | LIGHTING_OPAQUE | LIGHTING_TRANSPARENT);
unsigned char setPasses = NO_PASS;
};
///////////////////////////////////////////////
//// Radium defined technique ///
///////////////////////////////////////////////
namespace EngineRenderTechniques
{
// A default technique function is a function that will fill the given RenderTEchnique with the default
// configurations associated with a material
using DefaultTechniqueBuilder = std::function<void(RenderTechnique &, bool)>;
/** register a new default builder for a technique
* @return true if builder added, false else (e.g, a builder with the same name exists)
*/
RA_ENGINE_API bool registerDefaultTechnique(const std::string &name, DefaultTechniqueBuilder builder);
/** remove a default builder
* @return true if builder removed, false else (e.g, a builder with the same name does't exists)
*/
RA_ENGINE_API bool removeDefaultTechnique(const std::string &name);
/**
* @param name name of the technique to construct
* @return a pair containing the search result and, if true, the functor to call to build the technique.
*/
RA_ENGINE_API std::pair<bool, DefaultTechniqueBuilder> getDefaultTechnique(const std::string &name);
}
} // namespace Engine
} // namespace Ra
#endif // RADIUMENGINE_RENDERTECHNIQUE_HPP
| 7,791 | 2,019 |
/*ckwg +29
* Copyright 2016 by Kitware, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither name of Kitware, Inc. nor the names of any 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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file
* \brief config_explorer tool
*/
// Would be nice to provide better insight into config reading process.
// - Scan search path and report files found in a concise list.
// - How config_parser resolves include files.
//
#include <vital/config/config_block_io.h>
#include <vital/config/config_block.h>
#include <vital/config/config_parser.h>
#include <kwiversys/CommandLineArguments.hxx>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <string>
typedef kwiversys::CommandLineArguments argT;
// Global options
bool opt_config( false );
bool opt_detail_ds( false );
bool opt_detail_dc( false );
bool opt_help( false );
std::vector< std::string > opt_path;
std::string opt_app_name( "config_explorer" );
std::string opt_app_version;
std::string opt_install_prefix;
// ------------------------------------------------------------------
void
print_help()
{
std::cout << "This program assists in debugging config loading problems. It loads a \n"
<< "configuration and displays the contents or displays the search path.\n"
<< "Additional paths can be specified in \"KWIVER_CONFIG_PATH\" environment variable\n"
<< "or on the command line with the -I or --path options.\n"
<< "\n"
<< "Options are:\n"
<< " -h / --help displays usage information\n"
<< " --path name add directory to config search path(can appear multiple times)\n"
<< " -Iname add directory to config search path(can appear multiple times)\n"
<< " -ds generate detailed application-specific search paths\n"
<< " -dc generate detailed config contents output\n"
<< " -a name alternate application name\n"
<< " -v version optional application version string\n"
<< " --prefix dir optional non-standard install prefix directory\n"
<< "\n"
<< "If -ds is specified, the detailed search paths that apply to the application are\n"
<< "displayed only otherwise, the config file is loaded.\n"
<< "\n"
<< "The option -dc only has effect when a config file is specified and causes a\n"
<< "detailed output of the config entries.\n"
<< "\n"
<< "If -I or --path are specified, then the config file is only searched for using\n"
<< "the specified path. The application name based paths are not used.\n"
;
return;
}
// ------------------------------------------------------------------
int
path_callback( const char* argument, // name of argument
const char* value, // value of argument
void* call_data ) // data from register call
{
const std::string p( value );
opt_path.push_back( p );
return 1; // return true for OK
}
// ------------------------------------------------------------------
int
main( int argc, char* argv[] )
{
std::string plugin_name;
kwiversys::CommandLineArguments arg;
arg.Initialize( argc, argv );
arg.StoreUnusedArguments( true );
arg.AddArgument( "-h", argT::NO_ARGUMENT, &opt_help, "Display usage information" );
arg.AddArgument( "--help", argT::NO_ARGUMENT, &opt_help, "Display usage information" );
// details
arg.AddArgument( "-ds", argT::NO_ARGUMENT, &opt_detail_ds, "Display detailed application search path" );
arg.AddArgument( "-dc", argT::NO_ARGUMENT, &opt_detail_dc, "Display detailed config contents" );
// manual search path
arg.AddCallback( "--path", argT::SPACE_ARGUMENT, path_callback, 0, "Add directory to config search path" );
arg.AddCallback( "-I", argT::CONCAT_ARGUMENT, path_callback, 0, "Add directory to config search path" );
// auto search path generation
arg.AddArgument( "-a", argT::SPACE_ARGUMENT, &opt_app_name, "Application name" );
arg.AddArgument( "-v", argT::SPACE_ARGUMENT, &opt_app_version, "Application version string" );
arg.AddArgument( "--prefix", argT::SPACE_ARGUMENT, &opt_install_prefix,
"Non-standard installation prefix. (e.g. /opt/kitware)" );
if ( ! arg.Parse() )
{
std::cerr << "Problem parsing arguments" << std::endl;
exit( 0 );
}
if ( opt_help )
{
print_help();
return EXIT_SUCCESS;
}
char** newArgv = 0;
int newArgc = 0;
arg.GetUnusedArguments(&newArgc, &newArgv);
//
// Display application specific search path.
//
if ( opt_detail_ds )
{
kwiver::vital::config_path_list_t search_path =
kwiver::vital::application_config_file_paths( opt_app_name,
opt_app_version,
opt_install_prefix );
std::cout << "Application specific configuration search paths for\n"
<< " App name: " << opt_app_name << std::endl
<< " App version: " << opt_app_version << std::endl
<< " Install Prefix: " << opt_install_prefix << std::endl
<< std::endl;
for( auto path : search_path )
{
std::cout << path << std::endl;
}
return EXIT_SUCCESS;
}
// Read in config
if( newArgc == 1 )
{
std::cout << "Missing file name.\n"
<< "Usage: " << newArgv[0] << " config-file-name\n"
<< " " << newArgv[0] << " --help for usage details\n"
<< std::endl;
return EXIT_FAILURE;
}
const std::string config_file = newArgv[1];
arg.DeleteRemainingArguments(newArgc, &newArgv);
kwiver::vital::config_block_sptr config;
if ( ! opt_path.empty() )
{
std::cout << "Using custom search path.\n";
config = kwiver::vital::read_config_file( config_file,
opt_path );
}
else
{
std::cout << "Using application default search path.\n";
config = kwiver::vital::read_config_file( config_file,
opt_app_name,
opt_app_version,
opt_install_prefix,
true ); // merge all configs
}
//
// Dump details of config
//
if ( opt_detail_dc )
{
std::cout << "Config contents for\n"
<< " App name: " << opt_app_name << std::endl
<< " App version: " << opt_app_version << std::endl
<< " Install Prefix: " << opt_install_prefix << std::endl
<< std::endl;
kwiver::vital::write_config( config, std::cout );
}
return EXIT_SUCCESS;
} // main
| 8,269 | 2,507 |
// Copyright 2014 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "../../../include/fpdfapi/fpdf_render.h"
#include "../../../include/fpdfapi/fpdf_module.h"
#include "../fpdf_page/pageint.h"
#include "../../../include/fxge/fx_ge.h"
#include "../../../include/fxcodec/fx_codec.h"
#include "render_int.h"
CPDF_DocRenderData::CPDF_DocRenderData(CPDF_Document* pPDFDoc)
: m_pPDFDoc(pPDFDoc)
, m_pFontCache(NULL)
{
}
CPDF_DocRenderData::~CPDF_DocRenderData()
{
Clear(TRUE);
}
void CPDF_DocRenderData::Clear(FX_BOOL bRelease)
{
FX_POSITION pos;
{
pos = m_Type3FaceMap.GetStartPosition();
while (pos) {
CPDF_Font* pFont;
CPDF_CountedObject<CPDF_Type3Cache*>* cache;
m_Type3FaceMap.GetNextAssoc(pos, pFont, cache);
if (bRelease || cache->m_nCount < 2) {
delete cache->m_Obj;
delete cache;
m_Type3FaceMap.RemoveKey(pFont);
}
}
}
#ifndef _FPDFAPI_MINI_
{
pos = m_TransferFuncMap.GetStartPosition();
while (pos) {
CPDF_Object* key;
CPDF_CountedObject<CPDF_TransferFunc*>* value;
m_TransferFuncMap.GetNextAssoc(pos, key, value);
if (bRelease || value->m_nCount < 2) {
delete value->m_Obj;
delete value;
m_TransferFuncMap.RemoveKey(key);
}
}
}
#endif
if (m_pFontCache) {
if (bRelease) {
delete m_pFontCache;
m_pFontCache = NULL;
} else {
m_pFontCache->FreeCache(FALSE);
}
}
}
FX_BOOL CPDF_DocRenderData::Initialize()
{
m_pFontCache = FX_NEW CFX_FontCache;
return TRUE;
}
CPDF_Type3Cache* CPDF_DocRenderData::GetCachedType3(CPDF_Type3Font* pFont)
{
CPDF_CountedObject<CPDF_Type3Cache*>* pCache;
if (!m_Type3FaceMap.Lookup(pFont, pCache)) {
CPDF_Type3Cache* pType3 = FX_NEW CPDF_Type3Cache(pFont);
pCache = FX_NEW CPDF_CountedObject<CPDF_Type3Cache*>;
pCache->m_Obj = pType3;
pCache->m_nCount = 1;
m_Type3FaceMap.SetAt(pFont, pCache);
}
pCache->m_nCount++;
return pCache->m_Obj;
}
void CPDF_DocRenderData::ReleaseCachedType3(CPDF_Type3Font* pFont)
{
CPDF_CountedObject<CPDF_Type3Cache*>* pCache;
if (!m_Type3FaceMap.Lookup(pFont, pCache)) {
return;
}
pCache->m_nCount--;
}
class CPDF_RenderModule : public CPDF_RenderModuleDef
{
public:
virtual ~CPDF_RenderModule() {}
virtual FX_BOOL Installed()
{
return TRUE;
}
virtual CPDF_DocRenderData* CreateDocData(CPDF_Document* pDoc);
virtual void DestroyDocData(CPDF_DocRenderData* p);
virtual void ClearDocData(CPDF_DocRenderData* p);
virtual CPDF_DocRenderData* GetRenderData()
{
return &m_RenderData;
}
virtual CPDF_PageRenderCache* CreatePageCache(CPDF_Page* pPage)
{
return FX_NEW CPDF_PageRenderCache(pPage);
}
virtual void DestroyPageCache(CPDF_PageRenderCache* pCache);
virtual CPDF_RenderConfig* GetConfig()
{
return &m_RenderConfig;
}
private:
CPDF_DocRenderData m_RenderData;
CPDF_RenderConfig m_RenderConfig;
};
CPDF_DocRenderData* CPDF_RenderModule::CreateDocData(CPDF_Document* pDoc)
{
CPDF_DocRenderData* pData = FX_NEW CPDF_DocRenderData(pDoc);
pData->Initialize();
return pData;
}
void CPDF_RenderModule::DestroyDocData(CPDF_DocRenderData* pDocData)
{
delete pDocData;
}
void CPDF_RenderModule::ClearDocData(CPDF_DocRenderData* p)
{
if (p) {
p->Clear(FALSE);
}
}
void CPDF_RenderModule::DestroyPageCache(CPDF_PageRenderCache* pCache)
{
delete pCache;
}
void CPDF_ModuleMgr::InitRenderModule()
{
if (m_pRenderModule) {
delete m_pRenderModule;
}
m_pRenderModule = FX_NEW CPDF_RenderModule;
}
CPDF_RenderOptions::CPDF_RenderOptions()
: m_ColorMode(RENDER_COLOR_NORMAL)
, m_Flags(RENDER_CLEARTYPE)
, m_Interpolation(0)
, m_AddFlags(0)
, m_pOCContext(NULL)
, m_dwLimitCacheSize(1024 * 1024 * 100)
, m_HalftoneLimit(-1)
{
#if defined(_FPDFAPI_MINI_)
m_Flags |= RENDER_LIMITEDIMAGECACHE;
#endif
}
FX_ARGB CPDF_RenderOptions::TranslateColor(FX_ARGB argb) const
{
if (m_ColorMode == RENDER_COLOR_NORMAL) {
return argb;
}
if (m_ColorMode == RENDER_COLOR_ALPHA) {
return argb;
}
int a, r, g, b;
ArgbDecode(argb, a, r, g, b);
int gray = FXRGB2GRAY(r, g, b);
if (m_ColorMode == RENDER_COLOR_TWOCOLOR) {
int color = (r - gray) * (r - gray) + (g - gray) * (g - gray) + (b - gray) * (b - gray);
if (gray < 35 && color < 20) {
return ArgbEncode(a, m_ForeColor);
}
if (gray > 221 && color < 20) {
return ArgbEncode(a, m_BackColor);
}
return argb;
}
int fr = FXSYS_GetRValue(m_ForeColor);
int fg = FXSYS_GetGValue(m_ForeColor);
int fb = FXSYS_GetBValue(m_ForeColor);
int br = FXSYS_GetRValue(m_BackColor);
int bg = FXSYS_GetGValue(m_BackColor);
int bb = FXSYS_GetBValue(m_BackColor);
r = (br - fr) * gray / 255 + fr;
g = (bg - fg) * gray / 255 + fg;
b = (bb - fb) * gray / 255 + fb;
return ArgbEncode(a, r, g, b);
}
CPDF_RenderStatus::CPDF_RenderStatus()
{
m_pContext = NULL;
m_bStopped = FALSE;
m_Level = 0;
m_pDevice = NULL;
m_pCurObj = NULL;
m_pStopObj = NULL;
m_HalftoneLimit = 0;
m_pObjectRenderer = NULL;
m_bPrint = FALSE;
m_Transparency = 0;
m_DitherBits = 0;
m_bDropObjects = FALSE;
m_bStdCS = FALSE;
m_GroupFamily = 0;
m_bLoadMask = FALSE;
m_pType3Char = NULL;
m_T3FillColor = 0;
m_pFormResource = NULL;
m_pPageResource = NULL;
m_curBlend = FXDIB_BLEND_NORMAL;
}
CPDF_RenderStatus::~CPDF_RenderStatus()
{
if (m_pObjectRenderer) {
delete m_pObjectRenderer;
}
}
FX_BOOL CPDF_RenderStatus::Initialize(int level, CPDF_RenderContext* pContext, CFX_RenderDevice* pDevice,
const CFX_AffineMatrix* pDeviceMatrix, const CPDF_PageObject* pStopObj,
const CPDF_RenderStatus* pParentState, const CPDF_GraphicStates* pInitialStates,
const CPDF_RenderOptions* pOptions, int transparency, FX_BOOL bDropObjects,
CPDF_Dictionary* pFormResource, FX_BOOL bStdCS, CPDF_Type3Char* pType3Char,
FX_ARGB fill_color, FX_DWORD GroupFamily,
FX_BOOL bLoadMask)
{
m_Level = level;
m_pContext = pContext;
m_pDevice = pDevice;
m_DitherBits = pDevice->GetDeviceCaps(FXDC_DITHER_BITS);
m_bPrint = m_pDevice->GetDeviceClass() != FXDC_DISPLAY;
if (pDeviceMatrix) {
m_DeviceMatrix = *pDeviceMatrix;
}
m_pStopObj = pStopObj;
if (pOptions) {
m_Options = *pOptions;
}
m_bDropObjects = bDropObjects;
m_bStdCS = bStdCS;
m_T3FillColor = fill_color;
m_pType3Char = pType3Char;
m_GroupFamily = GroupFamily;
m_bLoadMask = bLoadMask;
m_pFormResource = pFormResource;
m_pPageResource = m_pContext->m_pPageResources;
if (pInitialStates && !m_pType3Char) {
m_InitialStates.CopyStates(*pInitialStates);
if (pParentState) {
CPDF_ColorStateData* pColorData = (CPDF_ColorStateData*)(const CPDF_ColorStateData*)m_InitialStates.m_ColorState;
CPDF_ColorStateData* pParentData = (CPDF_ColorStateData*)(const CPDF_ColorStateData*)pParentState->m_InitialStates.m_ColorState;
if (!pColorData || pColorData->m_FillColor.IsNull()) {
CPDF_ColorStateData* pData = m_InitialStates.m_ColorState.GetModify();
pData->m_FillRGB = pParentData->m_FillRGB;
pData->m_FillColor.Copy(&pParentData->m_FillColor);
}
if (!pColorData || pColorData->m_StrokeColor.IsNull()) {
CPDF_ColorStateData* pData = m_InitialStates.m_ColorState.GetModify();
pData->m_StrokeRGB = pParentData->m_FillRGB;
pData->m_StrokeColor.Copy(&pParentData->m_StrokeColor);
}
}
} else {
m_InitialStates.DefaultStates();
}
#if defined(_FPDFAPI_MINI_)||defined(_FXCORE_LIMITED_CPU_)
m_HalftoneLimit = CPDF_ModuleMgr::Get()->GetRenderModule()->GetConfig()->m_HalftoneLimit;
if (pOptions && pOptions->m_HalftoneLimit >= 0) {
m_HalftoneLimit = pOptions->m_HalftoneLimit;
}
#endif
m_pObjectRenderer = NULL;
m_Transparency = transparency;
return TRUE;
}
void CPDF_RenderStatus::RenderObjectList(const CPDF_PageObjects* pObjs, const CFX_AffineMatrix* pObj2Device)
{
if (m_Level > 32) {
return;
}
CFX_FloatRect clip_rect = m_pDevice->GetClipBox();
CFX_AffineMatrix device2object;
device2object.SetReverse(*pObj2Device);
device2object.TransformRect(clip_rect);
int index = 0;
FX_POSITION pos = pObjs->GetFirstObjectPosition();
while(pos) {
index ++;
CPDF_PageObject* pCurObj = pObjs->GetNextObject(pos);
if (pCurObj == m_pStopObj) {
m_bStopped = TRUE;
return;
}
if (!pCurObj) {
continue;
}
if(pCurObj == NULL || pCurObj->m_Left > clip_rect.right || pCurObj->m_Right < clip_rect.left ||
pCurObj->m_Bottom > clip_rect.top || pCurObj->m_Top < clip_rect.bottom) {
continue;
}
RenderSingleObject(pCurObj, pObj2Device);
if (m_bStopped) {
return;
}
}
}
void CPDF_RenderStatus::RenderSingleObject(const CPDF_PageObject* pObj, const CFX_AffineMatrix* pObj2Device)
{
if (m_Level > 32) {
return;
}
m_pCurObj = pObj;
if (m_Options.m_pOCContext && pObj->m_ContentMark.NotNull())
if (!m_Options.m_pOCContext->CheckObjectVisible(pObj)) {
return;
}
ProcessClipPath(pObj->m_ClipPath, pObj2Device);
if (ProcessTransparency(pObj, pObj2Device)) {
return;
}
ProcessObjectNoClip(pObj, pObj2Device);
}
FX_BOOL CPDF_RenderStatus::ContinueSingleObject(const CPDF_PageObject* pObj, const CFX_AffineMatrix* pObj2Device, IFX_Pause* pPause)
{
if (m_pObjectRenderer) {
if (m_pObjectRenderer->Continue(pPause)) {
return TRUE;
}
if (!m_pObjectRenderer->m_Result) {
DrawObjWithBackground(pObj, pObj2Device);
}
#ifdef _FPDFAPI_MINI_
if (m_DitherBits) {
DitherObjectArea(pObj, pObj2Device);
}
#endif
delete m_pObjectRenderer;
m_pObjectRenderer = NULL;
return FALSE;
}
m_pCurObj = pObj;
if (m_Options.m_pOCContext && pObj->m_ContentMark.NotNull())
if (!m_Options.m_pOCContext->CheckObjectVisible(pObj)) {
return FALSE;
}
ProcessClipPath(pObj->m_ClipPath, pObj2Device);
if (ProcessTransparency(pObj, pObj2Device)) {
return FALSE;
}
if (pObj->m_Type == PDFPAGE_IMAGE) {
m_pObjectRenderer = IPDF_ObjectRenderer::Create(pObj->m_Type);
if (!m_pObjectRenderer->Start(this, pObj, pObj2Device, FALSE)) {
if (!m_pObjectRenderer->m_Result) {
DrawObjWithBackground(pObj, pObj2Device);
}
#ifdef _FPDFAPI_MINI_
if (m_DitherBits) {
DitherObjectArea(pObj, pObj2Device);
}
#endif
delete m_pObjectRenderer;
m_pObjectRenderer = NULL;
return FALSE;
}
return ContinueSingleObject(pObj, pObj2Device, pPause);
}
ProcessObjectNoClip(pObj, pObj2Device);
return FALSE;
}
IPDF_ObjectRenderer* IPDF_ObjectRenderer::Create(int type)
{
IPDF_ObjectRenderer* pRenderer = NULL;
if (type == PDFPAGE_IMAGE) {
pRenderer = FX_NEW CPDF_ImageRenderer;
}
return pRenderer;
}
FX_BOOL CPDF_RenderStatus::GetObjectClippedRect(const CPDF_PageObject* pObj, const CFX_AffineMatrix* pObj2Device, FX_BOOL bLogical, FX_RECT &rect) const
{
rect = pObj->GetBBox(pObj2Device);
FX_RECT rtClip = m_pDevice->GetClipBox();
if (!bLogical) {
CFX_Matrix dCTM = m_pDevice->GetCTM();
FX_FLOAT a = FXSYS_fabs(dCTM.a);
FX_FLOAT d = FXSYS_fabs(dCTM.d);
if (a != 1.0f || d != 1.0f) {
rect.right = rect.left + (FX_INT32)FXSYS_ceil((FX_FLOAT)rect.Width() * a);
rect.bottom = rect.top + (FX_INT32)FXSYS_ceil((FX_FLOAT)rect.Height() * d);
rtClip.right = rtClip.left + (FX_INT32)FXSYS_ceil((FX_FLOAT)rtClip.Width() * a);
rtClip.bottom = rtClip.top + (FX_INT32)FXSYS_ceil((FX_FLOAT)rtClip.Height() * d);
}
}
rect.Intersect(rtClip);
return rect.IsEmpty();
}
void CPDF_RenderStatus::DitherObjectArea(const CPDF_PageObject* pObj, const CFX_AffineMatrix* pObj2Device)
{
CFX_DIBitmap* pBitmap = m_pDevice->GetBitmap();
if (pBitmap == NULL) {
return;
}
FX_RECT rect;
if (GetObjectClippedRect(pObj, pObj2Device, FALSE, rect)) {
return;
}
if (m_DitherBits == 2) {
static FX_ARGB pal[4] = {0, 85, 170, 255};
pBitmap->DitherFS(pal, 4, &rect);
} else if (m_DitherBits == 3) {
static FX_ARGB pal[8] = {0, 36, 73, 109, 146, 182, 219, 255};
pBitmap->DitherFS(pal, 8, &rect);
} else if (m_DitherBits == 4) {
static FX_ARGB pal[16] = {0, 17, 34, 51, 68, 85, 102, 119, 136, 153, 170, 187, 204, 221, 238, 255};
pBitmap->DitherFS(pal, 16, &rect);
}
}
void CPDF_RenderStatus::ProcessObjectNoClip(const CPDF_PageObject* pObj, const CFX_AffineMatrix* pObj2Device)
{
FX_BOOL bRet = FALSE;
switch (pObj->m_Type) {
case PDFPAGE_TEXT:
bRet = ProcessText((CPDF_TextObject*)pObj, pObj2Device, NULL);
break;
case PDFPAGE_PATH:
bRet = ProcessPath((CPDF_PathObject*)pObj, pObj2Device);
break;
case PDFPAGE_IMAGE:
bRet = ProcessImage((CPDF_ImageObject*)pObj, pObj2Device);
break;
case PDFPAGE_SHADING:
bRet = ProcessShading((CPDF_ShadingObject*)pObj, pObj2Device);
break;
case PDFPAGE_FORM:
bRet = ProcessForm((CPDF_FormObject*)pObj, pObj2Device);
break;
#if defined(_FPDFAPI_MINI_)
case PDFPAGE_INLINES:
bRet = ProcessInlines((CPDF_InlineImages*)pObj, pObj2Device);
break;
#endif
}
if (!bRet) {
DrawObjWithBackground(pObj, pObj2Device);
}
}
FX_BOOL CPDF_RenderStatus::DrawObjWithBlend(const CPDF_PageObject* pObj, const CFX_AffineMatrix* pObj2Device)
{
FX_BOOL bRet = FALSE;
switch (pObj->m_Type) {
case PDFPAGE_PATH:
bRet = ProcessPath((CPDF_PathObject*)pObj, pObj2Device);
break;
case PDFPAGE_IMAGE:
bRet = ProcessImage((CPDF_ImageObject *)pObj, pObj2Device);
break;
case PDFPAGE_FORM:
bRet = ProcessForm((CPDF_FormObject*)pObj, pObj2Device);
break;
}
return bRet;
}
void CPDF_RenderStatus::GetScaledMatrix(CFX_Matrix &matrix) const
{
CFX_Matrix dCTM = m_pDevice->GetCTM();
matrix.a *= FXSYS_fabs(dCTM.a);
matrix.d *= FXSYS_fabs(dCTM.d);
}
void CPDF_RenderStatus::DrawObjWithBackground(const CPDF_PageObject* pObj, const CFX_AffineMatrix* pObj2Device)
{
#if !defined(_FPDFAPI_MINI_) || defined(_FXCORE_FEATURE_ALL_)
FX_RECT rect;
if (GetObjectClippedRect(pObj, pObj2Device, FALSE, rect)) {
return;
}
int res = 300;
if (pObj->m_Type == PDFPAGE_IMAGE && m_pDevice->GetDeviceCaps(FXDC_DEVICE_CLASS) == FXDC_PRINTER) {
res = 0;
}
CPDF_ScaledRenderBuffer buffer;
if (!buffer.Initialize(m_pContext, m_pDevice, &rect, pObj, &m_Options, res)) {
return;
}
CFX_AffineMatrix matrix = *pObj2Device;
matrix.Concat(*buffer.GetMatrix());
GetScaledMatrix(matrix);
CPDF_Dictionary* pFormResource = NULL;
if (pObj->m_Type == PDFPAGE_FORM) {
CPDF_FormObject* pFormObj = (CPDF_FormObject*)pObj;
if (pFormObj->m_pForm && pFormObj->m_pForm->m_pFormDict) {
pFormResource = pFormObj->m_pForm->m_pFormDict->GetDict(FX_BSTRC("Resources"));
}
}
CPDF_RenderStatus status;
status.Initialize(m_Level + 1, m_pContext, buffer.GetDevice(), buffer.GetMatrix(), NULL, NULL, NULL, &m_Options, m_Transparency, m_bDropObjects, pFormResource);
status.RenderSingleObject(pObj, &matrix);
buffer.OutputToDevice();
#endif
}
FX_BOOL CPDF_RenderStatus::ProcessForm(CPDF_FormObject* pFormObj, const CFX_AffineMatrix* pObj2Device)
{
CPDF_Dictionary* pOC = pFormObj->m_pForm->m_pFormDict->GetDict(FX_BSTRC("OC"));
if (pOC && m_Options.m_pOCContext && !m_Options.m_pOCContext->CheckOCGVisible(pOC)) {
return TRUE;
}
CFX_AffineMatrix matrix = pFormObj->m_FormMatrix;
matrix.Concat(*pObj2Device);
CPDF_Dictionary* pResources = NULL;
if (pFormObj->m_pForm && pFormObj->m_pForm->m_pFormDict) {
pResources = pFormObj->m_pForm->m_pFormDict->GetDict(FX_BSTRC("Resources"));
}
CPDF_RenderStatus status;
status.Initialize(m_Level + 1, m_pContext, m_pDevice, NULL, m_pStopObj,
this, pFormObj, &m_Options, m_Transparency, m_bDropObjects, pResources, FALSE);
status.m_curBlend = m_curBlend;
m_pDevice->SaveState();
status.RenderObjectList(pFormObj->m_pForm, &matrix);
m_bStopped = status.m_bStopped;
m_pDevice->RestoreState();
return TRUE;
}
FX_BOOL IsAvailableMatrix(const CFX_AffineMatrix& matrix)
{
if (matrix.a == 0 || matrix.d == 0) {
return matrix.b != 0 && matrix.c != 0;
}
if (matrix.b == 0 || matrix.c == 0) {
return matrix.a != 0 && matrix.d != 0;
}
return TRUE;
}
FX_BOOL CPDF_RenderStatus::ProcessPath(CPDF_PathObject* pPathObj, const CFX_AffineMatrix* pObj2Device)
{
int FillType = pPathObj->m_FillType;
FX_BOOL bStroke = pPathObj->m_bStroke;
ProcessPathPattern(pPathObj, pObj2Device, FillType, bStroke);
if (FillType == 0 && !bStroke) {
return TRUE;
}
FX_DWORD fill_argb = 0;
if (FillType) {
fill_argb = GetFillArgb(pPathObj);
}
FX_DWORD stroke_argb = 0;
if (bStroke) {
stroke_argb = GetStrokeArgb(pPathObj);
}
CFX_AffineMatrix path_matrix = pPathObj->m_Matrix;
path_matrix.Concat(*pObj2Device);
if (!IsAvailableMatrix(path_matrix)) {
return TRUE;
}
if (FillType && (m_Options.m_Flags & RENDER_RECT_AA)) {
FillType |= FXFILL_RECT_AA;
}
if (m_Options.m_Flags & RENDER_FILL_FULLCOVER) {
FillType |= FXFILL_FULLCOVER;
}
if (m_Options.m_Flags & RENDER_NOPATHSMOOTH) {
FillType |= FXFILL_NOPATHSMOOTH;
}
if (bStroke) {
FillType |= FX_FILL_STROKE;
}
#if !defined(_FPDFAPI_MINI_) || defined(_FXCORE_FEATURE_ALL_)
const CPDF_GeneralStateData* pGeneralData = ((CPDF_PageObject*)pPathObj)->m_GeneralState;
if (pGeneralData && pGeneralData->m_StrokeAdjust) {
FillType |= FX_STROKE_ADJUST;
}
#endif
if (m_pType3Char) {
FillType |= FX_FILL_TEXT_MODE;
}
CFX_GraphStateData graphState(*pPathObj->m_GraphState);
if (m_Options.m_Flags & RENDER_THINLINE) {
graphState.m_LineWidth = 0;
}
return m_pDevice->DrawPath(pPathObj->m_Path, &path_matrix, &graphState, fill_argb, stroke_argb, FillType, 0, NULL, m_curBlend);
}
CPDF_TransferFunc* CPDF_RenderStatus::GetTransferFunc(CPDF_Object* pObj) const
{
ASSERT(pObj != NULL);
CPDF_DocRenderData* pDocCache = m_pContext->m_pDocument->GetRenderData();
if (!pDocCache) {
return NULL;
}
return pDocCache->GetTransferFunc(pObj);
}
FX_ARGB CPDF_RenderStatus::GetFillArgb(const CPDF_PageObject* pObj, FX_BOOL bType3) const
{
CPDF_ColorStateData* pColorData = (CPDF_ColorStateData*)(const CPDF_ColorStateData*)pObj->m_ColorState;
if (m_pType3Char && !bType3 && (!m_pType3Char->m_bColored || (m_pType3Char->m_bColored && (!pColorData || pColorData->m_FillColor.IsNull())))) {
return m_T3FillColor;
} else if (!pColorData || pColorData->m_FillColor.IsNull()) {
pColorData = (CPDF_ColorStateData*)(const CPDF_ColorStateData*)m_InitialStates.m_ColorState;
}
FX_COLORREF rgb = pColorData->m_FillRGB;
if (rgb == (FX_DWORD) - 1) {
return 0;
}
const CPDF_GeneralStateData* pGeneralData = pObj->m_GeneralState;
int alpha;
if (pGeneralData) {
alpha = (FX_INT32)(pGeneralData->m_FillAlpha * 255);
#ifndef _FPDFAPI_MINI_
if (pGeneralData->m_pTR) {
if (!pGeneralData->m_pTransferFunc) {
((CPDF_GeneralStateData*)pGeneralData)->m_pTransferFunc = GetTransferFunc(pGeneralData->m_pTR);
}
if (pGeneralData->m_pTransferFunc) {
rgb = pGeneralData->m_pTransferFunc->TranslateColor(rgb);
}
}
#endif
} else {
alpha = 255;
}
return m_Options.TranslateColor(ArgbEncode(alpha, rgb));
}
FX_ARGB CPDF_RenderStatus::GetStrokeArgb(const CPDF_PageObject* pObj) const
{
CPDF_ColorStateData* pColorData = (CPDF_ColorStateData*)(const CPDF_ColorStateData*)pObj->m_ColorState;
if (m_pType3Char && (!m_pType3Char->m_bColored || (m_pType3Char->m_bColored && (!pColorData || pColorData->m_StrokeColor.IsNull())))) {
return m_T3FillColor;
} else if (!pColorData || pColorData->m_StrokeColor.IsNull()) {
pColorData = (CPDF_ColorStateData*)(const CPDF_ColorStateData*)m_InitialStates.m_ColorState;
}
FX_COLORREF rgb = pColorData->m_StrokeRGB;
if (rgb == (FX_DWORD) - 1) {
return 0;
}
const CPDF_GeneralStateData* pGeneralData = pObj->m_GeneralState;
int alpha;
if (pGeneralData) {
alpha = (FX_INT32)(pGeneralData->m_StrokeAlpha * 255);
#ifndef _FPDFAPI_MINI_
if (pGeneralData->m_pTR) {
if (!pGeneralData->m_pTransferFunc) {
((CPDF_GeneralStateData*)pGeneralData)->m_pTransferFunc = GetTransferFunc(pGeneralData->m_pTR);
}
if (pGeneralData->m_pTransferFunc) {
rgb = pGeneralData->m_pTransferFunc->TranslateColor(rgb);
}
}
#endif
} else {
alpha = 255;
}
return m_Options.TranslateColor(ArgbEncode(alpha, rgb));
}
void CPDF_RenderStatus::ProcessClipPath(CPDF_ClipPath ClipPath, const CFX_AffineMatrix* pObj2Device)
{
if (ClipPath.IsNull()) {
if (m_LastClipPath.IsNull()) {
return;
}
m_pDevice->RestoreState(TRUE);
m_LastClipPath.SetNull();
return;
}
if (m_LastClipPath == ClipPath) {
return;
}
m_LastClipPath = ClipPath;
m_pDevice->RestoreState(TRUE);
int nClipPath = ClipPath.GetPathCount();
int i;
for (i = 0; i < nClipPath; i++) {
const CFX_PathData* pPathData = ClipPath.GetPath(i);
if (pPathData == NULL) {
continue;
}
if (pPathData->GetPointCount() == 0) {
CFX_PathData EmptyPath;
EmptyPath.AppendRect(-1, -1, 0, 0);
int fill_mode = FXFILL_WINDING;
m_pDevice->SetClip_PathFill(&EmptyPath, NULL, fill_mode);
} else {
int ClipType = ClipPath.GetClipType(i);
m_pDevice->SetClip_PathFill(pPathData, pObj2Device, ClipType);
}
}
int textcount = ClipPath.GetTextCount();
if (textcount == 0) {
return;
}
if (m_pDevice->GetDeviceClass() == FXDC_DISPLAY && !(m_pDevice->GetDeviceCaps(FXDC_RENDER_CAPS) & FXRC_SOFT_CLIP)) {
return;
}
CFX_PathData* pTextClippingPath = NULL;
for (i = 0; i < textcount; i ++) {
CPDF_TextObject* pText = ClipPath.GetText(i);
if (pText == NULL) {
if (pTextClippingPath) {
int fill_mode = FXFILL_WINDING;
if (m_Options.m_Flags & RENDER_NOTEXTSMOOTH) {
fill_mode |= FXFILL_NOPATHSMOOTH;
}
m_pDevice->SetClip_PathFill(pTextClippingPath, NULL, fill_mode);
delete pTextClippingPath;
pTextClippingPath = NULL;
}
} else {
if (pTextClippingPath == NULL) {
pTextClippingPath = FX_NEW CFX_PathData;
}
ProcessText(pText, pObj2Device, pTextClippingPath);
}
}
if (pTextClippingPath) {
delete pTextClippingPath;
}
}
void CPDF_RenderStatus::DrawClipPath(CPDF_ClipPath ClipPath, const CFX_AffineMatrix* pObj2Device)
{
if (ClipPath.IsNull()) {
return;
}
int fill_mode = 0;
if (m_Options.m_Flags & RENDER_NOPATHSMOOTH) {
fill_mode |= FXFILL_NOPATHSMOOTH;
}
int nClipPath = ClipPath.GetPathCount();
int i;
for (i = 0; i < nClipPath; i++) {
const CFX_PathData* pPathData = ClipPath.GetPath(i);
if (pPathData == NULL) {
continue;
}
CFX_GraphStateData stroke_state;
if (m_Options.m_Flags & RENDER_THINLINE) {
stroke_state.m_LineWidth = 0;
}
m_pDevice->DrawPath(pPathData, pObj2Device, &stroke_state, 0, 0xffff0000, fill_mode);
}
}
FX_BOOL CPDF_RenderStatus::SelectClipPath(CPDF_PathObject* pPathObj, const CFX_AffineMatrix* pObj2Device, FX_BOOL bStroke)
{
CFX_AffineMatrix path_matrix = pPathObj->m_Matrix;
path_matrix.Concat(*pObj2Device);
if (bStroke) {
CFX_GraphStateData graphState(*pPathObj->m_GraphState);
if (m_Options.m_Flags & RENDER_THINLINE) {
graphState.m_LineWidth = 0;
}
return m_pDevice->SetClip_PathStroke(pPathObj->m_Path, &path_matrix, &graphState);
}
int fill_mode = pPathObj->m_FillType;
if (m_Options.m_Flags & RENDER_NOPATHSMOOTH) {
fill_mode |= FXFILL_NOPATHSMOOTH;
}
return m_pDevice->SetClip_PathFill(pPathObj->m_Path, &path_matrix, fill_mode);
}
FX_BOOL CPDF_RenderStatus::ProcessTransparency(const CPDF_PageObject* pPageObj, const CFX_AffineMatrix* pObj2Device)
{
const CPDF_GeneralStateData* pGeneralState = pPageObj->m_GeneralState;
int blend_type = pGeneralState ? pGeneralState->m_BlendType : FXDIB_BLEND_NORMAL;
if (blend_type == FXDIB_BLEND_UNSUPPORTED) {
return TRUE;
}
CPDF_Dictionary* pSMaskDict = pGeneralState ? (CPDF_Dictionary*)pGeneralState->m_pSoftMask : NULL;
if (pSMaskDict) {
if (pPageObj->m_Type == PDFPAGE_IMAGE &&
((CPDF_ImageObject*)pPageObj)->m_pImage->GetDict()->KeyExist(FX_BSTRC("SMask"))) {
pSMaskDict = NULL;
}
}
CPDF_Dictionary* pFormResource = NULL;
FX_FLOAT group_alpha = 1.0f;
int Transparency = m_Transparency;
FX_BOOL bGroupTransparent = FALSE;
if (pPageObj->m_Type == PDFPAGE_FORM) {
CPDF_FormObject* pFormObj = (CPDF_FormObject*)pPageObj;
const CPDF_GeneralStateData *pStateData = pFormObj->m_GeneralState.GetObject();
if (pStateData) {
group_alpha = pStateData->m_FillAlpha;
}
Transparency = pFormObj->m_pForm->m_Transparency;
bGroupTransparent = Transparency & PDFTRANS_ISOLATED ? TRUE : FALSE;
if (pFormObj->m_pForm->m_pFormDict) {
pFormResource = pFormObj->m_pForm->m_pFormDict->GetDict("Resources");
}
}
FX_BOOL bTextClip = FALSE;
if (pPageObj->m_ClipPath.NotNull() && pPageObj->m_ClipPath.GetTextCount() &&
m_pDevice->GetDeviceClass() == FXDC_DISPLAY && !(m_pDevice->GetDeviceCaps(FXDC_RENDER_CAPS) & FXRC_SOFT_CLIP)) {
bTextClip = TRUE;
}
if ((m_Options.m_Flags & RENDER_OVERPRINT) && pPageObj->m_Type == PDFPAGE_IMAGE && pGeneralState && pGeneralState->m_FillOP && pGeneralState->m_StrokeOP) {
CPDF_Document* pDocument = NULL;
CPDF_Page* pPage = NULL;
if (m_pContext->m_pPageCache) {
pPage = m_pContext->m_pPageCache->GetPage();
pDocument = pPage->m_pDocument;
} else {
pDocument = ((CPDF_ImageObject*)pPageObj)->m_pImage->GetDocument();
}
CPDF_Dictionary* pPageResources = pPage ? pPage->m_pPageResources : NULL;
CPDF_Object* pCSObj = ((CPDF_ImageObject*)pPageObj)->m_pImage->GetStream()->GetDict()->GetElementValue(FX_BSTRC("ColorSpace"));
CPDF_ColorSpace* pColorSpace = pDocument->LoadColorSpace(pCSObj, pPageResources);
if (pColorSpace) {
int format = pColorSpace->GetFamily();
if (format == PDFCS_DEVICECMYK || format == PDFCS_SEPARATION || format == PDFCS_DEVICEN) {
blend_type = FXDIB_BLEND_DARKEN;
}
pDocument->GetPageData()->ReleaseColorSpace(pCSObj);
}
}
if (pSMaskDict == NULL && group_alpha == 1.0f && blend_type == FXDIB_BLEND_NORMAL && !bTextClip && !bGroupTransparent) {
return FALSE;
}
FX_BOOL isolated = Transparency & PDFTRANS_ISOLATED;
if (m_bPrint) {
FX_BOOL bRet = FALSE;
int rendCaps = m_pDevice->GetRenderCaps();
if (!((Transparency & PDFTRANS_ISOLATED) || pSMaskDict || bTextClip) && (rendCaps & FXRC_BLEND_MODE)) {
int oldBlend = m_curBlend;
m_curBlend = blend_type;
bRet = DrawObjWithBlend(pPageObj, pObj2Device);
m_curBlend = oldBlend;
}
if (!bRet) {
DrawObjWithBackground(pPageObj, pObj2Device);
}
return TRUE;
}
FX_RECT rect = pPageObj->GetBBox(pObj2Device);
rect.Intersect(m_pDevice->GetClipBox());
if (rect.IsEmpty()) {
return TRUE;
}
CFX_Matrix deviceCTM = m_pDevice->GetCTM();
FX_FLOAT scaleX = FXSYS_fabs(deviceCTM.a);
FX_FLOAT scaleY = FXSYS_fabs(deviceCTM.d);
int width = FXSYS_round((FX_FLOAT)rect.Width() * scaleX);
int height = FXSYS_round((FX_FLOAT)rect.Height() * scaleY);
CFX_FxgeDevice bitmap_device;
CFX_DIBitmap* oriDevice = NULL;
if (!isolated && (m_pDevice->GetRenderCaps() & FXRC_GET_BITS)) {
oriDevice = FX_NEW CFX_DIBitmap;
if (!m_pDevice->CreateCompatibleBitmap(oriDevice, width, height)) {
return TRUE;
}
m_pDevice->GetDIBits(oriDevice, rect.left, rect.top);
}
if (!bitmap_device.Create(width, height, FXDIB_Argb, 0, oriDevice)) {
return TRUE;
}
CFX_DIBitmap* bitmap = bitmap_device.GetBitmap();
bitmap->Clear(0);
CFX_AffineMatrix new_matrix = *pObj2Device;
new_matrix.TranslateI(-rect.left, -rect.top);
new_matrix.Scale(scaleX, scaleY);
CFX_DIBitmap* pTextMask = NULL;
if (bTextClip) {
pTextMask = FX_NEW CFX_DIBitmap;
if (!pTextMask->Create(width, height, FXDIB_8bppMask)) {
delete pTextMask;
return TRUE;
}
pTextMask->Clear(0);
CFX_FxgeDevice text_device;
text_device.Attach(pTextMask);
for (FX_DWORD i = 0; i < pPageObj->m_ClipPath.GetTextCount(); i ++) {
CPDF_TextObject* textobj = pPageObj->m_ClipPath.GetText(i);
if (textobj == NULL) {
break;
}
CFX_AffineMatrix text_matrix;
textobj->GetTextMatrix(&text_matrix);
CPDF_TextRenderer::DrawTextPath(&text_device, textobj->m_nChars, textobj->m_pCharCodes, textobj->m_pCharPos,
textobj->m_TextState.GetFont(), textobj->m_TextState.GetFontSize(),
&text_matrix, &new_matrix, textobj->m_GraphState, (FX_ARGB) - 1, 0, NULL);
}
}
CPDF_RenderStatus bitmap_render;
bitmap_render.Initialize(m_Level + 1, m_pContext, &bitmap_device, NULL,
m_pStopObj, NULL, NULL, &m_Options, 0, m_bDropObjects, pFormResource, TRUE);
bitmap_render.ProcessObjectNoClip(pPageObj, &new_matrix);
m_bStopped = bitmap_render.m_bStopped;
if (pSMaskDict) {
CFX_AffineMatrix smask_matrix;
FXSYS_memcpy32(&smask_matrix, pGeneralState->m_SMaskMatrix, sizeof smask_matrix);
smask_matrix.Concat(*pObj2Device);
CFX_DIBSource* pSMaskSource = LoadSMask(pSMaskDict, &rect, &smask_matrix);
if (pSMaskSource) {
bitmap->MultiplyAlpha(pSMaskSource);
delete pSMaskSource;
}
}
if (pTextMask) {
bitmap->MultiplyAlpha(pTextMask);
delete pTextMask;
pTextMask = NULL;
}
if (Transparency & PDFTRANS_GROUP && group_alpha != 1.0f) {
bitmap->MultiplyAlpha((FX_INT32)(group_alpha * 255));
}
Transparency = m_Transparency;
if (pPageObj->m_Type == PDFPAGE_FORM) {
Transparency |= PDFTRANS_GROUP;
}
CompositeDIBitmap(bitmap, rect.left, rect.top, 0, 255, blend_type, Transparency);
if (oriDevice) {
delete oriDevice;
}
return TRUE;
}
CFX_DIBitmap* CPDF_RenderStatus::GetBackdrop(const CPDF_PageObject* pObj, const FX_RECT& rect, int& left, int& top,
FX_BOOL bBackAlphaRequired)
{
FX_RECT bbox = rect;
bbox.Intersect(m_pDevice->GetClipBox());
left = bbox.left;
top = bbox.top;
CFX_Matrix deviceCTM = m_pDevice->GetCTM();
FX_FLOAT scaleX = FXSYS_fabs(deviceCTM.a);
FX_FLOAT scaleY = FXSYS_fabs(deviceCTM.d);
int width = FXSYS_round(bbox.Width() * scaleX);
int height = FXSYS_round(bbox.Height() * scaleY);
CFX_DIBitmap* pBackdrop = FX_NEW CFX_DIBitmap;
if (bBackAlphaRequired && !m_bDropObjects) {
pBackdrop->Create(width, height, FXDIB_Argb);
} else {
m_pDevice->CreateCompatibleBitmap(pBackdrop, width, height);
}
if (pBackdrop->GetBuffer() == NULL) {
delete pBackdrop;
return NULL;
}
FX_BOOL bNeedDraw;
if (pBackdrop->HasAlpha()) {
bNeedDraw = !(m_pDevice->GetRenderCaps() & FXRC_ALPHA_OUTPUT);
} else {
bNeedDraw = !(m_pDevice->GetRenderCaps() & FXRC_GET_BITS);
}
if (!bNeedDraw) {
m_pDevice->GetDIBits(pBackdrop, left, top);
return pBackdrop;
}
CFX_AffineMatrix FinalMatrix = m_DeviceMatrix;
FinalMatrix.TranslateI(-left, -top);
FinalMatrix.Scale(scaleX, scaleY);
pBackdrop->Clear(pBackdrop->HasAlpha() ? 0 : 0xffffffff);
CFX_FxgeDevice device;
device.Attach(pBackdrop);
m_pContext->Render(&device, pObj, &m_Options, &FinalMatrix);
return pBackdrop;
}
void CPDF_RenderContext::GetBackground(CFX_DIBitmap* pBuffer, const CPDF_PageObject* pObj,
const CPDF_RenderOptions* pOptions, CFX_AffineMatrix* pFinalMatrix)
{
CFX_FxgeDevice device;
device.Attach(pBuffer);
if (m_pBackgroundDraw) {
m_pBackgroundDraw->OnDrawBackground(&device, pFinalMatrix);
} else {
FX_RECT rect(0, 0, device.GetWidth(), device.GetHeight());
device.FillRect(&rect, 0xffffffff);
}
Render(&device, pObj, pOptions, pFinalMatrix);
}
CPDF_GraphicStates* CPDF_RenderStatus::CloneObjStates(const CPDF_GraphicStates* pSrcStates, FX_BOOL bStroke)
{
if (!pSrcStates) {
return NULL;
}
CPDF_GraphicStates* pStates = FX_NEW CPDF_GraphicStates;
if (!pStates) {
return NULL;
}
pStates->CopyStates(*pSrcStates);
CPDF_Color* pObjColor = bStroke ? pSrcStates->m_ColorState.GetStrokeColor() :
pSrcStates->m_ColorState.GetFillColor();
if (!pObjColor->IsNull()) {
CPDF_ColorStateData* pColorData = pStates->m_ColorState.GetModify();
pColorData->m_FillRGB = bStroke ? pSrcStates->m_ColorState.GetObject()->m_StrokeRGB :
pSrcStates->m_ColorState.GetObject()->m_FillRGB;
pColorData->m_StrokeRGB = pColorData->m_FillRGB;
}
return pStates;
}
CPDF_RenderContext::CPDF_RenderContext()
{
}
void CPDF_RenderContext::Create(CPDF_Document* pDoc, CPDF_PageRenderCache* pPageCache,
CPDF_Dictionary* pPageResources, FX_BOOL bFirstLayer)
{
m_pBackgroundDraw = NULL;
m_pDocument = pDoc;
m_pPageResources = pPageResources;
m_pPageCache = pPageCache;
m_bFirstLayer = bFirstLayer;
}
void CPDF_RenderContext::Create(CPDF_Page* pPage, FX_BOOL bFirstLayer)
{
m_pBackgroundDraw = NULL;
m_pDocument = pPage->m_pDocument;
m_pPageResources = pPage->m_pPageResources;
m_pPageCache = pPage->GetRenderCache();
m_bFirstLayer = bFirstLayer;
}
CPDF_RenderContext::~CPDF_RenderContext()
{
}
void CPDF_RenderContext::Clear()
{
m_pDocument = NULL;
m_pPageResources = NULL;
m_pPageCache = NULL;
m_pBackgroundDraw = NULL;
m_bFirstLayer = TRUE;
m_ContentList.RemoveAll();
}
void CPDF_RenderContext::AppendObjectList(CPDF_PageObjects* pObjs, const CFX_AffineMatrix* pObject2Device)
{
_PDF_RenderItem* pItem = m_ContentList.AddSpace();
pItem->m_pObjectList = pObjs;
if (pObject2Device) {
pItem->m_Matrix = *pObject2Device;
} else {
pItem->m_Matrix.SetIdentity();
}
}
void CPDF_RenderContext::Render(CFX_RenderDevice* pDevice, const CPDF_RenderOptions* pOptions,
const CFX_AffineMatrix* pLastMatrix)
{
Render(pDevice, NULL, pOptions, pLastMatrix);
}
void CPDF_RenderContext::Render(CFX_RenderDevice* pDevice, const CPDF_PageObject* pStopObj,
const CPDF_RenderOptions* pOptions, const CFX_AffineMatrix* pLastMatrix)
{
int count = m_ContentList.GetSize();
for (int j = 0; j < count; j ++) {
pDevice->SaveState();
_PDF_RenderItem* pItem = m_ContentList.GetDataPtr(j);
if (pLastMatrix) {
CFX_AffineMatrix FinalMatrix = pItem->m_Matrix;
FinalMatrix.Concat(*pLastMatrix);
CPDF_RenderStatus status;
status.Initialize(0, this, pDevice, pLastMatrix, pStopObj, NULL, NULL, pOptions,
pItem->m_pObjectList->m_Transparency, FALSE, NULL);
status.RenderObjectList(pItem->m_pObjectList, &FinalMatrix);
#if !defined(_FPDFAPI_MINI_)
if (status.m_Options.m_Flags & RENDER_LIMITEDIMAGECACHE) {
m_pPageCache->CacheOptimization(status.m_Options.m_dwLimitCacheSize);
}
#endif
if (status.m_bStopped) {
pDevice->RestoreState();
break;
}
} else {
CPDF_RenderStatus status;
status.Initialize(0, this, pDevice, NULL, pStopObj, NULL, NULL, pOptions,
pItem->m_pObjectList->m_Transparency, FALSE, NULL);
status.RenderObjectList(pItem->m_pObjectList, &pItem->m_Matrix);
#if !defined(_FPDFAPI_MINI_)
if (status.m_Options.m_Flags & RENDER_LIMITEDIMAGECACHE) {
m_pPageCache->CacheOptimization(status.m_Options.m_dwLimitCacheSize);
}
#endif
if (status.m_bStopped) {
pDevice->RestoreState();
break;
}
}
pDevice->RestoreState();
}
}
void CPDF_RenderContext::DrawObjectList(CFX_RenderDevice* pDevice, CPDF_PageObjects* pObjs,
const CFX_AffineMatrix* pObject2Device, const CPDF_RenderOptions* pOptions)
{
AppendObjectList(pObjs, pObject2Device);
Render(pDevice, pOptions);
}
CPDF_ProgressiveRenderer::CPDF_ProgressiveRenderer()
{
m_pRenderer = NULL;
m_pContext = NULL;
m_pDevice = NULL;
m_Status = Ready;
}
CPDF_ProgressiveRenderer::~CPDF_ProgressiveRenderer()
{
Clear();
}
void CPDF_ProgressiveRenderer::Clear()
{
if (m_pRenderer) {
delete m_pRenderer;
m_pDevice->RestoreState();
m_pRenderer = NULL;
}
m_Status = Ready;
}
void CPDF_ProgressiveRenderer::Start(CPDF_RenderContext* pContext, CFX_RenderDevice* pDevice,
const CPDF_RenderOptions* pOptions, IFX_Pause* pPause, FX_BOOL bDropObjects)
{
if (m_Status != Ready) {
m_Status = Failed;
return;
}
m_pContext = pContext;
m_pDevice = pDevice;
m_pOptions = pOptions;
m_bDropObjects = bDropObjects;
if (pContext == NULL || pDevice == NULL) {
m_Status = Failed;
return;
}
m_Status = ToBeContinued;
m_ObjectPos = NULL;
m_LayerIndex = 0;
m_ObjectIndex = 0;
m_PrevLastPos = NULL;
Continue(pPause);
}
#ifdef _FPDFAPI_MINI_
#define RENDER_STEP_LIMIT 20
#else
#define RENDER_STEP_LIMIT 100
#endif
void CPDF_ProgressiveRenderer::Continue(IFX_Pause* pPause)
{
if (m_Status != ToBeContinued) {
return;
}
FX_DWORD nLayers = m_pContext->m_ContentList.GetSize();
for (; m_LayerIndex < nLayers; m_LayerIndex ++) {
_PDF_RenderItem* pItem = m_pContext->m_ContentList.GetDataPtr(m_LayerIndex);
FX_POSITION LastPos = pItem->m_pObjectList->GetLastObjectPosition();
if (m_ObjectPos == NULL) {
if (LastPos == m_PrevLastPos) {
if (!pItem->m_pObjectList->IsParsed()) {
pItem->m_pObjectList->ContinueParse(pPause);
if (!pItem->m_pObjectList->IsParsed()) {
return;
}
LastPos = pItem->m_pObjectList->GetLastObjectPosition();
}
}
if (LastPos == m_PrevLastPos) {
if (m_pRenderer) {
delete m_pRenderer;
m_pRenderer = NULL;
m_pDevice->RestoreState();
m_ObjectPos = NULL;
m_PrevLastPos = NULL;
}
continue;
}
if (m_PrevLastPos) {
m_ObjectPos = m_PrevLastPos;
pItem->m_pObjectList->GetNextObject(m_ObjectPos);
} else {
m_ObjectPos = pItem->m_pObjectList->GetFirstObjectPosition();
}
m_PrevLastPos = LastPos;
}
if (m_pRenderer == NULL) {
m_ObjectPos = pItem->m_pObjectList->GetFirstObjectPosition();
m_ObjectIndex = 0;
m_pRenderer = FX_NEW CPDF_RenderStatus();
m_pRenderer->Initialize(0, m_pContext, m_pDevice, NULL, NULL, NULL, NULL,
m_pOptions, pItem->m_pObjectList->m_Transparency, m_bDropObjects, NULL);
m_pDevice->SaveState();
m_ClipRect = m_pDevice->GetClipBox();
CFX_AffineMatrix device2object;
device2object.SetReverse(pItem->m_Matrix);
device2object.TransformRect(m_ClipRect);
}
int objs_to_go = CPDF_ModuleMgr::Get()->GetRenderModule()->GetConfig()->m_RenderStepLimit;
while (m_ObjectPos) {
CPDF_PageObject* pCurObj = pItem->m_pObjectList->GetObjectAt(m_ObjectPos);
if (pCurObj && pCurObj->m_Left <= m_ClipRect.right && pCurObj->m_Right >= m_ClipRect.left &&
pCurObj->m_Bottom <= m_ClipRect.top && pCurObj->m_Top >= m_ClipRect.bottom) {
if (m_pRenderer->ContinueSingleObject(pCurObj, &pItem->m_Matrix, pPause)) {
return;
}
#if !defined(_FPDFAPI_MINI_)
if (pCurObj->m_Type == PDFPAGE_IMAGE && m_pRenderer->m_Options.m_Flags & RENDER_LIMITEDIMAGECACHE) {
m_pContext->GetPageCache()->CacheOptimization(m_pRenderer->m_Options.m_dwLimitCacheSize);
}
#endif
if (pCurObj->m_Type == PDFPAGE_FORM || pCurObj->m_Type == PDFPAGE_SHADING) {
objs_to_go = 0;
} else {
objs_to_go --;
}
}
m_ObjectIndex ++;
pItem->m_pObjectList->GetNextObject(m_ObjectPos);
if (objs_to_go == 0) {
if (pPause && pPause->NeedToPauseNow()) {
return;
}
objs_to_go = CPDF_ModuleMgr::Get()->GetRenderModule()->GetConfig()->m_RenderStepLimit;
}
}
if (!pItem->m_pObjectList->IsParsed()) {
return;
}
delete m_pRenderer;
m_pRenderer = NULL;
m_pDevice->RestoreState();
m_ObjectPos = NULL;
m_PrevLastPos = NULL;
if (pPause && pPause->NeedToPauseNow()) {
m_LayerIndex++;
return;
}
}
m_Status = Done;
}
int CPDF_ProgressiveRenderer::EstimateProgress()
{
if (!m_pContext) {
return 0;
}
FX_DWORD nLayers = m_pContext->m_ContentList.GetSize();
int nTotal = 0, nRendered = 0;
for (FX_DWORD layer = 0; layer < nLayers; layer ++) {
_PDF_RenderItem* pItem = m_pContext->m_ContentList.GetDataPtr(layer);
int nObjs = pItem->m_pObjectList->CountObjects();
if (layer == m_LayerIndex) {
nRendered += m_ObjectIndex;
} else if (layer < m_LayerIndex) {
nRendered += nObjs;
}
nTotal += nObjs;
}
if (nTotal == 0) {
return 0;
}
return 100 * nRendered / nTotal;
}
CPDF_TransferFunc* CPDF_DocRenderData::GetTransferFunc(CPDF_Object* pObj)
{
if (pObj == NULL) {
return NULL;
}
CPDF_CountedObject<CPDF_TransferFunc*>* pTransferCounter;
if (!m_TransferFuncMap.Lookup(pObj, pTransferCounter)) {
CPDF_TransferFunc* pTransfer = NULL;
CPDF_Function* pFuncs[3] = {NULL, NULL, NULL};
FX_BOOL bUniTransfer = TRUE;
int i;
FX_BOOL bIdentity = TRUE;
if (pObj->GetType() == PDFOBJ_ARRAY) {
bUniTransfer = FALSE;
CPDF_Array* pArray = (CPDF_Array*)pObj;
if (pArray->GetCount() < 3) {
return NULL;
}
for (FX_DWORD i = 0; i < 3; i ++) {
pFuncs[2 - i] = CPDF_Function::Load(pArray->GetElementValue(i));
if (pFuncs[2 - i] == NULL) {
return NULL;
}
}
} else {
pFuncs[0] = CPDF_Function::Load(pObj);
if (pFuncs[0] == NULL) {
return NULL;
}
}
pTransfer = FX_NEW CPDF_TransferFunc;
pTransfer->m_pPDFDoc = m_pPDFDoc;
pTransferCounter = FX_NEW CPDF_CountedObject<CPDF_TransferFunc*>;
pTransferCounter->m_nCount = 1;
pTransferCounter->m_Obj = pTransfer;
m_TransferFuncMap.SetAt(pObj, pTransferCounter);
static const int kMaxOutputs = 16;
FX_FLOAT output[kMaxOutputs];
FXSYS_memset32(output, 0, sizeof(output));
FX_FLOAT input;
int noutput;
for (int v = 0; v < 256; v ++) {
input = (FX_FLOAT)v / 255.0f;
if (bUniTransfer) {
if (pFuncs[0] && pFuncs[0]->CountOutputs() <= kMaxOutputs) {
pFuncs[0]->Call(&input, 1, output, noutput);
}
int o = FXSYS_round(output[0] * 255);
if (o != v) {
bIdentity = FALSE;
}
for (i = 0; i < 3; i ++) {
pTransfer->m_Samples[i * 256 + v] = o;
}
} else
for (i = 0; i < 3; i ++) {
if (pFuncs[i] && pFuncs[i]->CountOutputs() <= kMaxOutputs) {
pFuncs[i]->Call(&input, 1, output, noutput);
int o = FXSYS_round(output[0] * 255);
if (o != v) {
bIdentity = FALSE;
}
pTransfer->m_Samples[i * 256 + v] = o;
} else {
pTransfer->m_Samples[i * 256 + v] = v;
}
}
}
for (i = 0; i < 3; i ++)
if (pFuncs[i]) {
delete pFuncs[i];
}
pTransfer->m_bIdentity = bIdentity;
}
pTransferCounter->m_nCount++;
return pTransferCounter->m_Obj;
}
void CPDF_DocRenderData::ReleaseTransferFunc(CPDF_Object* pObj)
{
CPDF_CountedObject<CPDF_TransferFunc*>* pTransferCounter;
if (!m_TransferFuncMap.Lookup(pObj, pTransferCounter)) {
return;
}
pTransferCounter->m_nCount--;
}
CPDF_RenderConfig::CPDF_RenderConfig()
{
m_HalftoneLimit = 0;
#ifdef _FPDFAPI_MINI_
m_RenderStepLimit = 20;
#else
m_RenderStepLimit = 100;
#endif
}
CPDF_RenderConfig::~CPDF_RenderConfig()
{
}
CPDF_DeviceBuffer::CPDF_DeviceBuffer()
{
m_pBitmap = NULL;
m_pDevice = NULL;
m_pContext = NULL;
m_pObject = NULL;
}
CPDF_DeviceBuffer::~CPDF_DeviceBuffer()
{
if (m_pBitmap) {
delete m_pBitmap;
}
}
FX_BOOL CPDF_DeviceBuffer::Initialize(CPDF_RenderContext* pContext, CFX_RenderDevice* pDevice, FX_RECT* pRect,
const CPDF_PageObject* pObj, int max_dpi)
{
m_pDevice = pDevice;
m_pContext = pContext;
m_Rect = *pRect;
m_pObject = pObj;
m_Matrix.TranslateI(-pRect->left, -pRect->top);
#if _FXM_PLATFORM_ != _FXM_PLATFORM_APPLE_
int horz_size = pDevice->GetDeviceCaps(FXDC_HORZ_SIZE);
int vert_size = pDevice->GetDeviceCaps(FXDC_VERT_SIZE);
if (horz_size && vert_size && max_dpi) {
int dpih = pDevice->GetDeviceCaps(FXDC_PIXEL_WIDTH) * 254 / (horz_size * 10);
int dpiv = pDevice->GetDeviceCaps(FXDC_PIXEL_HEIGHT) * 254 / (vert_size * 10);
if (dpih > max_dpi) {
m_Matrix.Scale((FX_FLOAT)(max_dpi) / dpih, 1.0f);
}
if (dpiv > max_dpi) {
m_Matrix.Scale(1.0f, (FX_FLOAT)(max_dpi) / (FX_FLOAT)dpiv);
}
}
#ifdef _FPDFAPI_MINI_
m_Matrix.Scale(0.5f, 0.5f);
#endif
#endif
CFX_Matrix ctm = m_pDevice->GetCTM();
FX_FLOAT fScaleX = FXSYS_fabs(ctm.a);
FX_FLOAT fScaleY = FXSYS_fabs(ctm.d);
m_Matrix.Concat(fScaleX, 0, 0, fScaleY, 0, 0);
CFX_FloatRect rect(*pRect);
m_Matrix.TransformRect(rect);
FX_RECT bitmap_rect = rect.GetOutterRect();
m_pBitmap = FX_NEW CFX_DIBitmap;
m_pBitmap->Create(bitmap_rect.Width(), bitmap_rect.Height(), FXDIB_Argb);
return TRUE;
}
void CPDF_DeviceBuffer::OutputToDevice()
{
if (m_pDevice->GetDeviceCaps(FXDC_RENDER_CAPS) & FXRC_GET_BITS) {
if (m_Matrix.a == 1.0f && m_Matrix.d == 1.0f) {
m_pDevice->SetDIBits(m_pBitmap, m_Rect.left, m_Rect.top);
} else {
m_pDevice->StretchDIBits(m_pBitmap, m_Rect.left, m_Rect.top, m_Rect.Width(), m_Rect.Height());
}
} else {
#if !defined(_FPDFAPI_MINI_) || defined(_FXCORE_FEATURE_ALL_)
CFX_DIBitmap buffer;
m_pDevice->CreateCompatibleBitmap(&buffer, m_pBitmap->GetWidth(), m_pBitmap->GetHeight());
m_pContext->GetBackground(&buffer, m_pObject, NULL, &m_Matrix);
buffer.CompositeBitmap(0, 0, buffer.GetWidth(), buffer.GetHeight(), m_pBitmap, 0, 0);
m_pDevice->StretchDIBits(&buffer, m_Rect.left, m_Rect.top, m_Rect.Width(), m_Rect.Height());
#endif
}
}
CPDF_ScaledRenderBuffer::CPDF_ScaledRenderBuffer()
{
m_pBitmapDevice = NULL;
}
CPDF_ScaledRenderBuffer::~CPDF_ScaledRenderBuffer()
{
if (m_pBitmapDevice) {
delete m_pBitmapDevice;
}
}
#ifndef _FPDFAPI_MINI_
#define _FPDFAPI_IMAGESIZE_LIMIT_ (30 * 1024 * 1024)
#else
#define _FPDFAPI_IMAGESIZE_LIMIT_ (10 * 1024 * 1024)
#endif
FX_BOOL CPDF_ScaledRenderBuffer::Initialize(CPDF_RenderContext* pContext, CFX_RenderDevice* pDevice, FX_RECT* pRect,
const CPDF_PageObject* pObj, const CPDF_RenderOptions *pOptions, int max_dpi)
{
FXSYS_assert(pRect != NULL);
m_pDevice = pDevice;
if (m_pDevice->GetDeviceCaps(FXDC_RENDER_CAPS) & FXRC_GET_BITS) {
return TRUE;
}
m_pContext = pContext;
m_Rect = *pRect;
m_pObject = pObj;
m_Matrix.TranslateI(-pRect->left, -pRect->top);
int horz_size = pDevice->GetDeviceCaps(FXDC_HORZ_SIZE);
int vert_size = pDevice->GetDeviceCaps(FXDC_VERT_SIZE);
if (horz_size && vert_size && max_dpi) {
int dpih = pDevice->GetDeviceCaps(FXDC_PIXEL_WIDTH) * 254 / (horz_size * 10);
int dpiv = pDevice->GetDeviceCaps(FXDC_PIXEL_HEIGHT) * 254 / (vert_size * 10);
if (dpih > max_dpi) {
m_Matrix.Scale((FX_FLOAT)(max_dpi) / dpih, 1.0f);
}
if (dpiv > max_dpi) {
m_Matrix.Scale(1.0f, (FX_FLOAT)(max_dpi) / (FX_FLOAT)dpiv);
}
}
m_pBitmapDevice = FX_NEW CFX_FxgeDevice;
FXDIB_Format dibFormat = FXDIB_Rgb;
FX_INT32 bpp = 24;
if (m_pDevice->GetDeviceCaps(FXDC_RENDER_CAPS) & FXRC_ALPHA_OUTPUT) {
dibFormat = FXDIB_Argb;
bpp = 32;
}
CFX_FloatRect rect;
FX_INT32 iWidth, iHeight, iPitch;
while (1) {
rect = *pRect;
m_Matrix.TransformRect(rect);
FX_RECT bitmap_rect = rect.GetOutterRect();
iWidth = bitmap_rect.Width();
iHeight = bitmap_rect.Height();
iPitch = (iWidth * bpp + 31) / 32 * 4;
if (iWidth * iHeight < 1) {
return FALSE;
}
if (iPitch * iHeight <= _FPDFAPI_IMAGESIZE_LIMIT_ &&
m_pBitmapDevice->Create(iWidth, iHeight, dibFormat)) {
break;
}
m_Matrix.Scale(0.5f, 0.5f);
}
#if !defined(_FPDFAPI_MINI_) || defined(_FXCORE_FEATURE_ALL_)
m_pContext->GetBackground(m_pBitmapDevice->GetBitmap(), m_pObject, pOptions, &m_Matrix);
#endif
return TRUE;
}
void CPDF_ScaledRenderBuffer::OutputToDevice()
{
if (m_pBitmapDevice) {
m_pDevice->StretchDIBits(m_pBitmapDevice->GetBitmap(), m_Rect.left, m_Rect.top, m_Rect.Width(), m_Rect.Height());
}
}
FX_BOOL IPDF_OCContext::CheckObjectVisible(const CPDF_PageObject* pObj)
{
const CPDF_ContentMarkData* pData = pObj->m_ContentMark;
int nItems = pData->CountItems();
for (int i = 0; i < nItems; i ++) {
CPDF_ContentMarkItem& item = pData->GetItem(i);
if (item.GetName() == FX_BSTRC("OC") && item.GetParamType() == CPDF_ContentMarkItem::PropertiesDict) {
CPDF_Dictionary* pOCG = (CPDF_Dictionary*)item.GetParam();
if (!CheckOCGVisible(pOCG)) {
return FALSE;
}
}
}
return TRUE;
}
| 54,166 | 19,762 |
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */
#include <sstream>
#include <limits>
#include "ifcpp/model/AttributeObject.h"
#include "ifcpp/model/BuildingException.h"
#include "ifcpp/model/BuildingGuid.h"
#include "ifcpp/reader/ReaderUtil.h"
#include "ifcpp/writer/WriterUtil.h"
#include "ifcpp/IFC4/include/IfcBoundaryCurve.h"
#include "ifcpp/IFC4/include/IfcCompositeCurveSegment.h"
#include "ifcpp/IFC4/include/IfcLogical.h"
#include "ifcpp/IFC4/include/IfcPresentationLayerAssignment.h"
#include "ifcpp/IFC4/include/IfcStyledItem.h"
// ENTITY IfcBoundaryCurve
IfcBoundaryCurve::IfcBoundaryCurve() {}
IfcBoundaryCurve::IfcBoundaryCurve( int id ) { m_entity_id = id; }
IfcBoundaryCurve::~IfcBoundaryCurve() {}
shared_ptr<BuildingObject> IfcBoundaryCurve::getDeepCopy( BuildingCopyOptions& options )
{
shared_ptr<IfcBoundaryCurve> copy_self( new IfcBoundaryCurve() );
for( size_t ii=0; ii<m_Segments.size(); ++ii )
{
auto item_ii = m_Segments[ii];
if( item_ii )
{
copy_self->m_Segments.push_back( dynamic_pointer_cast<IfcCompositeCurveSegment>(item_ii->getDeepCopy(options) ) );
}
}
if( m_SelfIntersect ) { copy_self->m_SelfIntersect = dynamic_pointer_cast<IfcLogical>( m_SelfIntersect->getDeepCopy(options) ); }
return copy_self;
}
void IfcBoundaryCurve::getStepLine( std::stringstream& stream ) const
{
stream << "#" << m_entity_id << "= IFCBOUNDARYCURVE" << "(";
writeEntityList( stream, m_Segments );
stream << ",";
if( m_SelfIntersect ) { m_SelfIntersect->getStepParameter( stream ); } else { stream << "$"; }
stream << ");";
}
void IfcBoundaryCurve::getStepParameter( std::stringstream& stream, bool ) const { stream << "#" << m_entity_id; }
const std::wstring IfcBoundaryCurve::toString() const { return L"IfcBoundaryCurve"; }
void IfcBoundaryCurve::readStepArguments( const std::vector<std::wstring>& args, const std::map<int,shared_ptr<BuildingEntity> >& map )
{
const size_t num_args = args.size();
if( num_args != 2 ){ std::stringstream err; err << "Wrong parameter count for entity IfcBoundaryCurve, expecting 2, having " << num_args << ". Entity ID: " << m_entity_id << std::endl; throw BuildingException( err.str().c_str() ); }
readEntityReferenceList( args[0], m_Segments, map );
m_SelfIntersect = IfcLogical::createObjectFromSTEP( args[1], map );
}
void IfcBoundaryCurve::getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) const
{
IfcCompositeCurveOnSurface::getAttributes( vec_attributes );
}
void IfcBoundaryCurve::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes_inverse ) const
{
IfcCompositeCurveOnSurface::getAttributesInverse( vec_attributes_inverse );
}
void IfcBoundaryCurve::setInverseCounterparts( shared_ptr<BuildingEntity> ptr_self_entity )
{
IfcCompositeCurveOnSurface::setInverseCounterparts( ptr_self_entity );
}
void IfcBoundaryCurve::unlinkFromInverseCounterparts()
{
IfcCompositeCurveOnSurface::unlinkFromInverseCounterparts();
}
| 3,091 | 1,123 |
#include "shm_sem.h"
#include <errno.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <iostream>
const std::string ShmSemaphore::sLockSemaphoreName = "/semaphoreInit";
ShmSemaphore::ShmSemaphore(const std::string& sName)
: name_(sName), ptr_(nullptr), shm_id_(-1), sem_id_(nullptr), size_(0) {
/**
* Semaphore open
*/
sem_id_ = sem_open(sLockSemaphoreName.c_str(), O_CREAT, S_IRUSR | S_IWUSR, 1);
}
bool ShmSemaphore::Create(size_t nSize, int mode /*= READ_WRITE*/) {
size_ = nSize;
shm_id_ = shm_open(name_.c_str(), O_CREAT | mode, 0666);
if (shm_id_ < 0) {
switch (errno) {
case EACCES:
throw ShmException("Permission Exception ");
break;
case EEXIST:
throw ShmException(
"Shared memory object specified by name already exists.");
break;
case EINVAL:
throw ShmException("Invalid shared memory name passed.");
break;
case EMFILE:
throw ShmException(
"The process already has the maximum number of files open.");
break;
case ENAMETOOLONG:
throw ShmException("The length of name exceeds PATH_MAX.");
break;
case ENFILE:
throw ShmException(
"The limit on the total number of files open on the system has "
"been reached");
break;
default:
throw ShmException(
"Invalid exception occurred in shared memory creation");
break;
}
}
/* adjusting mapped file size (make room for the whole segment to map) --
* ftruncate() */
ftruncate(shm_id_, size_);
return true;
}
bool ShmSemaphore::Attach(int mode /*= A_READ | A_WRITE*/) {
/* requesting the shared segment -- mmap() */
ptr_ = mmap(NULL, size_, mode, MAP_SHARED, shm_id_, 0);
if (ptr_ == nullptr) {
throw ShmException("Exception in attaching the shared memory region");
}
return true;
}
bool ShmSemaphore::Detach() { munmap(ptr_, size_); }
bool ShmSemaphore::Lock() { sem_wait(sem_id_); }
bool ShmSemaphore::Trylock() { return (sem_trywait(sem_id_) == 0); }
bool ShmSemaphore::Unlock() { return (sem_post(sem_id_) == 0); }
bool ShmSemaphore::UnlockSingle() {
int sem_val;
if (sem_getvalue(sem_id_, &sem_val) == 0) {
if (sem_val == 0) {
return (sem_post(sem_id_) == 0);
} else {
return false;
}
}
return false;
}
ShmSemaphore::~ShmSemaphore() { Clear(); }
void ShmSemaphore::Clear() {
if (shm_id_ != -1) {
if (shm_unlink(name_.c_str()) < 0) {
perror("shm_unlink");
}
}
/**
* Semaphore unlink: Remove a named semaphore from the system.
*/
if (sem_id_ != NULL) {
/**
* Semaphore Close: Close a named semaphore
*/
if (sem_close(sem_id_) < 0) {
perror("sem_close");
}
/**
* Semaphore unlink: Remove a named semaphore from the system.
*/
if (sem_unlink(sLockSemaphoreName.c_str()) < 0) {
perror("sem_unlink");
}
}
}
ShmException::ShmException(const std::string& message,
bool bSysMsg /*= false*/) throw() {}
ShmException::~ShmException() throw() {} | 3,191 | 1,152 |
/*
Copyright 2005-2014 Intel Corporation. All Rights Reserved.
This file is part of Threading Building Blocks. Threading Building Blocks is free software;
you can redistribute it and/or modify it under the terms of the GNU General Public License
version 2 as published by the Free Software Foundation. Threading Building Blocks 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 Threading Building Blocks; if not, write to the
Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
As a special exception, you may use this file as part of a free software library without
restriction. Specifically, if other files instantiate templates or use macros or inline
functions from this file, or you compile this file and link it with other files to produce
an executable, this file does not by itself cause the resulting executable to be covered
by the GNU General Public License. This exception does not however invalidate any other
reasons why the executable file might be covered by the GNU General Public License.
*/
#include "tbbmalloc_internal.h"
#include <new> /* for placement new */
namespace rml {
namespace internal {
/********* backreferences ***********************/
/* Each slab block and each large memory object header contains BackRefIdx
* that points out in some BackRefBlock which points back to this block or header.
*/
struct BackRefBlock : public BlockI {
BackRefBlock *nextForUse; // the next in the chain of blocks with free items
FreeObject *bumpPtr; // bump pointer moves from the end to the beginning of the block
FreeObject *freeList;
// list of all blocks that were allocated from raw mem (i.e., not from backend)
BackRefBlock *nextRawMemBlock;
int allocatedCount; // the number of objects allocated
int myNum; // the index in the master
MallocMutex blockMutex;
// true if this block has been added to the listForUse chain,
// modifications protected by masterMutex
bool addedToForUse;
BackRefBlock(const BackRefBlock *blockToUse, int num) :
nextForUse(NULL), bumpPtr((FreeObject*)((uintptr_t)blockToUse + slabSize - sizeof(void*))),
freeList(NULL), nextRawMemBlock(NULL), allocatedCount(0), myNum(num),
addedToForUse(false) {
memset(&blockMutex, 0, sizeof(MallocMutex));
// index in BackRefMaster must fit to uint16_t
MALLOC_ASSERT(!(myNum >> 16), ASSERT_TEXT);
}
// clean all but header
void zeroSet() { memset(this+1, 0, BackRefBlock::bytes-sizeof(BackRefBlock)); }
static const int bytes = slabSize;
};
// max number of backreference pointers in slab block
static const int BR_MAX_CNT = (BackRefBlock::bytes-sizeof(BackRefBlock))/sizeof(void*);
struct BackRefMaster {
/* A slab block can hold up to ~2K back pointers to slab blocks or large objects,
* so it can address at least 32MB. The array of 64KB holds 8K pointers
* to such blocks, addressing ~256 GB.
*/
static const size_t bytes = 64*1024;
static const int dataSz;
/* space is reserved for master table and 4 leaves
taking into account VirtualAlloc allocation granularity */
static const int leaves = 4;
static const size_t masterSize = BackRefMaster::bytes+leaves*BackRefBlock::bytes;
// take into account VirtualAlloc 64KB granularity
static const size_t blockSpaceSize = 64*1024;
Backend *backend;
BackRefBlock *active; // if defined, use it for allocations
BackRefBlock *listForUse; // the chain of data blocks with free items
BackRefBlock *allRawMemBlocks;
intptr_t lastUsed; // index of the last used block
bool rawMemUsed;
MallocMutex requestNewSpaceMutex;
BackRefBlock *backRefBl[1]; // the real size of the array is dataSz
BackRefBlock *findFreeBlock();
void addToForUseList(BackRefBlock *bl);
void initEmptyBackRefBlock(BackRefBlock *newBl);
bool requestNewSpace();
};
const int BackRefMaster::dataSz
= 1+(BackRefMaster::bytes-sizeof(BackRefMaster))/sizeof(BackRefBlock*);
static MallocMutex masterMutex;
static BackRefMaster *backRefMaster;
bool initBackRefMaster(Backend *backend)
{
bool rawMemUsed;
BackRefMaster *master =
(BackRefMaster*)backend->getBackRefSpace(BackRefMaster::masterSize,
&rawMemUsed);
if (! master)
return false;
master->backend = backend;
master->listForUse = master->allRawMemBlocks = NULL;
master->rawMemUsed = rawMemUsed;
master->lastUsed = -1;
memset(&master->requestNewSpaceMutex, 0, sizeof(MallocMutex));
for (int i=0; i<BackRefMaster::leaves; i++) {
BackRefBlock *bl = (BackRefBlock*)((uintptr_t)master + BackRefMaster::bytes + i*BackRefBlock::bytes);
bl->zeroSet();
master->initEmptyBackRefBlock(bl);
if (i)
master->addToForUseList(bl);
else // active leaf is not needed in listForUse
master->active = bl;
}
// backRefMaster is read in getBackRef, so publish it in consistent state
FencedStore((intptr_t&)backRefMaster, (intptr_t)master);
return true;
}
void destroyBackRefMaster(Backend *backend)
{
if (backRefMaster) { // Is initBackRefMaster() called?
for (BackRefBlock *curr=backRefMaster->allRawMemBlocks; curr; ) {
BackRefBlock *next = curr->nextRawMemBlock;
// allRawMemBlocks list is only for raw mem blocks
backend->putBackRefSpace(curr, BackRefMaster::blockSpaceSize,
/*rawMemUsed=*/true);
curr = next;
}
backend->putBackRefSpace(backRefMaster, BackRefMaster::masterSize,
backRefMaster->rawMemUsed);
}
}
void BackRefMaster::addToForUseList(BackRefBlock *bl)
{
bl->nextForUse = listForUse;
listForUse = bl;
bl->addedToForUse = true;
}
void BackRefMaster::initEmptyBackRefBlock(BackRefBlock *newBl)
{
intptr_t nextLU = lastUsed+1;
new (newBl) BackRefBlock(newBl, nextLU);
backRefBl[nextLU] = newBl;
// lastUsed is read in getBackRef, and access to backRefBl[lastUsed]
// is possible only after checking backref against current lastUsed
FencedStore(lastUsed, nextLU);
}
bool BackRefMaster::requestNewSpace()
{
bool rawMemUsed;
MALLOC_STATIC_ASSERT(!(blockSpaceSize % BackRefBlock::bytes),
"Must request space for whole number of blocks.");
// only one thread at a time may add blocks
MallocMutex::scoped_lock newSpaceLock(requestNewSpaceMutex);
if (listForUse) // double check that only one block is available
return true;
BackRefBlock *newBl =
(BackRefBlock*)backend->getBackRefSpace(blockSpaceSize, &rawMemUsed);
if (!newBl) return false;
// touch a page for the 1st time without taking masterMutex ...
for (BackRefBlock *bl = newBl; (uintptr_t)bl < (uintptr_t)newBl + blockSpaceSize;
bl = (BackRefBlock*)((uintptr_t)bl + BackRefBlock::bytes))
bl->zeroSet();
MallocMutex::scoped_lock lock(masterMutex); // ... and share under lock
// use the first block in the batch to maintain the list of "raw" memory
// to be released at shutdown
if (rawMemUsed) {
newBl->nextRawMemBlock = backRefMaster->allRawMemBlocks;
backRefMaster->allRawMemBlocks = newBl;
}
for (BackRefBlock *bl = newBl; (uintptr_t)bl < (uintptr_t)newBl + blockSpaceSize;
bl = (BackRefBlock*)((uintptr_t)bl + BackRefBlock::bytes)) {
initEmptyBackRefBlock(bl);
if (active->allocatedCount == BR_MAX_CNT)
active = bl; // active leaf is not needed in listForUse
else
addToForUseList(bl);
}
return true;
}
BackRefBlock *BackRefMaster::findFreeBlock()
{
if (active->allocatedCount < BR_MAX_CNT)
return active;
if (listForUse) { // use released list
MallocMutex::scoped_lock lock(masterMutex);
if (active->allocatedCount == BR_MAX_CNT && listForUse) {
active = listForUse;
listForUse = listForUse->nextForUse;
MALLOC_ASSERT(active->addedToForUse, ASSERT_TEXT);
active->addedToForUse = false;
}
} else if (lastUsed-1 < backRefMaster->dataSz) { // allocate new data node
if (!requestNewSpace()) return NULL;
} else // no free space in BackRefMaster, give up
return NULL;
return active;
}
void *getBackRef(BackRefIdx backRefIdx)
{
// !backRefMaster means no initialization done, so it can't be valid memory
// see addEmptyBackRefBlock for fences around lastUsed
if (!FencedLoad((intptr_t&)backRefMaster)
|| backRefIdx.getMaster() > FencedLoad(backRefMaster->lastUsed)
|| backRefIdx.getOffset() >= BR_MAX_CNT)
return NULL;
return *(void**)((uintptr_t)backRefMaster->backRefBl[backRefIdx.getMaster()]
+ sizeof(BackRefBlock)+backRefIdx.getOffset()*sizeof(void*));
}
void setBackRef(BackRefIdx backRefIdx, void *newPtr)
{
MALLOC_ASSERT(backRefIdx.getMaster()<=backRefMaster->lastUsed && backRefIdx.getOffset()<BR_MAX_CNT,
ASSERT_TEXT);
*(void**)((uintptr_t)backRefMaster->backRefBl[backRefIdx.getMaster()]
+ sizeof(BackRefBlock) + backRefIdx.getOffset()*sizeof(void*)) = newPtr;
}
BackRefIdx BackRefIdx::newBackRef(bool largeObj)
{
BackRefBlock *blockToUse;
void **toUse;
BackRefIdx res;
bool lastBlockFirstUsed = false;
do {
MALLOC_ASSERT(backRefMaster, ASSERT_TEXT);
blockToUse = backRefMaster->findFreeBlock();
if (!blockToUse)
return BackRefIdx();
toUse = NULL;
{ // the block is locked to find a reference
MallocMutex::scoped_lock lock(blockToUse->blockMutex);
if (blockToUse->freeList) {
toUse = (void**)blockToUse->freeList;
blockToUse->freeList = blockToUse->freeList->next;
MALLOC_ASSERT(!blockToUse->freeList ||
((uintptr_t)blockToUse->freeList>=(uintptr_t)blockToUse
&& (uintptr_t)blockToUse->freeList <
(uintptr_t)blockToUse + slabSize), ASSERT_TEXT);
} else if (blockToUse->allocatedCount < BR_MAX_CNT) {
toUse = (void**)blockToUse->bumpPtr;
blockToUse->bumpPtr =
(FreeObject*)((uintptr_t)blockToUse->bumpPtr - sizeof(void*));
if (blockToUse->allocatedCount == BR_MAX_CNT-1) {
MALLOC_ASSERT((uintptr_t)blockToUse->bumpPtr
< (uintptr_t)blockToUse+sizeof(BackRefBlock),
ASSERT_TEXT);
blockToUse->bumpPtr = NULL;
}
}
if (toUse) {
if (!blockToUse->allocatedCount && !backRefMaster->listForUse)
lastBlockFirstUsed = true;
blockToUse->allocatedCount++;
}
} // end of lock scope
} while (!toUse);
// The first thread that uses the last block requests new space in advance;
// possible failures are ignored.
if (lastBlockFirstUsed)
backRefMaster->requestNewSpace();
res.master = blockToUse->myNum;
uintptr_t offset =
((uintptr_t)toUse - ((uintptr_t)blockToUse + sizeof(BackRefBlock)))/sizeof(void*);
// Is offset too big?
MALLOC_ASSERT(!(offset >> 15), ASSERT_TEXT);
res.offset = offset;
if (largeObj) res.largeObj = largeObj;
return res;
}
void removeBackRef(BackRefIdx backRefIdx)
{
MALLOC_ASSERT(!backRefIdx.isInvalid(), ASSERT_TEXT);
MALLOC_ASSERT(backRefIdx.getMaster()<=backRefMaster->lastUsed
&& backRefIdx.getOffset()<BR_MAX_CNT, ASSERT_TEXT);
BackRefBlock *currBlock = backRefMaster->backRefBl[backRefIdx.getMaster()];
FreeObject *freeObj = (FreeObject*)((uintptr_t)currBlock + sizeof(BackRefBlock)
+ backRefIdx.getOffset()*sizeof(void*));
MALLOC_ASSERT(((uintptr_t)freeObj>(uintptr_t)currBlock &&
(uintptr_t)freeObj<(uintptr_t)currBlock + slabSize), ASSERT_TEXT);
{
MallocMutex::scoped_lock lock(currBlock->blockMutex);
freeObj->next = currBlock->freeList;
MALLOC_ASSERT(!freeObj->next ||
((uintptr_t)freeObj->next > (uintptr_t)currBlock
&& (uintptr_t)freeObj->next <
(uintptr_t)currBlock + slabSize), ASSERT_TEXT);
currBlock->freeList = freeObj;
currBlock->allocatedCount--;
}
// TODO: do we need double-check here?
if (!currBlock->addedToForUse && currBlock!=backRefMaster->active) {
MallocMutex::scoped_lock lock(masterMutex);
if (!currBlock->addedToForUse && currBlock!=backRefMaster->active)
backRefMaster->addToForUseList(currBlock);
}
}
/********* End of backreferences ***********************/
} // namespace internal
} // namespace rml
| 13,543 | 4,125 |
#define EIGEN_USE_THREADS
#include "tensorflow/core/kernels/training_ops.h"
#include "tensorflow/core/framework/op_kernel.h"
namespace tensorflow {
typedef Eigen::ThreadPoolDevice CPUDevice;
typedef Eigen::GpuDevice GPUDevice;
namespace functor {
static inline bool DoInline(int64 size) { return size <= (256ll << 10); }
template <typename T>
struct ApplyGradientDescent<CPUDevice, T> {
void operator()(const CPUDevice& d, typename TTypes<T>::Flat var,
typename TTypes<T>::ConstScalar lr,
typename TTypes<T>::ConstFlat grad) {
if (DoInline(var.size())) {
var -= grad * lr();
} else {
var.device(d) -= grad * lr();
}
}
};
template <typename T>
struct ApplyAdagrad<CPUDevice, T> {
void operator()(const CPUDevice& d, typename TTypes<T>::Flat var,
typename TTypes<T>::Flat accum,
typename TTypes<T>::ConstScalar lr,
typename TTypes<T>::ConstFlat grad) {
if (DoInline(var.size())) {
accum += grad.square();
var -= grad * lr() * accum.rsqrt();
} else {
accum.device(d) += grad.square();
var.device(d) -= grad * lr() * accum.rsqrt();
}
}
};
template <typename T>
struct ApplyMomentum<CPUDevice, T> {
void operator()(const CPUDevice& d, typename TTypes<T>::Flat var,
typename TTypes<T>::Flat accum,
typename TTypes<T>::ConstScalar lr,
typename TTypes<T>::ConstFlat grad,
typename TTypes<T>::ConstScalar momentum) {
if (DoInline(var.size())) {
accum = accum * momentum() + grad;
var -= accum * lr();
} else {
accum.device(d) = accum * momentum() + grad;
var.device(d) -= accum * lr();
}
}
};
template <typename T>
struct ApplyAdam<CPUDevice, T> {
void operator()(const CPUDevice& d, typename TTypes<T>::Flat var,
typename TTypes<T>::Flat m, typename TTypes<T>::Flat v,
typename TTypes<T>::ConstScalar beta1_power,
typename TTypes<T>::ConstScalar beta2_power,
typename TTypes<T>::ConstScalar lr,
typename TTypes<T>::ConstScalar beta1,
typename TTypes<T>::ConstScalar beta2,
typename TTypes<T>::ConstScalar epsilon,
typename TTypes<T>::ConstFlat grad) {
const T alpha = lr() * std::sqrt(1 - beta2_power()) / (1 - beta1_power());
if (DoInline(var.size())) {
m += (grad - m) * (1 - beta1());
v += (grad.square() - v) * (1 - beta2());
var -= (m * alpha) / (v.sqrt() + epsilon());
} else {
m.device(d) += (grad - m) * (1 - beta1());
v.device(d) += (grad.square() - v) * (1 - beta2());
var.device(d) -= (m * alpha) / (v.sqrt() + epsilon());
}
}
};
template <typename T>
struct ApplyRMSProp<CPUDevice, T> {
void operator()(const CPUDevice& d, typename TTypes<T>::Flat var,
typename TTypes<T>::Flat ms, typename TTypes<T>::Flat mom,
typename TTypes<T>::ConstScalar lr,
typename TTypes<T>::ConstScalar rho,
typename TTypes<T>::ConstScalar momentum,
typename TTypes<T>::ConstScalar epsilon,
typename TTypes<T>::ConstFlat grad) {
if (DoInline(var.size())) {
ms += (grad.square() - ms) * (1 - rho());
mom = mom * momentum() + (grad * lr()) / ((ms + epsilon()).sqrt());
var -= mom;
} else {
ms.device(d) += (grad.square() - ms) * (1 - rho());
mom.device(d) =
mom * momentum() + (grad * lr()) / ((ms + epsilon()).sqrt());
var.device(d) -= mom;
}
}
};
} // namespace functor
template <typename Device, typename T>
class ApplyGradientDescentOp : public OpKernel {
public:
explicit ApplyGradientDescentOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
OP_REQUIRES_OK(ctx, ctx->GetAttr("use_locking", &use_exclusive_lock_));
}
void Compute(OpKernelContext* ctx) override {
if (use_exclusive_lock_) {
mutex_lock l(*ctx->input_ref_mutex(0));
DoValidate(ctx);
if (!ctx->status().ok()) return;
DoCompute(ctx);
} else {
DoValidate(ctx);
if (!ctx->status().ok()) return;
DoCompute(ctx);
}
ctx->forward_ref_input_to_ref_output(0, 0);
}
private:
bool use_exclusive_lock_;
void DoValidate(OpKernelContext* ctx) {
Tensor var = ctx->mutable_input(0, use_exclusive_lock_);
OP_REQUIRES(
ctx, var.IsInitialized(),
errors::FailedPrecondition(
"Attempting to use uninitialized variables: ", def().input(0)));
const Tensor& alpha = ctx->input(1);
OP_REQUIRES(ctx, TensorShapeUtils::IsLegacyScalar(alpha.shape()),
errors::InvalidArgument("alpha is not a scalar: ",
alpha.shape().DebugString()));
const Tensor& delta = ctx->input(2);
OP_REQUIRES(
ctx, var.shape().IsSameSize(delta.shape()),
errors::InvalidArgument("var and delta do not have the same shape",
var.shape().DebugString(), " ",
delta.shape().DebugString()));
}
void DoCompute(OpKernelContext* ctx) {
const Device& device = ctx->template eigen_device<Device>();
Tensor var = ctx->mutable_input(0, use_exclusive_lock_);
const Tensor& alpha = ctx->input(1);
const Tensor& delta = ctx->input(2);
functor::ApplyGradientDescent<Device, T>()(
device, var.flat<T>(), alpha.scalar<T>(), delta.flat<T>());
}
};
#define REGISTER_KERNELS(D, T) \
REGISTER_KERNEL_BUILDER( \
Name("ApplyGradientDescent").Device(DEVICE_##D).TypeConstraint<T>("T"), \
ApplyGradientDescentOp<D##Device, T>);
REGISTER_KERNELS(CPU, float);
REGISTER_KERNELS(CPU, double);
#if GOOGLE_CUDA
// Forward declarations of the functor specializations for GPU.
namespace functor {
#define DECLARE_GPU_SPEC(T) \
template <> \
void ApplyGradientDescent<GPUDevice, T>::operator()( \
const GPUDevice& d, typename TTypes<T>::Flat var, \
typename TTypes<T>::ConstScalar alpha, \
typename TTypes<T>::ConstFlat delta); \
extern template struct ApplyGradientDescent<GPUDevice, T>;
DECLARE_GPU_SPEC(float);
DECLARE_GPU_SPEC(double);
#undef DECLARE_GPU_SPEC
} // namespace functor
REGISTER_KERNELS(GPU, float);
REGISTER_KERNELS(GPU, double);
#endif
#undef REGISTER_KERNELS
template <typename Device, typename T>
class ApplyAdagradOp : public OpKernel {
public:
explicit ApplyAdagradOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
OP_REQUIRES_OK(ctx, ctx->GetAttr("use_locking", &use_exclusive_lock_));
}
void Compute(OpKernelContext* ctx) override {
if (use_exclusive_lock_) {
mutex_lock l1(*ctx->input_ref_mutex(0));
// Don't try to acquire a lock on the second ref as they share the same
// mutex.
//
// mutex_lock l2(*ctx->input_ref_mutex(1));
DoValidate(ctx);
if (!ctx->status().ok()) return;
DoCompute(ctx);
} else {
DoValidate(ctx);
if (!ctx->status().ok()) return;
DoCompute(ctx);
}
ctx->forward_ref_input_to_ref_output(0, 0);
}
private:
bool use_exclusive_lock_;
void DoValidate(OpKernelContext* ctx) {
Tensor var = ctx->mutable_input(0, use_exclusive_lock_);
Tensor accum = ctx->mutable_input(1, use_exclusive_lock_);
OP_REQUIRES(
ctx, var.IsInitialized(),
errors::FailedPrecondition(
"Attempting to use uninitialized variables: ", def().input(0)));
OP_REQUIRES(
ctx, accum.IsInitialized(),
errors::FailedPrecondition(
"Attempting to use uninitialized variables: ", def().input(1)));
const Tensor& lr = ctx->input(2);
OP_REQUIRES(ctx, TensorShapeUtils::IsLegacyScalar(lr.shape()),
errors::InvalidArgument("lr is not a scalar: ",
lr.shape().DebugString()));
const Tensor& grad = ctx->input(3);
OP_REQUIRES(
ctx, var.shape().IsSameSize(accum.shape()),
errors::InvalidArgument("var and accum do not have the same shape",
var.shape().DebugString(), " ",
accum.shape().DebugString()));
OP_REQUIRES(
ctx, var.shape().IsSameSize(grad.shape()),
errors::InvalidArgument("var and delta do not have the same shape",
var.shape().DebugString(), " ",
grad.shape().DebugString()));
}
void DoCompute(OpKernelContext* ctx) {
const Device& device = ctx->template eigen_device<Device>();
Tensor var = ctx->mutable_input(0, use_exclusive_lock_);
Tensor accum = ctx->mutable_input(1, use_exclusive_lock_);
const Tensor& lr = ctx->input(2);
const Tensor& grad = ctx->input(3);
functor::ApplyAdagrad<Device, T>()(device, var.flat<T>(), accum.flat<T>(),
lr.scalar<T>(), grad.flat<T>());
}
};
typedef Eigen::ThreadPoolDevice CPUDevice;
typedef Eigen::GpuDevice GPUDevice;
#define REGISTER_KERNELS(D, T) \
REGISTER_KERNEL_BUILDER( \
Name("ApplyAdagrad").Device(DEVICE_##D).TypeConstraint<T>("T"), \
ApplyAdagradOp<D##Device, T>);
REGISTER_KERNELS(CPU, float);
REGISTER_KERNELS(CPU, double);
#if GOOGLE_CUDA
// Forward declarations of the functor specializations for GPU.
namespace functor {
#define DECLARE_GPU_SPEC(T) \
template <> \
void ApplyAdagrad<GPUDevice, T>::operator()( \
const GPUDevice& d, typename TTypes<T>::Flat var, \
typename TTypes<T>::Flat accum, typename TTypes<T>::ConstScalar lr, \
typename TTypes<T>::ConstFlat grad); \
extern template struct ApplyAdagrad<GPUDevice, T>;
DECLARE_GPU_SPEC(float);
DECLARE_GPU_SPEC(double);
#undef DECLARE_GPU_SPEC
} // namespace functor
REGISTER_KERNELS(GPU, float);
REGISTER_KERNELS(GPU, double);
#endif
#undef REGISTER_KERNELS
// Note, this op works on cpu only.
template <typename T, typename Tindex>
class SparseApplyAdagradOp : public OpKernel {
public:
explicit SparseApplyAdagradOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
OP_REQUIRES_OK(ctx, ctx->GetAttr("use_locking", &use_exclusive_lock_));
}
void Compute(OpKernelContext* ctx) override NO_THREAD_SAFETY_ANALYSIS {
mutex* mu_var = ctx->input_ref_mutex(0);
// mu_accum is actually the same mutex as mu_var since currently we use a
// global mutex.
//
// mutex* mu_accum = ctx->input_ref_mutex(1);
if (use_exclusive_lock_) {
mu_var->lock();
}
Tensor var = ctx->mutable_input(0, use_exclusive_lock_);
Tensor accum = ctx->mutable_input(1, use_exclusive_lock_);
OP_REQUIRES(
ctx, var.IsInitialized(),
errors::FailedPrecondition(
"Attempting to use uninitialized variables: ", def().input(0)));
OP_REQUIRES(
ctx, accum.IsInitialized(),
errors::FailedPrecondition(
"Attempting to use uninitialized variables: ", def().input(1)));
OP_REQUIRES(
ctx, var.shape().IsSameSize(accum.shape()),
errors::InvalidArgument("var and accum do not have the same shape",
var.shape().DebugString(), " ",
accum.shape().DebugString()));
OP_REQUIRES(ctx, TensorShapeUtils::IsVectorOrHigher(var.shape()),
errors::InvalidArgument("var must be at least 1 dimensional"));
const Tensor& lr = ctx->input(2);
OP_REQUIRES(ctx, TensorShapeUtils::IsLegacyScalar(lr.shape()),
errors::InvalidArgument("lr is not a scalar: ",
lr.shape().DebugString()));
const Tensor& grad = ctx->input(3);
const Tensor& indices = ctx->input(4);
OP_REQUIRES(ctx, TensorShapeUtils::IsVector(indices.shape()),
errors::InvalidArgument("indices must be one-dimensional"));
for (int d = 1; d < var.dims(); d++) {
OP_REQUIRES(ctx, var.dim_size(d) == grad.dim_size(d),
errors::InvalidArgument(strings::StrCat(
"var and grad must match in dimension ", d)));
}
const Tindex N = indices.dim_size(0);
OP_REQUIRES(
ctx, grad.dim_size(0) == N,
errors::InvalidArgument(
"grad must be the same size as indices in the first dimension."));
if (N > 0) {
const Tindex first_dim_size = var.dim_size(0);
// Validate all the indices are in range
auto indices_vec = indices.vec<Tindex>();
for (Tindex i = 0; i < N; i++) {
const Tindex index = indices_vec(i);
OP_REQUIRES(ctx, index >= 0 && index < first_dim_size,
errors::InvalidArgument(
strings::StrCat("Index ", index, " at offset ", i,
" in indices is out of range")));
}
auto var_flat = var.flat_outer_dims<T>();
auto accum_flat = accum.flat_outer_dims<T>();
auto grad_flat = grad.flat_outer_dims<T>();
T lr_scalar = lr.scalar<T>()();
// Note(yonghui): It might be worth multi-threading square() and rsqrt().
for (Tindex i = 0; i < N; i++) {
const Tindex index = indices_vec(i);
auto a = accum_flat.template chip<0>(index);
auto g = grad_flat.template chip<0>(i);
auto v = var_flat.template chip<0>(index);
a += g.square();
v -= g.constant(lr_scalar) * g * a.rsqrt();
}
}
if (use_exclusive_lock_) {
mu_var->unlock();
}
ctx->forward_ref_input_to_ref_output(0, 0);
}
private:
bool use_exclusive_lock_;
};
#define REGISTER_KERNELS(T, Tindices) \
REGISTER_KERNEL_BUILDER(Name("SparseApplyAdagrad") \
.Device(DEVICE_CPU) \
.TypeConstraint<T>("T") \
.TypeConstraint<Tindices>("Tindices"), \
SparseApplyAdagradOp<T, Tindices>);
REGISTER_KERNELS(float, int32);
REGISTER_KERNELS(float, int64);
REGISTER_KERNELS(double, int32);
REGISTER_KERNELS(double, int64);
#undef REGISTER_KERNELS
template <typename Device, typename T>
class ApplyMomentumOp : public OpKernel {
public:
explicit ApplyMomentumOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
OP_REQUIRES_OK(ctx, ctx->GetAttr("use_locking", &use_exclusive_lock_));
}
void Compute(OpKernelContext* ctx) override {
if (use_exclusive_lock_) {
mutex_lock l1(*ctx->input_ref_mutex(0));
// Don't try to acquire a lock on the second ref as they share the same
// mutex.
//
// mutex_lock l2(*ctx->input_ref_mutex(1));
DoValidate(ctx);
if (!ctx->status().ok()) return;
DoCompute(ctx);
} else {
DoValidate(ctx);
if (!ctx->status().ok()) return;
DoCompute(ctx);
}
ctx->forward_ref_input_to_ref_output(0, 0);
}
private:
bool use_exclusive_lock_;
void DoValidate(OpKernelContext* ctx) {
Tensor var = ctx->mutable_input(0, use_exclusive_lock_);
Tensor accum = ctx->mutable_input(1, use_exclusive_lock_);
OP_REQUIRES(
ctx, var.IsInitialized(),
errors::FailedPrecondition(
"Attempting to use uninitialized variables: ", def().input(0)));
OP_REQUIRES(
ctx, accum.IsInitialized(),
errors::FailedPrecondition(
"Attempting to use uninitialized variables: ", def().input(1)));
const Tensor& lr = ctx->input(2);
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(lr.shape()),
errors::InvalidArgument("lr is not a scalar: ",
lr.shape().DebugString()));
const Tensor& grad = ctx->input(3);
OP_REQUIRES(
ctx, var.shape().IsSameSize(accum.shape()),
errors::InvalidArgument("var and accum do not have the same shape",
var.shape().DebugString(), " ",
accum.shape().DebugString()));
OP_REQUIRES(
ctx, var.shape().IsSameSize(grad.shape()),
errors::InvalidArgument("var and delta do not have the same shape",
var.shape().DebugString(), " ",
grad.shape().DebugString()));
const Tensor& momentum = ctx->input(4);
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(momentum.shape()),
errors::InvalidArgument("momentum is not a scalar: ",
momentum.shape().DebugString()));
}
void DoCompute(OpKernelContext* ctx) {
const Device& device = ctx->template eigen_device<Device>();
Tensor var = ctx->mutable_input(0, use_exclusive_lock_);
Tensor accum = ctx->mutable_input(1, use_exclusive_lock_);
const Tensor& lr = ctx->input(2);
const Tensor& grad = ctx->input(3);
const Tensor& momentum = ctx->input(4);
functor::ApplyMomentum<Device, T>()(device, var.flat<T>(), accum.flat<T>(),
lr.scalar<T>(), grad.flat<T>(),
momentum.scalar<T>());
}
};
typedef Eigen::ThreadPoolDevice CPUDevice;
typedef Eigen::GpuDevice GPUDevice;
#define REGISTER_KERNELS(D, T) \
REGISTER_KERNEL_BUILDER( \
Name("ApplyMomentum").Device(DEVICE_##D).TypeConstraint<T>("T"), \
ApplyMomentumOp<D##Device, T>);
REGISTER_KERNELS(CPU, float);
REGISTER_KERNELS(CPU, double);
#if GOOGLE_CUDA
// Forward declarations of the functor specializations for GPU.
namespace functor {
#define DECLARE_GPU_SPEC(T) \
template <> \
void ApplyMomentum<GPUDevice, T>::operator()( \
const GPUDevice& d, typename TTypes<T>::Flat var, \
typename TTypes<T>::Flat accum, typename TTypes<T>::ConstScalar lr, \
typename TTypes<T>::ConstFlat grad, \
typename TTypes<T>::ConstScalar momentum); \
extern template struct ApplyMomentum<GPUDevice, T>;
DECLARE_GPU_SPEC(float);
DECLARE_GPU_SPEC(double);
#undef DECLARE_GPU_SPEC
} // namespace functor
REGISTER_KERNELS(GPU, float);
REGISTER_KERNELS(GPU, double);
#endif
#undef REGISTER_KERNELS
// Note, this op works on cpu only.
template <typename T, typename Tindex>
class SparseApplyMomentumOp : public OpKernel {
public:
explicit SparseApplyMomentumOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
OP_REQUIRES_OK(ctx, ctx->GetAttr("use_locking", &use_exclusive_lock_));
}
void Compute(OpKernelContext* ctx) override NO_THREAD_SAFETY_ANALYSIS {
mutex* mu_var = ctx->input_ref_mutex(0);
// mu_accum is actually the same mutex as mu_var since currently we use a
// global mutex.
//
// mutex* mu_accum = ctx->input_ref_mutex(1);
if (use_exclusive_lock_) {
mu_var->lock();
}
Tensor var = ctx->mutable_input(0, use_exclusive_lock_);
Tensor accum = ctx->mutable_input(1, use_exclusive_lock_);
OP_REQUIRES(
ctx, var.IsInitialized(),
errors::FailedPrecondition(
"Attempting to use uninitialized variables: ", def().input(0)));
OP_REQUIRES(
ctx, accum.IsInitialized(),
errors::FailedPrecondition(
"Attempting to use uninitialized variables: ", def().input(1)));
OP_REQUIRES(
ctx, var.shape().IsSameSize(accum.shape()),
errors::InvalidArgument("var and accum do not have the same shape",
var.shape().DebugString(), " ",
accum.shape().DebugString()));
OP_REQUIRES(ctx, TensorShapeUtils::IsVectorOrHigher(var.shape()),
errors::InvalidArgument("var must be at least 1 dimensional"));
const Tensor& lr = ctx->input(2);
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(lr.shape()),
errors::InvalidArgument("lr is not a scalar: ",
lr.shape().DebugString()));
const Tensor& grad = ctx->input(3);
const Tensor& indices = ctx->input(4);
OP_REQUIRES(ctx, TensorShapeUtils::IsVector(indices.shape()),
errors::InvalidArgument("indices must be one-dimensional"));
for (int d = 1; d < var.dims(); d++) {
OP_REQUIRES(ctx, var.dim_size(d) == grad.dim_size(d),
errors::InvalidArgument(strings::StrCat(
"var and grad must match in dimension ", d)));
}
const Tindex N = indices.dim_size(0);
OP_REQUIRES(
ctx, grad.dim_size(0) == N,
errors::InvalidArgument(
"grad must be the same size as indices in the first dimension."));
const Tensor& momentum = ctx->input(5);
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(momentum.shape()),
errors::InvalidArgument("momentum is not a scalar: ",
momentum.shape().DebugString()));
if (N > 0) {
const Tindex first_dim_size = var.dim_size(0);
// Validate all the indices are in range
auto indices_vec = indices.vec<Tindex>();
for (Tindex i = 0; i < N; i++) {
const Tindex index = indices_vec(i);
OP_REQUIRES(ctx, index >= 0 && index < first_dim_size,
errors::InvalidArgument(
strings::StrCat("Index ", index, " at offset ", i,
" in indices is out of range")));
}
auto var_flat = var.flat_outer_dims<T>();
auto accum_flat = accum.flat_outer_dims<T>();
auto grad_flat = grad.flat_outer_dims<T>();
T lr_scalar = lr.scalar<T>()();
T momentum_scalar = momentum.scalar<T>()();
for (Tindex i = 0; i < N; i++) {
const Tindex index = indices_vec(i);
auto a = accum_flat.template chip<0>(index);
auto g = grad_flat.template chip<0>(i);
auto v = var_flat.template chip<0>(index);
a = a * a.constant(momentum_scalar) + g;
v -= a.constant(lr_scalar) * a;
}
}
if (use_exclusive_lock_) {
mu_var->unlock();
}
ctx->forward_ref_input_to_ref_output(0, 0);
}
private:
bool use_exclusive_lock_;
};
#define REGISTER_KERNELS(T, Tindices) \
REGISTER_KERNEL_BUILDER(Name("SparseApplyMomentum") \
.Device(DEVICE_CPU) \
.TypeConstraint<T>("T") \
.TypeConstraint<Tindices>("Tindices"), \
SparseApplyMomentumOp<T, Tindices>);
REGISTER_KERNELS(float, int32);
REGISTER_KERNELS(float, int64);
REGISTER_KERNELS(double, int32);
REGISTER_KERNELS(double, int64);
#undef REGISTER_KERNELS
template <typename Device, typename T>
class ApplyAdamOp : public OpKernel {
public:
explicit ApplyAdamOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
OP_REQUIRES_OK(ctx, ctx->GetAttr("use_locking", &use_exclusive_lock_));
}
void Compute(OpKernelContext* ctx) override {
if (use_exclusive_lock_) {
// all input refs share the same mutex
mutex_lock l1(*ctx->input_ref_mutex(0));
DoValidate(ctx);
if (!ctx->status().ok()) return;
DoCompute(ctx);
} else {
DoValidate(ctx);
if (!ctx->status().ok()) return;
DoCompute(ctx);
}
ctx->forward_ref_input_to_ref_output(0, 0);
}
private:
bool use_exclusive_lock_;
void DoValidate(OpKernelContext* ctx) {
Tensor var = ctx->mutable_input(0, use_exclusive_lock_);
Tensor m = ctx->mutable_input(1, use_exclusive_lock_);
Tensor v = ctx->mutable_input(2, use_exclusive_lock_);
OP_REQUIRES(
ctx, var.IsInitialized(),
errors::FailedPrecondition(
"Attempting to use uninitialized variables: ", def().input(0)));
OP_REQUIRES(
ctx, m.IsInitialized(),
errors::FailedPrecondition(
"Attempting to use uninitialized variables: ", def().input(1)));
OP_REQUIRES(
ctx, v.IsInitialized(),
errors::FailedPrecondition(
"Attempting to use uninitialized variables: ", def().input(2)));
const Tensor& beta1_power = ctx->input(3);
const Tensor& beta2_power = ctx->input(4);
const Tensor& lr = ctx->input(5);
const Tensor& beta1 = ctx->input(6);
const Tensor& beta2 = ctx->input(7);
const Tensor& epsilon = ctx->input(8);
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(beta1_power.shape()),
errors::InvalidArgument("beta1_power is not a scalar: ",
beta1_power.shape().DebugString()));
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(beta2_power.shape()),
errors::InvalidArgument("beta2_power is not a scalar: ",
beta2_power.shape().DebugString()));
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(lr.shape()),
errors::InvalidArgument("lr is not a scalar: ",
lr.shape().DebugString()));
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(beta1.shape()),
errors::InvalidArgument("beta1 is not a scalar: ",
beta1.shape().DebugString()));
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(beta2.shape()),
errors::InvalidArgument("beta2 is not a scalar: ",
beta2.shape().DebugString()));
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(epsilon.shape()),
errors::InvalidArgument("epsilon is not a scalar: ",
epsilon.shape().DebugString()));
const Tensor& grad = ctx->input(9);
OP_REQUIRES(ctx, var.shape().IsSameSize(m.shape()),
errors::InvalidArgument("var and m do not have the same shape",
var.shape().DebugString(), " ",
m.shape().DebugString()));
OP_REQUIRES(ctx, var.shape().IsSameSize(v.shape()),
errors::InvalidArgument("var and v do not have the same shape",
var.shape().DebugString(), " ",
v.shape().DebugString()));
OP_REQUIRES(
ctx, var.shape().IsSameSize(grad.shape()),
errors::InvalidArgument("var and grad do not have the same shape",
var.shape().DebugString(), " ",
grad.shape().DebugString()));
}
void DoCompute(OpKernelContext* ctx) {
const Device& device = ctx->template eigen_device<Device>();
Tensor var = ctx->mutable_input(0, use_exclusive_lock_);
Tensor m = ctx->mutable_input(1, use_exclusive_lock_);
Tensor v = ctx->mutable_input(2, use_exclusive_lock_);
const Tensor& beta1_power = ctx->input(3);
const Tensor& beta2_power = ctx->input(4);
const Tensor& lr = ctx->input(5);
const Tensor& beta1 = ctx->input(6);
const Tensor& beta2 = ctx->input(7);
const Tensor& epsilon = ctx->input(8);
const Tensor& grad = ctx->input(9);
functor::ApplyAdam<Device, T>()(device, var.flat<T>(), m.flat<T>(),
v.flat<T>(), beta1_power.scalar<T>(),
beta2_power.scalar<T>(), lr.scalar<T>(),
beta1.scalar<T>(), beta2.scalar<T>(),
epsilon.scalar<T>(), grad.flat<T>());
}
};
typedef Eigen::ThreadPoolDevice CPUDevice;
typedef Eigen::GpuDevice GPUDevice;
#define REGISTER_KERNELS(D, T) \
REGISTER_KERNEL_BUILDER( \
Name("ApplyAdam").Device(DEVICE_##D).TypeConstraint<T>("T"), \
ApplyAdamOp<D##Device, T>);
REGISTER_KERNELS(CPU, float);
REGISTER_KERNELS(CPU, double);
#if GOOGLE_CUDA
// Forward declarations of the functor specializations for GPU.
namespace functor {
#define DECLARE_GPU_SPEC(T) \
template <> \
void ApplyAdam<GPUDevice, T>::operator()( \
const GPUDevice& d, typename TTypes<T>::Flat var, \
typename TTypes<T>::Flat m, typename TTypes<T>::Flat v, \
typename TTypes<T>::ConstScalar beta1_power, \
typename TTypes<T>::ConstScalar beta2_power, \
typename TTypes<T>::ConstScalar lr, \
typename TTypes<T>::ConstScalar beta1, \
typename TTypes<T>::ConstScalar beta2, \
typename TTypes<T>::ConstScalar epsilon, \
typename TTypes<T>::ConstFlat grad); \
extern template struct ApplyAdam<GPUDevice, T>;
DECLARE_GPU_SPEC(float);
DECLARE_GPU_SPEC(double);
#undef DECLARE_GPU_SPEC
} // namespace functor
REGISTER_KERNELS(GPU, float);
REGISTER_KERNELS(GPU, double);
#endif
#undef REGISTER_KERNELS
template <typename Device, typename T>
class ApplyRMSPropOp : public OpKernel {
public:
explicit ApplyRMSPropOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
OP_REQUIRES_OK(ctx, ctx->GetAttr("use_locking", &use_exclusive_lock_));
}
void Compute(OpKernelContext* ctx) override {
if (use_exclusive_lock_) {
// all input refs share the same mutex
mutex_lock l1(*ctx->input_ref_mutex(0));
DoValidate(ctx);
if (!ctx->status().ok()) return;
DoCompute(ctx);
} else {
DoValidate(ctx);
if (!ctx->status().ok()) return;
DoCompute(ctx);
}
ctx->forward_ref_input_to_ref_output(0, 0);
}
private:
bool use_exclusive_lock_;
void DoValidate(OpKernelContext* ctx) {
Tensor var = ctx->mutable_input(0, use_exclusive_lock_);
Tensor ms = ctx->mutable_input(1, use_exclusive_lock_);
Tensor mom = ctx->mutable_input(2, use_exclusive_lock_);
OP_REQUIRES(
ctx, var.IsInitialized(),
errors::FailedPrecondition(
"Attempting to use uninitialized variables: ", def().input(0)));
OP_REQUIRES(
ctx, ms.IsInitialized(),
errors::FailedPrecondition(
"Attempting to use uninitialized variables: ", def().input(1)));
OP_REQUIRES(
ctx, mom.IsInitialized(),
errors::FailedPrecondition(
"Attempting to use uninitialized variables: ", def().input(2)));
const Tensor& lr = ctx->input(3);
const Tensor& rho = ctx->input(4);
const Tensor& momentum = ctx->input(5);
const Tensor& epsilon = ctx->input(6);
const Tensor& grad = ctx->input(7);
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(lr.shape()),
errors::InvalidArgument("lr is not a scalar: ",
lr.shape().DebugString()));
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(rho.shape()),
errors::InvalidArgument("rho is not a scalar: ",
rho.shape().DebugString()));
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(momentum.shape()),
errors::InvalidArgument("momentum is not a scalar: ",
momentum.shape().DebugString()));
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(epsilon.shape()),
errors::InvalidArgument("epsilon is not a scalar: ",
epsilon.shape().DebugString()));
OP_REQUIRES(ctx, var.shape().IsSameSize(ms.shape()),
errors::InvalidArgument("var and ms do not have the same shape",
var.shape().DebugString(), " ",
ms.shape().DebugString()));
OP_REQUIRES(ctx, var.shape().IsSameSize(mom.shape()),
errors::InvalidArgument(
"var and mom do not have the same shape",
var.shape().DebugString(), " ", mom.shape().DebugString()));
OP_REQUIRES(
ctx, var.shape().IsSameSize(grad.shape()),
errors::InvalidArgument("var and grad do not have the same shape",
var.shape().DebugString(), " ",
grad.shape().DebugString()));
}
void DoCompute(OpKernelContext* ctx) {
const Device& device = ctx->template eigen_device<Device>();
Tensor var = ctx->mutable_input(0, use_exclusive_lock_);
Tensor ms = ctx->mutable_input(1, use_exclusive_lock_);
Tensor mom = ctx->mutable_input(2, use_exclusive_lock_);
const Tensor& lr = ctx->input(3);
const Tensor& rho = ctx->input(4);
const Tensor& momentum = ctx->input(5);
const Tensor& epsilon = ctx->input(6);
const Tensor& grad = ctx->input(7);
functor::ApplyRMSProp<Device, T>()(device, var.flat<T>(), ms.flat<T>(),
mom.flat<T>(), lr.scalar<T>(),
rho.scalar<T>(), momentum.scalar<T>(),
epsilon.scalar<T>(), grad.flat<T>());
}
};
typedef Eigen::ThreadPoolDevice CPUDevice;
typedef Eigen::GpuDevice GPUDevice;
#define REGISTER_KERNELS(D, T) \
REGISTER_KERNEL_BUILDER( \
Name("ApplyRMSProp").Device(DEVICE_##D).TypeConstraint<T>("T"), \
ApplyRMSPropOp<D##Device, T>);
REGISTER_KERNELS(CPU, float);
REGISTER_KERNELS(CPU, double);
#if GOOGLE_CUDA
// Forward declarations of the functor specializations for GPU.
namespace functor {
#define DECLARE_GPU_SPEC(T) \
template <> \
void ApplyRMSProp<GPUDevice, T>::operator()( \
const GPUDevice& d, typename TTypes<T>::Flat var, \
typename TTypes<T>::Flat ms, typename TTypes<T>::Flat mom, \
typename TTypes<T>::ConstScalar lr, typename TTypes<T>::ConstScalar rho, \
typename TTypes<T>::ConstScalar momentum, \
typename TTypes<T>::ConstScalar epsilon, \
typename TTypes<T>::ConstFlat grad); \
extern template struct ApplyRMSProp<GPUDevice, T>;
DECLARE_GPU_SPEC(float);
DECLARE_GPU_SPEC(double);
#undef DECLARE_GPU_SPEC
} // namespace functor
REGISTER_KERNELS(GPU, float);
REGISTER_KERNELS(GPU, double);
#endif
#undef REGISTER_KERNELS
} // namespace tensorflow
| 35,105 | 11,304 |
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2007 Robert McNeel & Associates. All rights reserved.
// Rhinoceros is a registered trademark of Robert McNeel & Assoicates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#include "opennurbs.h"
ON_Sum::ON_Sum()
{
Begin(0.0);
}
int ON_Sum::SummandCount() const
{
return m_pos_count + m_neg_count + m_zero_count;
}
void ON_Sum::Begin( double starting_value )
{
m_sum_err = 0.0;
m_pos_sum = 0.0;
m_neg_sum = 0.0;
m_pos_sum1_count = 0;
m_pos_sum2_count = 0;
m_pos_sum3_count = 0;
m_neg_sum1_count = 0;
m_neg_sum2_count = 0;
m_neg_sum3_count = 0;
m_pos_count = 0;
m_neg_count = 0;
m_zero_count = 0;
if ( starting_value > 0.0 )
{
m_pos_sum = starting_value;
}
else if ( starting_value < 0.0 )
{
m_neg_sum = starting_value;
}
}
double ON_Sum::SortAndSum( int count, double* a )
{
// note that the arrays passed to ON_Sum::SortAndSum() are all
// homogeneous in sign
double s = 0.0;
if ( count > 0 )
{
if ( count >= 2 )
{
ON_SortDoubleArray( ON::quick_sort, a, count );
//double a0 = fabs(a[0]);
//double a1 = fabs(a[count-1]);
m_sum_err += ON_EPSILON*( fabs(a[count-1]) + count*fabs(a[0]) );
}
if ( a[count] < 0.0 )
{
a += count-1;
while (count--)
s += *a--;
}
else
{
while (count--)
s += *a++;
}
}
return s;
}
void ON_Sum::Plus( double x )
{
if (x > 0.0)
{
m_pos_count++;
m_pos_sum1[m_pos_sum1_count++] = x;
if ( m_pos_sum1_count == sum1_max_count )
{
m_pos_sum2[m_pos_sum2_count++] = SortAndSum( m_pos_sum1_count, m_pos_sum1 );
m_pos_sum1_count = 0;
if ( m_pos_sum2_count == sum2_max_count )
{
m_pos_sum3[m_pos_sum3_count++] = SortAndSum( m_pos_sum2_count, m_pos_sum2 );
m_pos_sum2_count = 0;
if ( m_pos_sum3_count == sum3_max_count )
{
x = SortAndSum( m_pos_sum3_count, m_pos_sum3 );
m_sum_err += ON_EPSILON*( fabs(x) + fabs(m_pos_sum) );
m_pos_sum += x;
m_pos_sum3_count = 0;
}
}
}
}
else if ( x < 0.0 )
{
m_neg_count++;
m_neg_sum1[m_neg_sum1_count++] = x;
if ( m_neg_sum1_count == sum1_max_count )
{
m_neg_sum2[m_neg_sum2_count++] = SortAndSum( m_neg_sum1_count, m_neg_sum1 );
m_neg_sum1_count = 0;
if ( m_neg_sum2_count == sum2_max_count )
{
m_neg_sum3[m_neg_sum3_count++] = SortAndSum( m_neg_sum2_count, m_neg_sum2 );
m_neg_sum2_count = 0;
if ( m_neg_sum3_count == sum3_max_count )
{
x = SortAndSum( m_neg_sum3_count, m_neg_sum3 );
m_sum_err += ON_EPSILON*( fabs(x) + fabs(m_neg_sum) );
m_neg_sum += x;
m_neg_sum3_count = 0;
}
}
}
}
else
m_zero_count++;
}
void ON_Sum::operator=(double x)
{
Begin(x);
}
void ON_Sum::operator+=(double x)
{
Plus(x);
}
void ON_Sum::operator-=(double x)
{
Plus(-x);
}
double ON_Sum::Total( double* error_estimate )
{
double x;
if ( m_pos_sum1_count > 0 )
{
m_pos_sum2[m_pos_sum2_count++] = SortAndSum( m_pos_sum1_count, m_pos_sum1 );
m_pos_sum1_count = 0;
}
if ( m_pos_sum2_count > 0 )
{
m_pos_sum3[m_pos_sum3_count++] = SortAndSum( m_pos_sum2_count, m_pos_sum2 );
m_pos_sum2_count = 0;
}
if ( m_pos_sum3_count > 0 )
{
x = SortAndSum( m_pos_sum3_count, m_pos_sum3 );
m_sum_err += ON_EPSILON*( fabs(x) + fabs(m_pos_sum) );
m_pos_sum += x;
m_pos_sum3_count = 0;
}
if ( m_neg_sum1_count > 0 )
{
m_neg_sum2[m_neg_sum2_count++] = SortAndSum( m_neg_sum1_count, m_neg_sum1 );
m_neg_sum1_count = 0;
}
if ( m_neg_sum2_count > 0 )
{
m_neg_sum3[m_neg_sum3_count++] = SortAndSum( m_neg_sum2_count, m_neg_sum2 );
m_neg_sum2_count = 0;
}
if ( m_neg_sum3_count > 0 )
{
x = SortAndSum( m_neg_sum3_count, m_neg_sum3 );
m_sum_err += ON_EPSILON*( fabs(x) + fabs(m_neg_sum) );
m_neg_sum += x;
m_neg_sum3_count = 0;
}
if ( error_estimate )
{
*error_estimate = m_sum_err + ON_EPSILON*(fabs(m_pos_sum) + fabs(m_neg_sum));
}
return m_pos_sum + m_neg_sum;
}
| 4,487 | 2,072 |
#include <iostream>
#include <stdlib.h>
#include <math.h>
using namespace std;
int result_array[] = {0,0,1,4,6,8,9,7,2,13,12};
int array[] = {1,2,3,4,5,6};
int elements = 6;
int merge_sort(int inArray[], int total_elements, bool count_inversion)
{
int inversion = 0;
if (total_elements <= 1 ) {
return 1;
}
merge_sort(&inArray[0], total_elements/2, false);
merge_sort(&inArray[(total_elements/2)], total_elements - (total_elements/2) , false);
int *arraya = &inArray[0];
int *arrayb = &inArray[(total_elements/2)];
int i=0, j=0, k=0;
cout << "Dumping Array A " << total_elements << " :";
for(int m = 0; m < total_elements/2; m++)
cout << arraya[m] << " " ;
cout << endl;
cout << "Dumping Array B " << total_elements << " :";
for(int m = 0; m < total_elements - total_elements/2; m++)
cout << arrayb[m] << " " ;
cout << endl;
for( k = 0; k < total_elements; k++)
{
if (arraya[i] < arrayb[j])
{
if ( i < total_elements/2 )
{
result_array[k] = arraya[i];
i++;
}
else
{
result_array[k] = arrayb[j];
j++;
}
}
else
{
if ( j < (total_elements - total_elements/2) )
{
result_array[k] = arrayb[j];
j++;
if (count_inversion)
{
inversion += (total_elements/2 - i) ;
}
}
else
{
result_array[k] = arraya[i];
i++;
}
}
}
for (k =0; k < total_elements; k++)
{
inArray[k] = result_array[k];
}
cout << "Level Sorted:";
for(int m = 0; m < total_elements; m++)
cout << result_array[m] << " " ;
cout << endl;
if (count_inversion)
{
cout << "Need to count inversion " << inversion << endl;
}
}
int
main(int argc, char **argv)
{
merge_sort (array, elements, true);
}
| 1,731 | 719 |
// ControlWnd.cpp - A window for containing camera controls.
#include <wx/panel.h>
#include <wx/choice.h>
#include <wx/checkbox.h>
#include <wx/slider.h>
#include <wx/spinctrl.h>
#include <wx/stattext.h>
#include <libcamera/controls.h>
#include <libcamera/control_ids.h>
#include "ControlWnd.h"
BEGIN_EVENT_TABLE(ControlWnd, wxPanel)
EVT_CHOICE(wxID_ANY, ControlWnd::OnChoice)
EVT_SLIDER(wxID_ANY, ControlWnd::OnSlider)
EVT_CHECKBOX(wxID_ANY, ControlWnd::OnCheckBox)
EVT_SPINCTRL(wxID_ANY, ControlWnd::OnSpinCtrl)
END_EVENT_TABLE()
/*** ControlWnd *******************************************************
Constructor.
Inputs:
parent = Parent window.
Coding history:
WJB 19/06/21 Converted from MovieCap
*/
ControlWnd::ControlWnd (wxWindow *parent)
: wxPanel (parent)
{
// printf ("ControlWnd constructor.\n");
// Create controls.
LoadCtl ();
m_fgsz = new wxFlexGridSizer (2);
m_fgsz->AddGrowableCol (1);
std::vector<ImgCtl>::iterator it;
int iCtrl;
for (iCtrl = 0, it = m_victl.begin (); it != m_victl.end (); ++iCtrl, ++it)
{
const char *psDesc = it->GetDesc ().c_str ();
// printf ("Create image control \"%s\"\n", psDesc);
wxString sDesc = wxString (psDesc, wxConvUTF8);
m_fgsz->Add (new wxStaticText (this, wxID_ANY, sDesc), 0, wxALIGN_CENTRE_VERTICAL);
int iType = it->GetType ();
int iMin, iMax, iDef, iVal;
it->GetData (iMin, iMax, iDef, iVal);
if ( iType == 1 )
{
wxBoxSizer *phbsz1 = new wxBoxSizer (wxHORIZONTAL);
m_fgsz->Add (phbsz1, 0, wxEXPAND | wxALIGN_CENTRE_VERTICAL);
wxSlider *pslide = new wxSlider (this, 3*iCtrl, iVal, iMin, iMax, wxDefaultPosition,
wxSize (100,-1));
pslide->Enable (it->Enabled ());
phbsz1->Add (pslide, 1, wxEXPAND | wxALIGN_CENTRE_VERTICAL);
wxSpinCtrl *pspin = new wxSpinCtrl (this, 3*iCtrl + 1, wxT(""), wxDefaultPosition,
wxSize (120, -1), wxSP_VERTICAL);
pspin->SetRange (iMin, iMax);
pspin->SetValue (iVal);
pspin->Enable (it->Enabled ());
phbsz1->Add (pspin, 0, wxALIGN_CENTRE_VERTICAL);
}
else if ( iType == 2 )
{
wxCheckBox * pchk = new wxCheckBox (this, 3*iCtrl, wxT(""));
pchk->SetValue (it->Enabled ());
m_fgsz->Add (pchk, 0, wxEXPAND);
}
else if ( iType == 3 )
{
wxChoice * pchc = new wxChoice (this, 3*iCtrl);
for ( int iItem = iMin; iItem <= iMax; ++iItem )
{
const char *psMenu = it->GetMenuItem (iItem).c_str ();
// printf ("Menu item %d = \"%s\"\n", iItem, psMenu);
pchc->Append (wxString (psMenu, wxConvUTF8));
}
pchc->SetSelection (iVal - iMin);
m_fgsz->Add (pchc, 0, wxEXPAND);
}
else if ( iType == 4 )
{
wxBoxSizer *phbsz1 = new wxBoxSizer (wxHORIZONTAL);
m_fgsz->Add (phbsz1, 0, wxEXPAND | wxALIGN_CENTRE_VERTICAL);
wxCheckBox * pchk = new wxCheckBox (this, 3*iCtrl, wxT(""));
pchk->SetValue (it->Enabled ());
phbsz1->Add (pchk, 0, wxALIGN_CENTRE_VERTICAL);
wxSlider *pslide = new wxSlider (this, 3*iCtrl + 1, iVal, iMin, iMax, wxDefaultPosition,
wxSize (100,-1));
pslide->Enable (it->Enabled ());
phbsz1->Add (pslide, 1, wxALIGN_CENTRE_VERTICAL);
wxSpinCtrl *pspin = new wxSpinCtrl (this, 3*iCtrl + 2, wxT(""), wxDefaultPosition,
wxSize (120, -1), wxSP_VERTICAL);
pspin->SetRange (iMin, iMax);
pspin->SetValue (iVal);
pspin->Enable (it->Enabled ());
phbsz1->Add (pspin, 0, wxALIGN_CENTRE_VERTICAL);
}
else if ( iType == 5 )
{
wxSpinCtrl *pspin = new wxSpinCtrl (this, 3*iCtrl, wxT(""), wxDefaultPosition,
wxSize (120, -1), wxSP_VERTICAL);
pspin->SetRange (iMin, iMax);
pspin->SetValue (iVal);
m_fgsz->Add (pspin, 0, wxEXPAND | wxALIGN_CENTRE_VERTICAL);
}
else if ( iType == 6 )
{
wxBoxSizer *phbsz1 = new wxBoxSizer (wxHORIZONTAL);
m_fgsz->Add (phbsz1, 0, wxEXPAND | wxALIGN_CENTRE_VERTICAL);
wxCheckBox * pchk = new wxCheckBox (this, 3*iCtrl, wxT(""));
pchk->SetValue (it->Enabled ());
phbsz1->Add (pchk, 0, wxALIGN_CENTRE_VERTICAL);
wxSpinCtrl *pspin = new wxSpinCtrl (this, 3*iCtrl + 2, wxT(""), wxDefaultPosition,
wxSize (120, -1), wxSP_VERTICAL);
pspin->SetRange (iMin, iMax);
pspin->SetValue (iVal);
pspin->Enable (it->Enabled ());
phbsz1->Add (pspin, 1, wxALIGN_CENTRE_VERTICAL);
}
}
m_fgsz->Add (new wxStaticText (this, wxID_ANY, ""), 0, wxALIGN_CENTRE_VERTICAL);
m_fgsz->Add (new wxButton (this, ID_SNAP, "Snap"), 0, wxALIGN_CENTRE_VERTICAL);
SetSizer (m_fgsz);
m_fgsz->SetSizeHints (this);
}
/*** ~ControlWnd ******************************************************
Destructor.
Coding history:
WJB 19/ 6/21 Empty version.
*/
ControlWnd::~ControlWnd (void)
{
// printf ("ControlWnd destructor.\n");
}
/*** LoadCtl *******************************************************
Load all the controls for the image capture device.
Coding history:
WJB 19/ 6/21 Converted from MovieCap
*/
void ControlWnd::LoadCtl (void)
{
ImgCtl ctl (0);
m_victl.clear ();
/* Brightness */
ctl.m_iID = ctrlBright; // Control ID.
ctl.m_sName = "Brightness"; // Control name.
ctl.m_iType = 4; // Control type.
ctl.m_iMin = 0; // Minimum control value.
ctl.m_iMax = 100; // Maximum control value.
ctl.m_iStep = 1; // Control value step.
ctl.m_iDefault = 50; // Default value.
ctl.m_iValue = 50; // Current value.
ctl.m_bEnable = true;
ctl.m_bChanged = false;
m_victl.push_back (ctl);
/* Contrast */
ctl.m_iID = ctrlCont; // Control ID.
ctl.m_sName = "Contrast"; // Control name.
ctl.m_iType = 4; // Control type.
ctl.m_iMin = -100; // Minimum control value.
ctl.m_iMax = 100; // Maximum control value.
ctl.m_iStep = 1; // Control value step.
ctl.m_iDefault = 0; // Default value.
ctl.m_iValue = 0; // Current value.
ctl.m_bEnable = true;
ctl.m_bChanged = false;
m_victl.push_back (ctl);
/* Saturation */
ctl.m_iID = ctrlSat; // Control ID.
ctl.m_sName = "Saturation"; // Control name.
ctl.m_iType = 4; // Control type.
ctl.m_iMin = -100; // Minimum control value.
ctl.m_iMax = 100; // Maximum control value.
ctl.m_iStep = 1; // Control value step.
ctl.m_iDefault = 0; // Default value.
ctl.m_iValue = 0; // Current value.
ctl.m_bEnable = true;
ctl.m_bChanged = false;
m_victl.push_back (ctl);
/* Exposure Compensation */
ctl.m_iID = ctrlExpComp; // Control ID.
ctl.m_sName = "Exposure Comp."; // Control name.
ctl.m_iType = 4; // Control type.
ctl.m_iMin = -10; // Minimum control value.
ctl.m_iMax = 10; // Maximum control value.
ctl.m_iStep = 1; // Control value step.
ctl.m_iDefault = 0; // Default value.
ctl.m_iValue = 0; // Current value.
ctl.m_bEnable = false;
ctl.m_bChanged = false;
m_victl.push_back (ctl);
/* White Balance */
ctl.m_iID = ctrlWhiteBal; // Control ID.
ctl.m_sName = "White Balance"; // Control name.
ctl.m_iType = 3; // Control type.
ctl.m_iMin = 0; // Minimum control value.
ctl.m_iMax = 8; // Maximum control value.
ctl.m_iStep = 1; // Control value step.
ctl.m_iDefault = 1; // Default value.
ctl.m_iValue = 1; // Current value.
ctl.m_bEnable = true;
ctl.m_bChanged = false;
ctl.m_vsMenu.push_back (std::string ("Off"));
ctl.m_vsMenu.push_back (std::string ("Auto"));
ctl.m_vsMenu.push_back (std::string ("Incandescent"));
ctl.m_vsMenu.push_back (std::string ("Tungsten"));
ctl.m_vsMenu.push_back (std::string ("Fluorescent"));
ctl.m_vsMenu.push_back (std::string ("Indoor"));
ctl.m_vsMenu.push_back (std::string ("Daylight"));
ctl.m_vsMenu.push_back (std::string ("Cloudy"));
ctl.m_vsMenu.push_back (std::string ("Custom"));
m_victl.push_back (ctl);
ctl.m_vsMenu.clear ();
/* Exposure Mode */
ctl.m_iID = ctrlExMode; // Control ID.
ctl.m_sName = "Exposure Mode"; // Control name.
ctl.m_iType = 3; // Control type.
ctl.m_iMin = 0; // Minimum control value.
ctl.m_iMax = 4; // Maximum control value.
ctl.m_iStep = 1; // Control value step.
ctl.m_iDefault = 1; // Default value.
ctl.m_iValue = 1; // Current value.
ctl.m_bEnable = true;
ctl.m_bChanged = false;
ctl.m_vsMenu.push_back (std::string ("Off"));
ctl.m_vsMenu.push_back (std::string ("Normal"));
ctl.m_vsMenu.push_back (std::string ("Short"));
ctl.m_vsMenu.push_back (std::string ("Long"));
ctl.m_vsMenu.push_back (std::string ("Custom"));
m_victl.push_back (ctl);
ctl.m_vsMenu.clear ();
/* Meter Mode */
ctl.m_iID = ctrlMeterMode; // Control ID.
ctl.m_sName = "Meter Mode"; // Control name.
ctl.m_iType = 3; // Control type.
ctl.m_iMin = 0; // Minimum control value.
ctl.m_iMax = 3; // Maximum control value.
ctl.m_iStep = 1; // Control value step.
ctl.m_iDefault = 0; // Default value.
ctl.m_iValue = 0; // Current value.
ctl.m_bEnable = true;
ctl.m_bChanged = false;
ctl.m_vsMenu.push_back (std::string ("Centre-weighted"));
ctl.m_vsMenu.push_back (std::string ("Spot"));
ctl.m_vsMenu.push_back (std::string ("Matrix"));
ctl.m_vsMenu.push_back (std::string ("Custom"));
m_victl.push_back (ctl);
ctl.m_vsMenu.clear ();
/* Exposure Time */
ctl.m_iID = ctrlExp; // Control ID.
ctl.m_sName = "Exposure Time"; // Control name.
ctl.m_iType = 6; // Control type.
ctl.m_iMin = 0; // Minimum control value.
ctl.m_iMax = 1000000; // Maximum control value.
ctl.m_iStep = 1000; // Control value step.
ctl.m_iDefault = 10000; // Default value.
ctl.m_iValue = 10000; // Current value.
ctl.m_bEnable = false;
ctl.m_bChanged = false;
m_victl.push_back (ctl);
/* Analog Gain */
ctl.m_iID = ctrlAlgGain; // Control ID.
ctl.m_sName = "Analog Gain"; // Control name.
ctl.m_iType = 4; // Control type.
ctl.m_iMin = 0; // Minimum control value.
ctl.m_iMax = 400; // Maximum control value.
ctl.m_iStep = 10; // Control value step.
ctl.m_iDefault = 100; // Default value.
ctl.m_iValue = 100; // Current value.
ctl.m_bEnable = false;
ctl.m_bChanged = false;
m_victl.push_back (ctl);
#if HAVE_DIG_GAIN
/* Digital Gain */
ctl.m_iID = ctrlDigGain; // Control ID.
ctl.m_sName = "Digital Gain"; // Control name.
ctl.m_iType = 4; // Control type.
ctl.m_iMin = 0; // Minimum control value.
ctl.m_iMax = 6400; // Maximum control value.
ctl.m_iStep = 100; // Control value step.
ctl.m_iDefault = 100; // Default value.
ctl.m_iValue = 100; // Current value.
ctl.m_bEnable = false;
ctl.m_bChanged = false;
m_victl.push_back (ctl);
#endif
/* Red Gain */
ctl.m_iID = ctrlRedGain; // Control ID.
ctl.m_sName = "Red Gain"; // Control name.
ctl.m_iType = 4; // Control type.
ctl.m_iMin = 0; // Minimum control value.
ctl.m_iMax = 800; // Maximum control value.
ctl.m_iStep = 10; // Control value step.
ctl.m_iDefault = 100; // Default value.
ctl.m_iValue = 100; // Current value.
ctl.m_bEnable = false;
ctl.m_bChanged = false;
m_victl.push_back (ctl);
/* Blue Gain */
ctl.m_iID = ctrlBlueGain; // Control ID.
ctl.m_sName = "Blue Gain"; // Control name.
ctl.m_iType = 4; // Control type.
ctl.m_iMin = 0; // Minimum control value.
ctl.m_iMax = 800; // Maximum control value.
ctl.m_iStep = 10; // Control value step.
ctl.m_iDefault = 100; // Default value.
ctl.m_iValue = 100; // Current value.
ctl.m_bEnable = false;
ctl.m_bChanged = false;
m_victl.push_back (ctl);
/* Dynamic Noise Reduction */
ctl.m_iID = ctrlDenoise; // Control ID.
ctl.m_sName = "Denoise"; // Control name.
ctl.m_iType = 3; // Control type.
ctl.m_iMin = 0; // Minimum control value.
ctl.m_iMax = 3; // Maximum control value.
ctl.m_iStep = 1; // Control value step.
ctl.m_iDefault = 0; // Default value.
ctl.m_iValue = 0; // Current value.
ctl.m_bEnable = true;
ctl.m_bChanged = false;
ctl.m_vsMenu.push_back (std::string ("Off"));
ctl.m_vsMenu.push_back (std::string ("Low"));
ctl.m_vsMenu.push_back (std::string ("Medium"));
ctl.m_vsMenu.push_back (std::string ("High"));
m_victl.push_back (ctl);
ctl.m_vsMenu.clear ();
/* Image scale */
ctl.m_iID = ctrlScale; // Control ID.
ctl.m_sName = "Image Scale"; // Control name.
ctl.m_iType = 1; // Control type.
ctl.m_iMin = 1; // Minimum control value.
ctl.m_iMax = 5; // Maximum control value.
ctl.m_iStep = 1; // Control value step.
ctl.m_iDefault = 1; // Default value.
ctl.m_iValue = 1; // Current value.
ctl.m_bEnable = true;
ctl.m_bChanged = false;
m_victl.push_back (ctl);
/* Camera Run */
ctl.m_iID = ctrlRun; // Control ID.
ctl.m_sName = "Camera Run"; // Control name.
ctl.m_iType = 2; // Control type.
ctl.m_iMin = 1; // Minimum control value.
ctl.m_iMax = 5; // Maximum control value.
ctl.m_iStep = 1; // Control value step.
ctl.m_iDefault = 1; // Default value.
ctl.m_iValue = 1; // Current value.
ctl.m_bEnable = false;
ctl.m_bChanged = false;
m_victl.push_back (ctl);
}
/*** ApplyControls *************************************************************************************
Apply control settings to camera
WJB 19/ 6/21 First draft
*/
void ControlWnd::ApplyControls (libcamera::ControlList &controls_)
{
controls_.clear ();
/* Brightness */
if ( m_victl[ctrlBright].m_bEnable )
controls_.set(libcamera::controls::Brightness, m_victl[ctrlBright].m_iValue / 50.0 - 1.0);
/* Contrast */
if ( m_victl[ctrlCont].m_bEnable )
controls_.set(libcamera::controls::Contrast, m_victl[ctrlCont].m_iValue / 100.0 + 1.0);
/* Saturation */
if ( m_victl[ctrlSat].m_bEnable )
controls_.set(libcamera::controls::Saturation, m_victl[ctrlSat].m_iValue / 100.0 + 1.0);
/* Exposure Compensation */
if ( m_victl[ctrlExpComp].m_bEnable )
controls_.set(libcamera::controls::ExposureValue, m_victl[ctrlExpComp].m_iValue / 4.0);
/* White Balance */
if ( ( m_victl[ctrlWhiteBal].m_bEnable ) && ( m_victl[ctrlWhiteBal].m_iValue > 0 ) )
{
controls_.set(libcamera::controls::AwbEnable, true);
controls_.set(libcamera::controls::AwbMode, m_victl[ctrlWhiteBal].m_iValue - 1);
}
else
{
controls_.set(libcamera::controls::AwbEnable, false);
}
/* Exposure Mode */
if ( ( m_victl[ctrlExMode].m_bEnable ) && m_victl[ctrlExMode].m_iValue > 0 )
{
controls_.set(libcamera::controls::AeEnable, true);
controls_.set(libcamera::controls::AeExposureMode, m_victl[ctrlExMode].m_iValue - 1);
}
else
{
controls_.set(libcamera::controls::AeEnable, false);
}
/* Meter Mode */
if ( m_victl[ctrlMeterMode].m_bEnable )
controls_.set(libcamera::controls::AeMeteringMode, m_victl[ctrlMeterMode].m_iValue);
/* Exposure Time */
if ( m_victl[ctrlExp].m_bEnable )
controls_.set(libcamera::controls::ExposureTime, m_victl[ctrlExp].m_iValue);
// else controls_.set(libcamera::controls::ExposureTime, 0);
/* Analog Gain */
if ( m_victl[ctrlAlgGain].m_bEnable )
controls_.set(libcamera::controls::AnalogueGain, m_victl[ctrlAlgGain].m_iValue / 100.0);
#if HAVE_DIG_GAIN
/* Digital Gain */
if ( m_victl[ctrlDigGain].m_bEnable )
controls_.set(libcamera::controls::DigitalGain, m_victl[ctrlDigGain].m_iValue / 100.0);
#endif
/* Red & Blue Gains */
if ( ( m_victl[ctrlRedGain].m_bEnable ) && ( m_victl[ctrlBlueGain].m_bEnable ) )
controls_.set(libcamera::controls::ColourGains,
{float(m_victl[ctrlRedGain].m_iValue / 100.0),
float(m_victl[ctrlBlueGain].m_iValue / 100.0)});
else if ( ( m_victl[ctrlWhiteBal].m_bEnable ) && ( m_victl[ctrlWhiteBal].m_iValue > 0 ) )
controls_.set(libcamera::controls::ColourGains, {0.0f, 0.0f});
// fval = picam->awb_gains_r; printf ("awb_gains_r = %10.3E\n", fval);
/* Dynamic noise reduction */
if ( m_victl[ctrlDenoise].m_bEnable )
controls_.set(libcamera::controls::draft::NoiseReductionMode,
libcamera::controls::draft::NoiseReductionModeEnum(m_victl[ctrlDenoise].m_iValue));
}
/*** OnChoice *********************************************************
Update a camera control.
Inputs:
e = Choice event.
Coding history:
WJB 28/ 5/10 First draft.
WJB 4/ 9/11 Revised for separate controls.
*/
void ControlWnd::OnChoice (wxCommandEvent &e)
{
int iCtrl = e.GetId () / 3;
wxChoice * pchc = (wxChoice *) e.GetEventObject ();
ImgCtl * pictl = &m_victl[iCtrl];
int iMin, iMax, iDefault, iValue;
pictl->GetData (iMin, iMax, iDefault, iValue);
iValue = pchc->GetSelection () + iMin;
pictl->Set (iValue);
}
/*** OnCheckBox *********************************************************
Update a camera control.
Inputs:
e = Choice event.
Coding history:
WJB 4/ 9/11 Revised for separate controls.
*/
void ControlWnd::OnCheckBox (wxCommandEvent &e)
{
int iCtrl = e.GetId () / 3;
wxCheckBox *pchk = (wxCheckBox *) e.GetEventObject ();
bool bEnable = pchk->GetValue ();
ImgCtl * pictl = &m_victl[iCtrl];
pictl->Enable (bEnable);
if ( pictl->GetType () == 4 )
{
wxSlider * psld = (wxSlider *) pchk->GetNextSibling ();
wxSpinCtrl *pspin = (wxSpinCtrl *) psld->GetNextSibling ();
psld->Enable (bEnable);
pspin->Enable (bEnable);
}
else if ( pictl->GetType () == 6 )
{
wxSpinCtrl *pspin = (wxSpinCtrl *) pchk->GetNextSibling ();
pspin->Enable (bEnable);
}
if ( iCtrl == ctrlRedGain )
{
m_victl[ctrlBlueGain].m_bEnable = bEnable;
((wxCheckBox *)FindWindow (3 * ctrlBlueGain))->SetValue (bEnable);
FindWindow (3 * ctrlBlueGain + 1)->Enable (bEnable);
FindWindow (3 * ctrlBlueGain + 2)->Enable (bEnable);
}
else if ( iCtrl == ctrlBlueGain )
{
m_victl[ctrlRedGain].m_bEnable = bEnable;
((wxCheckBox *)FindWindow (3 * ctrlRedGain))->SetValue (bEnable);
FindWindow (3 * ctrlRedGain + 1)->Enable (bEnable);
FindWindow (3 * ctrlRedGain + 2)->Enable (bEnable);
}
}
/*** OnSlider *********************************************************
Update a camera control.
Inputs:
e = Choice event.
Coding history:
WJB 4/ 9/11 Revised for separate controls.
WJB 11/ 9/11 Display both slider and spin control.
*/
void ControlWnd::OnSlider (wxCommandEvent &e)
{
int iCtrl = e.GetId () / 3;
wxSlider * psld = (wxSlider *) e.GetEventObject ();
wxSpinCtrl *pspin = (wxSpinCtrl *) psld->GetNextSibling ();
ImgCtl * pictl = &m_victl[iCtrl];
int iVal = psld->GetValue ();
// printf ("OnSlider: this = %p, m_grabimg = %p, iCtrl = %d, pictl = %p, iVal = %d\n",
// this, m_grabimg, iCtrl, pictl, iVal);
pspin->SetValue (iVal);
pictl->Set (iVal);
}
/*** OnSpinCtrl *********************************************************
Update a camera control.
Inputs:
e = Choice event.
Coding history:
WJB 11/ 9/11 Display both slider and spin control.
*/
void ControlWnd::OnSpinCtrl (wxSpinEvent &e)
{
int iCtrl = e.GetId () / 3;
wxSpinCtrl *pspin = (wxSpinCtrl *) e.GetEventObject ();
ImgCtl * pictl = &m_victl[iCtrl];
int iVal = pspin->GetValue ();
// printf ("OnSpinCtrl: this = %p, m_grabimg = %p, iCtrl = %d, pictl = %p, iVal = %d\n",
// this, m_grabimg, iCtrl, pictl, iVal);
pictl->Set (iVal);
if ( pictl->GetType () < 5 )
{
wxSlider * psld = (wxSlider *) pspin->GetPrevSibling ();
psld->SetValue (iVal);
}
}
| 22,412 | 8,559 |
#include <pybind11/pybind11.h>
#include "structures/typedefs.h"
namespace py = pybind11;
void init_enums(py::module_ &m) {
py::enum_<vroom::ROUTER>(m, "ROUTER")
.value("OSRM", vroom::ROUTER::OSRM)
.value("LIBOSRM", vroom::ROUTER::LIBOSRM)
.value("ORS", vroom::ROUTER::ORS)
.value("VALHALLA", vroom::ROUTER::VALHALLA)
.export_values();
py::enum_<vroom::JOB_TYPE>(m, "JOB_TYPE")
.value("SINGLE", vroom::JOB_TYPE::SINGLE)
.value("PICKUP", vroom::JOB_TYPE::PICKUP)
.value("DELIVERY", vroom::JOB_TYPE::DELIVERY)
.export_values();
py::enum_<vroom::STEP_TYPE>(m, "STEP_TYPE")
.value("START", vroom::STEP_TYPE::START)
.value("JOB", vroom::STEP_TYPE::JOB)
.value("BREAK", vroom::STEP_TYPE::BREAK)
.value("END", vroom::STEP_TYPE::END)
.export_values();
py::enum_<vroom::HEURISTIC>(m, "HEURISTIC")
.value("BASIC", vroom::HEURISTIC::BASIC)
.value("DYNAMIC", vroom::HEURISTIC::DYNAMIC)
.value("INIT_ROUTES", vroom::HEURISTIC::INIT_ROUTES)
.export_values();
py::enum_<vroom::INIT>(m, "INIT")
.value("NONE", vroom::INIT::NONE)
.value("HIGHER_AMOUNT", vroom::INIT::HIGHER_AMOUNT)
.value("NEAREST", vroom::INIT::NEAREST)
.value("FURTHEST", vroom::INIT::FURTHEST)
.value("EARLIEST_DEADLINE", vroom::INIT::EARLIEST_DEADLINE)
.export_values();
py::enum_<vroom::VIOLATION>(m, "VIOLATION")
.value("LEAD_TIME", vroom::VIOLATION::LEAD_TIME)
.value("DELAY", vroom::VIOLATION::DELAY)
.value("LOAD", vroom::VIOLATION::LOAD)
.value("MAX_TASKS", vroom::VIOLATION::MAX_TASKS)
.value("SKILLS", vroom::VIOLATION::SKILLS)
.value("PRECEDENCE", vroom::VIOLATION::PRECEDENCE)
.value("MISSING_BREAK", vroom::VIOLATION::MISSING_BREAK)
.export_values();
}
| 1,830 | 790 |
/* Copyright 2021, Gurobi Optimization, LLC */
/* This example reads an LP model from a file and solves it.
If the model is infeasible or unbounded, the example turns off
presolve and solves the model again. If the model is infeasible,
the example computes an Irreducible Inconsistent Subsystem (IIS),
and writes it to a file */
#include "gurobi_c++.h"
using namespace std;
int
main(int argc,
char *argv[])
{
if (argc < 2) {
cout << "Usage: lp_c++ filename" << endl;
return 1;
}
try {
GRBEnv env = GRBEnv();
GRBModel model = GRBModel(env, argv[1]);
model.optimize();
int optimstatus = model.get(GRB_IntAttr_Status);
if (optimstatus == GRB_INF_OR_UNBD) {
model.set(GRB_IntParam_Presolve, 0);
model.optimize();
optimstatus = model.get(GRB_IntAttr_Status);
}
if (optimstatus == GRB_OPTIMAL) {
double objval = model.get(GRB_DoubleAttr_ObjVal);
cout << "Optimal objective: " << objval << endl;
} else if (optimstatus == GRB_INFEASIBLE) {
cout << "Model is infeasible" << endl;
// compute and write out IIS
model.computeIIS();
model.write("model.ilp");
} else if (optimstatus == GRB_UNBOUNDED) {
cout << "Model is unbounded" << endl;
} else {
cout << "Optimization was stopped with status = "
<< optimstatus << endl;
}
} catch(GRBException e) {
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
} catch (...) {
cout << "Error during optimization" << endl;
}
return 0;
}
| 1,585 | 551 |
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "objectdumper.h"
#include <vespa/vespalib/util/stringfmt.h>
namespace vespalib {
void
ObjectDumper::addIndent()
{
int n = _currIndent;
if (n < 0) {
n = 0;
}
_str.append(vespalib::string(n, ' '));
}
void
ObjectDumper::addLine(const vespalib::string &line)
{
addIndent();
_str.append(line);
_str.push_back('\n');
}
void
ObjectDumper::openScope()
{
_currIndent += _indent;
}
void
ObjectDumper::closeScope()
{
_currIndent -= _indent;
}
ObjectDumper::ObjectDumper(int indent)
: _str(),
_indent(indent),
_currIndent(0)
{
}
ObjectDumper::~ObjectDumper() = default;
//-----------------------------------------------------------------------------
void
ObjectDumper::openStruct(const vespalib::string &name, const vespalib::string &type)
{
if (name.empty()) {
addLine(make_string("%s {", type.c_str()));
} else {
addLine(make_string("%s: %s {", name.c_str(), type.c_str()));
}
openScope();
}
void
ObjectDumper::closeStruct()
{
closeScope();
addLine("}");
}
void
ObjectDumper::visitBool(const vespalib::string &name, bool value)
{
addLine(make_string("%s: %s", name.c_str(), value? "true" : "false"));
}
void
ObjectDumper::visitInt(const vespalib::string &name, int64_t value)
{
addLine(make_string("%s: %" PRId64 "", name.c_str(), value));
}
void
ObjectDumper::visitFloat(const vespalib::string &name, double value)
{
addLine(make_string("%s: %g", name.c_str(), value));
}
void
ObjectDumper::visitString(const vespalib::string &name, const vespalib::string &value)
{
addLine(make_string("%s: '%s'", name.c_str(), value.c_str()));
}
void
ObjectDumper::visitNull(const vespalib::string &name)
{
addLine(make_string("%s: <NULL>", name.c_str()));
}
void
ObjectDumper::visitNotImplemented()
{
addLine("<member visit not implemented>");
}
} // namespace vespalib
| 2,002 | 746 |
/*
Copyright (c) 2015 - present Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#pragma once
#include <hsa/amd_hsa_kernel_code.h>
#include <hsa/hsa.h>
#include <hsa/hsa_ext_amd.h>
#include <hsa/hsa_ven_amd_loader.h>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <hip/hip_common.h>
struct ihipModuleSymbol_t;
using hipFunction_t = ihipModuleSymbol_t*;
namespace hip_impl {
// This section contains internal APIs that
// needs to be exported
#ifdef __GNUC__
#pragma GCC visibility push (default)
#endif
struct kernarg_impl;
class kernarg {
public:
kernarg();
kernarg(kernarg&&);
~kernarg();
std::uint8_t* data();
std::size_t size();
void reserve(std::size_t);
void resize(std::size_t);
private:
kernarg_impl* impl;
};
class kernargs_size_align;
class program_state_impl;
class program_state {
public:
program_state();
~program_state();
program_state(const program_state&) = delete;
hipFunction_t kernel_descriptor(std::uintptr_t,
hsa_agent_t);
kernargs_size_align get_kernargs_size_align(std::uintptr_t);
hsa_executable_t load_executable(const char*, const size_t,
hsa_executable_t,
hsa_agent_t);
hsa_executable_t load_executable_no_copy(const char*, const size_t,
hsa_executable_t,
hsa_agent_t);
void* global_addr_by_name(const char* name);
private:
friend class agent_globals_impl;
program_state_impl* impl;
};
class kernargs_size_align {
public:
std::size_t size(std::size_t n) const;
std::size_t alignment(std::size_t n) const;
const void* getHandle() const {return handle;};
private:
const void* handle;
friend kernargs_size_align program_state::get_kernargs_size_align(std::uintptr_t);
};
#ifdef __GNUC__
#pragma GCC visibility pop
#endif
inline
__attribute__((visibility("hidden")))
program_state& get_program_state() {
static program_state ps;
return ps;
}
} // Namespace hip_impl.
| 3,157 | 1,056 |
/*
** Copyright 2011-2013 Centreon
**
** 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.
**
** For more information : contact@centreon.com
*/
#ifndef CCB_CONNECTOR_PLUGIN
#define CCB_CONNECTOR_PLUGIN
#include <list>
#include <map>
#include <string>
#include <sys/types.h>
#include <vector>
#include "com/centreon/benchmark/connector/benchmark.hh"
#include "com/centreon/benchmark/connector/namespace.hh"
CCB_CONNECTOR_BEGIN()
/**
* @class plugin plugin.hh "com/centreon/benchmark/connector/plugin.hh"
* @brief Implementation of benchmark for testing nagios plugin.
*
* This class is an implementation of benchmark for testing nagios
* plugin.
*/
class plugin : public benchmark {
public:
plugin(std::string const& commands_file, std::list<std::string> const& args);
plugin(plugin const& right);
~plugin() throw();
plugin& operator=(plugin const& right);
void run();
private:
void _cleanup();
plugin& _internal_copy(plugin const& right);
void _recv_data(int fd);
void _start_plugin(char** args);
void _wait_plugin(bool block);
std::list<std::string> _args;
std::vector<std::string> _commands;
std::string _commands_file;
unsigned int _current_running;
std::map<pid_t, int> _pid;
};
CCB_CONNECTOR_END()
#endif // !CCB_CONNECTOR_PLUGIN
| 1,789 | 601 |
#pragma once
#include <nall/traits.hpp>
#undef min
#undef max
namespace nall { namespace {
template<typename T, typename U> auto min(const T& t, const U& u) -> T {
return t < u ? t : u;
}
template<typename T, typename U, typename... P> auto min(const T& t, const U& u, P&&... p) -> T {
return t < u ? min(t, forward<P>(p)...) : min(u, forward<P>(p)...);
}
template<typename T, typename U> auto max(const T& t, const U& u) -> T {
return t > u ? t : u;
}
template<typename T, typename U, typename... P> auto max(const T& t, const U& u, P&&... p) -> T {
return t > u ? max(t, forward<P>(p)...) : max(u, forward<P>(p)...);
}
}}
| 640 | 262 |
#pragma once
#include <cmath>
namespace TurtleGraphics {
constexpr float float_epsilon = 0.001f;
constexpr float double_epsilon = 0.00001f;
inline bool ApproxEqual(const float a, const float b) {
return fabs(a - b) < float_epsilon;
}
inline bool ApproxEqual(const double a, const double b) {
return fabs(a - static_cast<long double>(b)) < double_epsilon;
}
inline int Round(const float x) {
return x < 0 ? static_cast<int>(x - 0.5f) : static_cast<int>(x + 0.5f);
}
template <typename Ty>
Ty Clamp(const Ty x, Ty min, Ty max) {
return x < min ? min : x > max ? max : x;
}
} // namespace TurtleGraphics
| 653 | 243 |
//========= Copyright Bernt Andreas Eide, All rights reserved. ============//
//
// Purpose: MP44 / STG44
//
//=============================================================================//
#include "cbase.h"
#include "basehlcombatweapon.h"
#include "NPCevent.h"
#include "basecombatcharacter.h"
#include "AI_BaseNPC.h"
#include "player.h"
#include "game.h"
#include "in_buttons.h"
#include "grenade_ar2.h"
#include "AI_Memory.h"
#include "soundent.h"
#include "rumble_shared.h"
#include "gamestats.h"
#include "te_effect_dispatch.h"
#include "particle_parse.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
class CWeaponSTG44 : public CHLSelectFireMachineGun
{
DECLARE_DATADESC();
public:
DECLARE_CLASS( CWeaponSTG44, CHLSelectFireMachineGun );
CWeaponSTG44();
DECLARE_SERVERCLASS();
void Precache( void );
void AddViewKick( void );
int GetOverloadCapacity() { return 10; }
void ItemPostFrame( void );
int GetMinBurst() { return 2; }
int GetMaxBurst() { return 5; }
virtual void Equip( CBaseCombatCharacter *pOwner );
bool Reload( void );
float GetFireRate( void ) { return 0.100f; }
int CapabilitiesGet( void ) { return bits_CAP_WEAPON_RANGE_ATTACK1; }
virtual const Vector& GetBulletSpread( void )
{
static Vector cone;
if (m_bIsIronsighted)
cone = VECTOR_CONE_1DEGREES;
else
cone = VECTOR_CONE_7DEGREES;
return cone;
}
const WeaponProficiencyInfo_t *GetProficiencyValues();
void FireNPCPrimaryAttack( CBaseCombatCharacter *pOperator, Vector &vecShootOrigin, Vector &vecShootDir );
void Operator_ForceNPCFire( CBaseCombatCharacter *pOperator, bool bSecondary );
void Operator_HandleAnimEvent( animevent_t *pEvent, CBaseCombatCharacter *pOperator );
DECLARE_ACTTABLE();
};
IMPLEMENT_SERVERCLASS_ST(CWeaponSTG44, DT_WeaponSTG44)
END_SEND_TABLE()
LINK_ENTITY_TO_CLASS( weapon_stg44, CWeaponSTG44 );
PRECACHE_WEAPON_REGISTER(weapon_stg44);
BEGIN_DATADESC( CWeaponSTG44 )
END_DATADESC()
acttable_t CWeaponSTG44::m_acttable[] =
{
{ ACT_RANGE_ATTACK1, ACT_RANGE_ATTACK_SMG1, true },
{ ACT_RELOAD, ACT_RELOAD_SMG1, true },
{ ACT_IDLE, ACT_IDLE_SMG1, true },
{ ACT_IDLE_ANGRY, ACT_IDLE_ANGRY_SMG1, true },
{ ACT_WALK, ACT_WALK_RIFLE, true },
{ ACT_WALK_AIM, ACT_WALK_AIM_RIFLE, true },
// Readiness activities (not aiming)
{ ACT_IDLE_RELAXED, ACT_IDLE_SMG1_RELAXED, false },//never aims
{ ACT_IDLE_STIMULATED, ACT_IDLE_SMG1_STIMULATED, false },
{ ACT_IDLE_AGITATED, ACT_IDLE_ANGRY_SMG1, false },//always aims
{ ACT_WALK_RELAXED, ACT_WALK_RIFLE_RELAXED, false },//never aims
{ ACT_WALK_STIMULATED, ACT_WALK_RIFLE_STIMULATED, false },
{ ACT_WALK_AGITATED, ACT_WALK_AIM_RIFLE, false },//always aims
{ ACT_RUN_RELAXED, ACT_RUN_RIFLE_RELAXED, false },//never aims
{ ACT_RUN_STIMULATED, ACT_RUN_RIFLE_STIMULATED, false },
{ ACT_RUN_AGITATED, ACT_RUN_AIM_RIFLE, false },//always aims
// Readiness activities (aiming)
{ ACT_IDLE_AIM_RELAXED, ACT_IDLE_SMG1_RELAXED, false },//never aims
{ ACT_IDLE_AIM_STIMULATED, ACT_IDLE_AIM_RIFLE_STIMULATED, false },
{ ACT_IDLE_AIM_AGITATED, ACT_IDLE_ANGRY_SMG1, false },//always aims
{ ACT_WALK_AIM_RELAXED, ACT_WALK_RIFLE_RELAXED, false },//never aims
{ ACT_WALK_AIM_STIMULATED, ACT_WALK_AIM_RIFLE_STIMULATED, false },
{ ACT_WALK_AIM_AGITATED, ACT_WALK_AIM_RIFLE, false },//always aims
{ ACT_RUN_AIM_RELAXED, ACT_RUN_RIFLE_RELAXED, false },//never aims
{ ACT_RUN_AIM_STIMULATED, ACT_RUN_AIM_RIFLE_STIMULATED, false },
{ ACT_RUN_AIM_AGITATED, ACT_RUN_AIM_RIFLE, false },//always aims
//End readiness activities
{ ACT_WALK_AIM, ACT_WALK_AIM_RIFLE, true },
{ ACT_WALK_CROUCH, ACT_WALK_CROUCH_RIFLE, true },
{ ACT_WALK_CROUCH_AIM, ACT_WALK_CROUCH_AIM_RIFLE, true },
{ ACT_RUN, ACT_RUN_RIFLE, true },
{ ACT_RUN_AIM, ACT_RUN_AIM_RIFLE, true },
{ ACT_RUN_CROUCH, ACT_RUN_CROUCH_RIFLE, true },
{ ACT_RUN_CROUCH_AIM, ACT_RUN_CROUCH_AIM_RIFLE, true },
{ ACT_GESTURE_RANGE_ATTACK1, ACT_GESTURE_RANGE_ATTACK_SMG1, true },
{ ACT_RANGE_ATTACK1_LOW, ACT_RANGE_ATTACK_SMG1_LOW, true },
{ ACT_COVER_LOW, ACT_COVER_SMG1_LOW, false },
{ ACT_RANGE_AIM_LOW, ACT_RANGE_AIM_SMG1_LOW, false },
{ ACT_RELOAD_LOW, ACT_RELOAD_SMG1_LOW, false },
{ ACT_GESTURE_RELOAD, ACT_GESTURE_RELOAD_SMG1, true },
{ ACT_HL2MP_IDLE, ACT_HL2MP_IDLE_SMG1, false },
{ ACT_HL2MP_RUN, ACT_HL2MP_RUN_SMG1, false },
{ ACT_HL2MP_IDLE_CROUCH, ACT_HL2MP_IDLE_CROUCH_SMG1, false },
{ ACT_HL2MP_WALK_CROUCH, ACT_HL2MP_WALK_CROUCH_SMG1, false },
{ ACT_HL2MP_GESTURE_RANGE_ATTACK, ACT_HL2MP_GESTURE_RANGE_ATTACK_SMG1, false },
{ ACT_HL2MP_GESTURE_RELOAD, ACT_GESTURE_RELOAD_SMG1, false },
{ ACT_HL2MP_JUMP, ACT_HL2MP_JUMP_SMG1, false },
{ ACT_RANGE_ATTACK1, ACT_RANGE_ATTACK_SMG1, false },
};
IMPLEMENT_ACTTABLE(CWeaponSTG44);
//=========================================================
CWeaponSTG44::CWeaponSTG44( )
{
m_fMinRange1 = 0;// No minimum range.
m_fMaxRange1 = 1400;
m_bMagazineStyleReloads = true; // Magazine style reloads
m_bAltFiresUnderwater = false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CWeaponSTG44::Precache( void )
{
BaseClass::Precache();
}
//-----------------------------------------------------------------------------
// Purpose: Give this weapon longer range when wielded by an ally NPC.
//-----------------------------------------------------------------------------
void CWeaponSTG44::Equip( CBaseCombatCharacter *pOwner )
{
if( pOwner->Classify() == CLASS_PLAYER_ALLY )
{
m_fMaxRange1 = 3000;
}
else
{
m_fMaxRange1 = 1400;
}
BaseClass::Equip( pOwner );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CWeaponSTG44::FireNPCPrimaryAttack( CBaseCombatCharacter *pOperator, Vector &vecShootOrigin, Vector &vecShootDir )
{
// FIXME: use the returned number of bullets to account for >10hz firerate
WeaponSoundRealtime( SINGLE_NPC );
CSoundEnt::InsertSound( SOUND_COMBAT|SOUND_CONTEXT_GUNFIRE, pOperator->GetAbsOrigin(), SOUNDENT_VOLUME_MACHINEGUN, 0.2, pOperator, SOUNDENT_CHANNEL_WEAPON, pOperator->GetEnemy() );
pOperator->FireBullets( 1, vecShootOrigin, vecShootDir, VECTOR_CONE_PRECALCULATED,
MAX_TRACE_LENGTH, m_iPrimaryAmmoType, 2, entindex(), 0 );
pOperator->DoMuzzleFlash();
m_iClip1 = m_iClip1 - 1;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CWeaponSTG44::Operator_ForceNPCFire( CBaseCombatCharacter *pOperator, bool bSecondary )
{
// Ensure we have enough rounds in the clip
m_iClip1++;
Vector vecShootOrigin, vecShootDir;
QAngle angShootDir;
GetAttachment( LookupAttachment( "muzzle" ), vecShootOrigin, angShootDir );
AngleVectors( angShootDir, &vecShootDir );
FireNPCPrimaryAttack( pOperator, vecShootOrigin, vecShootDir );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CWeaponSTG44::Operator_HandleAnimEvent( animevent_t *pEvent, CBaseCombatCharacter *pOperator )
{
switch( pEvent->event )
{
case EVENT_WEAPON_SMG1:
{
Vector vecShootOrigin, vecShootDir;
QAngle angDiscard;
// Support old style attachment point firing
if ((pEvent->options == NULL) || (pEvent->options[0] == '\0') || (!pOperator->GetAttachment(pEvent->options, vecShootOrigin, angDiscard)))
{
vecShootOrigin = pOperator->Weapon_ShootPosition();
}
CAI_BaseNPC *npc = pOperator->MyNPCPointer();
ASSERT( npc != NULL );
vecShootDir = npc->GetActualShootTrajectory( vecShootOrigin );
FireNPCPrimaryAttack( pOperator, vecShootOrigin, vecShootDir );
}
break;
default:
BaseClass::Operator_HandleAnimEvent( pEvent, pOperator );
break;
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CWeaponSTG44::Reload( void )
{
bool fRet;
float fCacheTime = m_flNextSecondaryAttack;
fRet = DefaultReload( GetMaxClip1(), GetMaxClip2(), ACT_VM_RELOAD );
if ( fRet )
{
// Undo whatever the reload process has done to our secondary
// attack timer. We allow you to interrupt reloading to fire
// a grenade.
m_flNextSecondaryAttack = GetOwner()->m_flNextAttack = fCacheTime;
WeaponSound( RELOAD );
CBasePlayer *pOwner = ToBasePlayer( GetOwner() );
CEffectData data;
data.m_vOrigin = pOwner->WorldSpaceCenter() + RandomVector( 0, 0 );
data.m_vAngles = QAngle( 90, random->RandomInt( 0, 360 ), 0 );
data.m_nEntIndex = entindex();
DispatchEffect( "ClipEject", data );
}
return fRet;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CWeaponSTG44::AddViewKick( void )
{
#define EASY_DAMPEN 0.5f
#define MAX_VERTICAL_KICK 1.0f //Degrees
#define SLIDE_LIMIT 2.0f //Seconds
//Get the view kick
CBasePlayer *pPlayer = ToBasePlayer( GetOwner() );
if ( pPlayer == NULL )
return;
DoMachineGunKick( pPlayer, EASY_DAMPEN, MAX_VERTICAL_KICK, m_fFireDuration, SLIDE_LIMIT );
}
void CWeaponSTG44::ItemPostFrame( void )
{
BaseClass::ItemPostFrame();
CBasePlayer *pPlayer = ToBasePlayer( GetOwner() );
if ( pPlayer == NULL )
return;
// Ammo Fix
int CurrAmmo = pPlayer->GetAmmoCount(m_iPrimaryAmmoType);
if ( CurrAmmo <= 29 && CurrAmmo >= 1 )
{
pPlayer->RemoveAmmo( CurrAmmo, m_iPrimaryAmmoType );
}
}
//----------------------------------------------------------------------------
const WeaponProficiencyInfo_t *CWeaponSTG44::GetProficiencyValues()
{
static WeaponProficiencyInfo_t proficiencyTable[] =
{
{ 7.0, 0.75 },
{ 5.00, 0.75 },
{ 10.0/3.0, 0.75 },
{ 5.0/3.0, 0.75 },
{ 1.00, 1.0 },
};
COMPILE_TIME_ASSERT( ARRAYSIZE(proficiencyTable) == WEAPON_PROFICIENCY_PERFECT + 1);
return proficiencyTable;
} | 10,582 | 4,598 |
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "DemoPage.h"
#include <VGUI/IVGui.h>
#include <vgui_controls/Controls.h>
#include <Keyvalues.h>
#include <vgui_controls/Button.h>
#include <vgui_controls/QueryBox.h>
using namespace vgui;
// Query boxes are windows that pop up in response to events.
// They are useful for asking questions (like... "Are you sure you want to do this?").
// In this example we will trigger the opening of a query box when
// a button is pressed.
// Query boxes are Message boxes that have an OK and a Cancel button,
// each button may be linked to an additional command in order to trigger an
// appropriate response.
class QueryBoxDemo: public DemoPage
{
public:
QueryBoxDemo(Panel *parent, const char *name);
~QueryBoxDemo();
void OnButtonClicked();
void ShowQueryBox();
void OnOK();
void OnCancel();
private:
Button *m_pButton;
DECLARE_PANELMAP();
};
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
QueryBoxDemo::QueryBoxDemo(Panel *parent, const char *name) : DemoPage(parent, name)
{
// Create a button to trigger the message box.
m_pButton = new Button(this, "AButton", "Click Me For A Question");
// Size the button to its text.
m_pButton->SizeToContents();
// Set its position.
m_pButton->SetPos(100, 100);
// Install a command that will be executed when the button is pressed
// Here we use a KeyValues command, this is mapped using the Message map
// below to a function.
m_pButton->SetCommand(new KeyValues ("ButtonClicked"));
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
QueryBoxDemo::~QueryBoxDemo()
{
}
//-----------------------------------------------------------------------------
// Purpose: Respond to a message based action signal
// Popup the query box.
//-----------------------------------------------------------------------------
void QueryBoxDemo::OnButtonClicked()
{
ivgui()->DPrintf("Button was clicked.\n");
// When the button is clicked we open the message box in response.
ShowQueryBox();
}
//-----------------------------------------------------------------------------
// Purpose: Display a query box
//-----------------------------------------------------------------------------
void QueryBoxDemo::ShowQueryBox()
{
// create a new message box.
// The first arg is the name of the window and will be across the top.
// The second arg is the text that will appear in the message box.
QueryBox *pQuery = new QueryBox ("Message Window", "Will you pick OK or Cancel?");
// Make ourselves the target of the button messages
pQuery->AddActionSignalTarget(this);
// Install the message to be sent when the ok button is clicked.
pQuery->SetOKCommand(new KeyValues("OKClicked"));
// Install the message to be sent when the cancel button is clicked.
pQuery->SetCancelCommand(new KeyValues("Cancel"));
// This command will pop up the message box and hold it there until we click
// a button. When a button is clicked the query box object is destroyed.
pQuery->DoModal();
}
//-----------------------------------------------------------------------------
// Purpose: Respond to a message based action signal
// Respond to the OK button in the query box.
//-----------------------------------------------------------------------------
void QueryBoxDemo::OnOK()
{
ivgui()->DPrintf("Query received the OK.\n");
}
//-----------------------------------------------------------------------------
// Purpose: Respond to a message based action signal
// Respond to the Cancel button in the query box
//-----------------------------------------------------------------------------
void QueryBoxDemo::OnCancel()
{
ivgui()->DPrintf("Query was canceled.\n");
}
MessageMapItem_t QueryBoxDemo::m_MessageMap[] =
{
MAP_MESSAGE( QueryBoxDemo, "ButtonClicked", OnButtonClicked ),
MAP_MESSAGE( QueryBoxDemo, "OKClicked", OnOK ),
MAP_MESSAGE( QueryBoxDemo, "Cancel", OnCancel ),
};
IMPLEMENT_PANELMAP(QueryBoxDemo, DemoPage);
Panel* QueryBoxDemo_Create(Panel *parent)
{
return new QueryBoxDemo(parent, "QueryBoxDemo");
}
| 4,488 | 1,202 |
# /* **************************************************************************
# * *
# * (C) Copyright Paul Mensonides 2002.
# * Distributed under the Boost Software License, Version 1.0. (See
# * accompanying file LICENSE_1_0.txt or copy at
# * http://www.boost.org/LICENSE_1_0.txt)
# * *
# ************************************************************************** */
#
# /* See http://www.boost.org for most recent version. */
#
# ifndef MSGPACK_PREPROCESSOR_ITERATION_ITERATE_HPP
# define MSGPACK_PREPROCESSOR_ITERATION_ITERATE_HPP
#
# include <msgpack/preprocessor/arithmetic/dec.hpp>
# include <msgpack/preprocessor/arithmetic/inc.hpp>
# include <msgpack/preprocessor/array/elem.hpp>
# include <msgpack/preprocessor/array/size.hpp>
# include <msgpack/preprocessor/cat.hpp>
# include <msgpack/preprocessor/slot/slot.hpp>
# include <msgpack/preprocessor/tuple/elem.hpp>
#
# /* MSGPACK_PP_ITERATION_DEPTH */
#
# define MSGPACK_PP_ITERATION_DEPTH() 0
#
# /* MSGPACK_PP_ITERATION */
#
# define MSGPACK_PP_ITERATION() MSGPACK_PP_CAT(MSGPACK_PP_ITERATION_, MSGPACK_PP_ITERATION_DEPTH())
#
# /* MSGPACK_PP_ITERATION_START && MSGPACK_PP_ITERATION_FINISH */
#
# define MSGPACK_PP_ITERATION_START() MSGPACK_PP_CAT(MSGPACK_PP_ITERATION_START_, MSGPACK_PP_ITERATION_DEPTH())
# define MSGPACK_PP_ITERATION_FINISH() MSGPACK_PP_CAT(MSGPACK_PP_ITERATION_FINISH_, MSGPACK_PP_ITERATION_DEPTH())
#
# /* MSGPACK_PP_ITERATION_FLAGS */
#
# define MSGPACK_PP_ITERATION_FLAGS() (MSGPACK_PP_CAT(MSGPACK_PP_ITERATION_FLAGS_, MSGPACK_PP_ITERATION_DEPTH())())
#
# /* MSGPACK_PP_FRAME_ITERATION */
#
# define MSGPACK_PP_FRAME_ITERATION(i) MSGPACK_PP_CAT(MSGPACK_PP_ITERATION_, i)
#
# /* MSGPACK_PP_FRAME_START && MSGPACK_PP_FRAME_FINISH */
#
# define MSGPACK_PP_FRAME_START(i) MSGPACK_PP_CAT(MSGPACK_PP_ITERATION_START_, i)
# define MSGPACK_PP_FRAME_FINISH(i) MSGPACK_PP_CAT(MSGPACK_PP_ITERATION_FINISH_, i)
#
# /* MSGPACK_PP_FRAME_FLAGS */
#
# define MSGPACK_PP_FRAME_FLAGS(i) (MSGPACK_PP_CAT(MSGPACK_PP_ITERATION_FLAGS_, i)())
#
# /* MSGPACK_PP_RELATIVE_ITERATION */
#
# define MSGPACK_PP_RELATIVE_ITERATION(i) MSGPACK_PP_CAT(MSGPACK_PP_RELATIVE_, i)(MSGPACK_PP_ITERATION_)
#
# define MSGPACK_PP_RELATIVE_0(m) MSGPACK_PP_CAT(m, MSGPACK_PP_ITERATION_DEPTH())
# define MSGPACK_PP_RELATIVE_1(m) MSGPACK_PP_CAT(m, MSGPACK_PP_DEC(MSGPACK_PP_ITERATION_DEPTH()))
# define MSGPACK_PP_RELATIVE_2(m) MSGPACK_PP_CAT(m, MSGPACK_PP_DEC(MSGPACK_PP_DEC(MSGPACK_PP_ITERATION_DEPTH())))
# define MSGPACK_PP_RELATIVE_3(m) MSGPACK_PP_CAT(m, MSGPACK_PP_DEC(MSGPACK_PP_DEC(MSGPACK_PP_DEC(MSGPACK_PP_ITERATION_DEPTH()))))
# define MSGPACK_PP_RELATIVE_4(m) MSGPACK_PP_CAT(m, MSGPACK_PP_DEC(MSGPACK_PP_DEC(MSGPACK_PP_DEC(MSGPACK_PP_DEC(MSGPACK_PP_ITERATION_DEPTH())))))
#
# /* MSGPACK_PP_RELATIVE_START && MSGPACK_PP_RELATIVE_FINISH */
#
# define MSGPACK_PP_RELATIVE_START(i) MSGPACK_PP_CAT(MSGPACK_PP_RELATIVE_, i)(MSGPACK_PP_ITERATION_START_)
# define MSGPACK_PP_RELATIVE_FINISH(i) MSGPACK_PP_CAT(MSGPACK_PP_RELATIVE_, i)(MSGPACK_PP_ITERATION_FINISH_)
#
# /* MSGPACK_PP_RELATIVE_FLAGS */
#
# define MSGPACK_PP_RELATIVE_FLAGS(i) (MSGPACK_PP_CAT(MSGPACK_PP_RELATIVE_, i)(MSGPACK_PP_ITERATION_FLAGS_)())
#
# /* MSGPACK_PP_ITERATE */
#
# define MSGPACK_PP_ITERATE() MSGPACK_PP_CAT(MSGPACK_PP_ITERATE_, MSGPACK_PP_INC(MSGPACK_PP_ITERATION_DEPTH()))
#
# define MSGPACK_PP_ITERATE_1 <msgpack/preprocessor/iteration/detail/iter/forward1.hpp>
# define MSGPACK_PP_ITERATE_2 <msgpack/preprocessor/iteration/detail/iter/forward2.hpp>
# define MSGPACK_PP_ITERATE_3 <msgpack/preprocessor/iteration/detail/iter/forward3.hpp>
# define MSGPACK_PP_ITERATE_4 <msgpack/preprocessor/iteration/detail/iter/forward4.hpp>
# define MSGPACK_PP_ITERATE_5 <msgpack/preprocessor/iteration/detail/iter/forward5.hpp>
#
# endif
| 4,004 | 1,760 |
// Generated by Haxe 4.1.5
#include <hxcpp.h>
#ifndef INCLUDED___ASSET__flixel_flixel_ui_img_finger_small_png
#include <__ASSET__flixel_flixel_ui_img_finger_small_png.h>
#endif
#ifndef INCLUDED_haxe_Resource
#include <haxe/Resource.h>
#endif
#ifndef INCLUDED_haxe_io_Bytes
#include <haxe/io/Bytes.h>
#endif
#ifndef INCLUDED_lime_graphics_Image
#include <lime/graphics/Image.h>
#endif
#ifndef INCLUDED_lime_graphics_ImageBuffer
#include <lime/graphics/ImageBuffer.h>
#endif
#ifndef INCLUDED_lime_graphics_ImageType
#include <lime/graphics/ImageType.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_a8b28c08cd7936ec_346_new,"__ASSET__flixel_flixel_ui_img_finger_small_png","new",0x4e817064,"__ASSET__flixel_flixel_ui_img_finger_small_png.new","lime/_internal/macros/AssetsMacro.hx",346,0xc651f030)
HX_LOCAL_STACK_FRAME(_hx_pos_db845bbd0c26ed3d_600_boot,"__ASSET__flixel_flixel_ui_img_finger_small_png","boot",0x5ad9e7ae,"__ASSET__flixel_flixel_ui_img_finger_small_png.boot","ManifestResources.hx",600,0xf77aa668)
void __ASSET__flixel_flixel_ui_img_finger_small_png_obj::__construct( ::lime::graphics::ImageBuffer buffer, ::Dynamic offsetX, ::Dynamic offsetY, ::Dynamic width, ::Dynamic height, ::Dynamic color, ::lime::graphics::ImageType type){
HX_STACKFRAME(&_hx_pos_a8b28c08cd7936ec_346_new)
HXLINE( 375) super::__construct(null(),null(),null(),null(),null(),null(),null());
HXLINE( 377) this->_hx___fromBytes(::haxe::Resource_obj::getBytes(::__ASSET__flixel_flixel_ui_img_finger_small_png_obj::resourceName),null());
}
Dynamic __ASSET__flixel_flixel_ui_img_finger_small_png_obj::__CreateEmpty() { return new __ASSET__flixel_flixel_ui_img_finger_small_png_obj; }
void *__ASSET__flixel_flixel_ui_img_finger_small_png_obj::_hx_vtable = 0;
Dynamic __ASSET__flixel_flixel_ui_img_finger_small_png_obj::__Create(::hx::DynamicArray inArgs)
{
::hx::ObjectPtr< __ASSET__flixel_flixel_ui_img_finger_small_png_obj > _hx_result = new __ASSET__flixel_flixel_ui_img_finger_small_png_obj();
_hx_result->__construct(inArgs[0],inArgs[1],inArgs[2],inArgs[3],inArgs[4],inArgs[5],inArgs[6]);
return _hx_result;
}
bool __ASSET__flixel_flixel_ui_img_finger_small_png_obj::_hx_isInstanceOf(int inClassId) {
if (inClassId<=(int)0x33f052f7) {
return inClassId==(int)0x00000001 || inClassId==(int)0x33f052f7;
} else {
return inClassId==(int)0x57173132;
}
}
::String __ASSET__flixel_flixel_ui_img_finger_small_png_obj::resourceName;
::hx::ObjectPtr< __ASSET__flixel_flixel_ui_img_finger_small_png_obj > __ASSET__flixel_flixel_ui_img_finger_small_png_obj::__new( ::lime::graphics::ImageBuffer buffer, ::Dynamic offsetX, ::Dynamic offsetY, ::Dynamic width, ::Dynamic height, ::Dynamic color, ::lime::graphics::ImageType type) {
::hx::ObjectPtr< __ASSET__flixel_flixel_ui_img_finger_small_png_obj > __this = new __ASSET__flixel_flixel_ui_img_finger_small_png_obj();
__this->__construct(buffer,offsetX,offsetY,width,height,color,type);
return __this;
}
::hx::ObjectPtr< __ASSET__flixel_flixel_ui_img_finger_small_png_obj > __ASSET__flixel_flixel_ui_img_finger_small_png_obj::__alloc(::hx::Ctx *_hx_ctx, ::lime::graphics::ImageBuffer buffer, ::Dynamic offsetX, ::Dynamic offsetY, ::Dynamic width, ::Dynamic height, ::Dynamic color, ::lime::graphics::ImageType type) {
__ASSET__flixel_flixel_ui_img_finger_small_png_obj *__this = (__ASSET__flixel_flixel_ui_img_finger_small_png_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(__ASSET__flixel_flixel_ui_img_finger_small_png_obj), true, "__ASSET__flixel_flixel_ui_img_finger_small_png"));
*(void **)__this = __ASSET__flixel_flixel_ui_img_finger_small_png_obj::_hx_vtable;
__this->__construct(buffer,offsetX,offsetY,width,height,color,type);
return __this;
}
__ASSET__flixel_flixel_ui_img_finger_small_png_obj::__ASSET__flixel_flixel_ui_img_finger_small_png_obj()
{
}
bool __ASSET__flixel_flixel_ui_img_finger_small_png_obj::__GetStatic(const ::String &inName, Dynamic &outValue, ::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 12:
if (HX_FIELD_EQ(inName,"resourceName") ) { outValue = ( resourceName ); return true; }
}
return false;
}
bool __ASSET__flixel_flixel_ui_img_finger_small_png_obj::__SetStatic(const ::String &inName,Dynamic &ioValue,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 12:
if (HX_FIELD_EQ(inName,"resourceName") ) { resourceName=ioValue.Cast< ::String >(); return true; }
}
return false;
}
#ifdef HXCPP_SCRIPTABLE
static ::hx::StorageInfo *__ASSET__flixel_flixel_ui_img_finger_small_png_obj_sMemberStorageInfo = 0;
static ::hx::StaticInfo __ASSET__flixel_flixel_ui_img_finger_small_png_obj_sStaticStorageInfo[] = {
{::hx::fsString,(void *) &__ASSET__flixel_flixel_ui_img_finger_small_png_obj::resourceName,HX_("resourceName",39,7a,62,90)},
{ ::hx::fsUnknown, 0, null()}
};
#endif
static void __ASSET__flixel_flixel_ui_img_finger_small_png_obj_sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(__ASSET__flixel_flixel_ui_img_finger_small_png_obj::resourceName,"resourceName");
};
#ifdef HXCPP_VISIT_ALLOCS
static void __ASSET__flixel_flixel_ui_img_finger_small_png_obj_sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(__ASSET__flixel_flixel_ui_img_finger_small_png_obj::resourceName,"resourceName");
};
#endif
::hx::Class __ASSET__flixel_flixel_ui_img_finger_small_png_obj::__mClass;
static ::String __ASSET__flixel_flixel_ui_img_finger_small_png_obj_sStaticFields[] = {
HX_("resourceName",39,7a,62,90),
::String(null())
};
void __ASSET__flixel_flixel_ui_img_finger_small_png_obj::__register()
{
__ASSET__flixel_flixel_ui_img_finger_small_png_obj _hx_dummy;
__ASSET__flixel_flixel_ui_img_finger_small_png_obj::_hx_vtable = *(void **)&_hx_dummy;
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("__ASSET__flixel_flixel_ui_img_finger_small_png",72,ae,28,1f);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &__ASSET__flixel_flixel_ui_img_finger_small_png_obj::__GetStatic;
__mClass->mSetStaticField = &__ASSET__flixel_flixel_ui_img_finger_small_png_obj::__SetStatic;
__mClass->mMarkFunc = __ASSET__flixel_flixel_ui_img_finger_small_png_obj_sMarkStatics;
__mClass->mStatics = ::hx::Class_obj::dupFunctions(__ASSET__flixel_flixel_ui_img_finger_small_png_obj_sStaticFields);
__mClass->mMembers = ::hx::Class_obj::dupFunctions(0 /* sMemberFields */);
__mClass->mCanCast = ::hx::TCanCast< __ASSET__flixel_flixel_ui_img_finger_small_png_obj >;
#ifdef HXCPP_VISIT_ALLOCS
__mClass->mVisitFunc = __ASSET__flixel_flixel_ui_img_finger_small_png_obj_sVisitStatics;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = __ASSET__flixel_flixel_ui_img_finger_small_png_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = __ASSET__flixel_flixel_ui_img_finger_small_png_obj_sStaticStorageInfo;
#endif
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
void __ASSET__flixel_flixel_ui_img_finger_small_png_obj::__boot()
{
{
HX_STACKFRAME(&_hx_pos_db845bbd0c26ed3d_600_boot)
HXDLIN( 600) resourceName = HX_("__ASSET__:image___ASSET__flixel_flixel_ui_img_finger_small_png",80,fb,be,f7);
}
}
| 7,226 | 3,236 |
/* GRAPHITE2 LICENSING
Copyright 2010, SIL International
All rights reserved.
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; either version 2.1 of 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 also have received a copy of the GNU Lesser General Public
License along with this library in the file named "LICENSE".
If not, write to the Free Software Foundation, 51 Franklin Street,
Suite 500, Boston, MA 02110-1335, USA or visit their web page on the
internet at http://www.fsf.org/licenses/lgpl.html.
Alternatively, the contents of this file may be used under the terms of the
Mozilla Public License (http://mozilla.org/MPL) or 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.
*/
#include <cassert>
#include "graphite2/Segment.h"
#include "inc/CharInfo.h"
extern "C"
{
unsigned int gr_cinfo_unicode_char(const gr_char_info* p/*not NULL*/)
{
assert(p);
return p->unicodeChar();
}
int gr_cinfo_break_weight(const gr_char_info* p/*not NULL*/)
{
assert(p);
return p->breakWeight();
}
int gr_cinfo_after(const gr_char_info *p/*not NULL*/)
{
assert(p);
return p->after();
}
int gr_cinfo_before(const gr_char_info *p/*not NULL*/)
{
assert(p);
return p->before();
}
size_t gr_cinfo_base(const gr_char_info *p/*not NULL*/)
{
assert(p);
return p->base();
}
} // extern "C"
| 1,858 | 616 |
#if !defined(SIP0X_PARSER_TOKENSIPVERSION_HPP__)
#define SIP0X_PARSER_TOKENSIPVERSION_HPP__
#include "parser/tokens/TokenAbstract.hpp"
#include "parser/tokens/Operators.hpp"
#include "parser/tokens/Token.hpp"
#include "parser/tokens/TokenRegex.hpp"
#include "parser/factory/FactoryContextSIPVersion.hpp"
namespace sip0x
{
namespace parser
{
// SIP-Version = "SIP" "/" 1*DIGIT "." 1*DIGIT
class TokenSIPVersion : public TokenAbstract {
protected:
Sequence<Token, TokenDigits, Token, TokenDigits> _sequence;
public:
TokenSIPVersion(void) : TokenAbstract("SIPVersion"),
_sequence(Token("SIP/"), TokenDigits(), Token("."), TokenDigits())
{
_sequence.disable_factory(true);
}
virtual ~TokenSIPVersion(void) { }
protected:
virtual ParserResult handle_read(sip0x::utils::InputTokenStream& iss, FactoryContext* ctx) const override {
return _sequence.read(iss, ctx);
}
virtual FactoryContext* create_factory(void) const override {
return new FactoryContextSIPVersion();
}
};
}
}
#endif // SIP0X_PARSER_TOKENSIPVERSION_HPP__
| 1,151 | 393 |
// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban
// =============================================================================
//
// Demo code about collisions and contacts using the penalty method (SMC)
//
// =============================================================================
#include "chrono/physics/ChSystemSMC.h"
#include "chrono/physics/ChContactContainerSMC.h"
#include "chrono_irrlicht/ChIrrApp.h"
#include <irrlicht.h>
// Use the namespaces of Chrono
using namespace chrono;
using namespace chrono::irrlicht;
// Use the main namespaces of Irrlicht
using namespace irr;
using namespace irr::core;
using namespace irr::scene;
using namespace irr::video;
using namespace irr::io;
using namespace irr::gui;
void AddWall(std::shared_ptr<ChBody> body, const ChVector<>& dim, const ChVector<>& loc, std::shared_ptr<ChMaterialSurface> mat) {
body->GetCollisionModel()->AddBox(mat, dim.x(), dim.y(), dim.z(), loc);
auto box = chrono_types::make_shared<ChBoxShape>();
box->GetBoxGeometry().Size = dim;
box->GetBoxGeometry().Pos = loc;
box->SetColor(ChColor(1, 0, 0));
box->SetFading(0.6f);
body->AddAsset(box);
}
int main(int argc, char* argv[]) {
GetLog() << "Copyright (c) 2017 projectchrono.org\nChrono version: " << CHRONO_VERSION << "\n\n";
// Simulation parameters
double gravity = -9.81;
double time_step = 0.00001;
double out_step = 2000 * time_step;
// Parameters for the falling ball
int ballId = 100;
double radius = 1;
double mass = 1000;
ChVector<> pos(0, 2, 0);
ChQuaternion<> rot(1, 0, 0, 0);
ChVector<> init_vel(0, 0, 0);
// Parameters for the containing bin
int binId = 200;
double width = 2;
double length = 2;
double height = 1;
double thickness = 0.1;
// Create the system
ChSystemSMC msystem;
// The following two lines are optional, since they are the default options. They are added for future reference,
// i.e. when needed to change those models.
msystem.SetContactForceModel(ChSystemSMC::ContactForceModel::Hertz);
msystem.SetAdhesionForceModel(ChSystemSMC::AdhesionForceModel::Constant);
msystem.Set_G_acc(ChVector<>(0, gravity, 0));
// Change the default collision effective radius of curvature
collision::ChCollisionInfo::SetDefaultEffectiveCurvatureRadius(1);
// Create the Irrlicht visualization
ChIrrApp application(&msystem, L"SMC demo", core::dimension2d<u32>(800, 600));
// Easy shortcuts to add camera, lights, logo and sky in Irrlicht scene
application.AddTypicalLogo();
application.AddTypicalSky();
application.AddTypicalLights();
application.AddTypicalCamera(core::vector3df(0, 3, -6));
// This means that contactforces will be shown in Irrlicht application
application.SetSymbolscale(1e-4);
application.SetContactsDrawMode(IrrContactsDrawMode::CONTACT_FORCES);
// Create a material (will be used by both objects)
auto material = chrono_types::make_shared<ChMaterialSurfaceSMC>();
material->SetRestitution(0.1f);
material->SetFriction(0.4f);
material->SetAdhesion(0); // Magnitude of the adhesion in Constant adhesion model
// Create the falling ball
auto ball = chrono_types::make_shared<ChBody>();
ball->SetIdentifier(ballId);
ball->SetMass(mass);
ball->SetPos(pos);
ball->SetRot(rot);
ball->SetPos_dt(init_vel);
// ball->SetWvel_par(ChVector<>(0,0,3));
ball->SetBodyFixed(false);
ball->SetCollide(true);
ball->GetCollisionModel()->ClearModel();
ball->GetCollisionModel()->AddSphere(material, radius);
ball->GetCollisionModel()->BuildModel();
ball->SetInertiaXX(0.4 * mass * radius * radius * ChVector<>(1, 1, 1));
auto sphere = chrono_types::make_shared<ChSphereShape>();
sphere->GetSphereGeometry().rad = radius;
ball->AddAsset(sphere);
auto mtexture = chrono_types::make_shared<ChTexture>();
mtexture->SetTextureFilename(GetChronoDataFile("textures/bluewhite.png"));
ball->AddAsset(mtexture);
msystem.AddBody(ball);
// Create container
auto bin = chrono_types::make_shared<ChBody>();
bin->SetIdentifier(binId);
bin->SetMass(1);
bin->SetPos(ChVector<>(0, 0, 0));
bin->SetRot(ChQuaternion<>(1, 0, 0, 0));
bin->SetCollide(true);
bin->SetBodyFixed(true);
bin->GetCollisionModel()->ClearModel();
AddWall(bin, ChVector<>(width, thickness, length), ChVector<>(0, 0, 0), material);
////AddWall(bin, ChVector<>(thickness, height, length), ChVector<>(-width + thickness, height, 0), material);
////AddWall(bin, ChVector<>(thickness, height, length), ChVector<>(width - thickness, height, 0), material);
////AddWall(bin, ChVector<>(width, height, thickness), ChVector<>(0, height, -length + thickness), material);
////AddWall(bin, ChVector<>(width, height, thickness), ChVector<>(0, height, length - thickness), material);
bin->GetCollisionModel()->BuildModel();
msystem.AddBody(bin);
// Complete asset construction
application.AssetBindAll();
application.AssetUpdateAll();
// The soft-real-time cycle
double time = 0.0;
double out_time = 0.0;
while (application.GetDevice()->run()) {
application.BeginScene();
application.DrawAll();
tools::drawGrid(application.GetVideoDriver(), 0.2, 0.2, 20, 20,
ChCoordsys<>(ChVector<>(0, 0, 0), Q_from_AngX(CH_C_PI_2)),
video::SColor(255, 80, 100, 100), true);
while (time < out_time) {
msystem.DoStepDynamics(time_step);
time += time_step;
}
out_time += out_step;
application.EndScene();
}
return 0;
}
| 6,194 | 2,042 |
#include <bits/stdc++.h>
using namespace std;
#define ll long long
int main() {
ll n;
cin >> n;
vector<ll> v1, v2;
ll sum = n * (n + 1) / 2;
if (sum % 2 != 0) {
cout << "NO" << endl;
return 0;
}
sum /= 2;
for (int i = n; i > 0; i--) {
if (sum - i >= 0) {
v1.push_back(i);
sum -= i;
} else
v2.push_back(i);
}
cout << "YES\n" << endl;
cout << v1.size() << endl;
for(int e : v1)
cout << e << " ";
cout << endl;
cout << v2.size() << endl;
for(int e : v2)
cout << e << " ";
cout << endl;
} | 636 | 263 |
/*
// Copyright (c) 2018 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
*/
///////////////////////////////////////////////////////////////////////////////////////////////////
#include <gtest/gtest.h>
#include "api/memory.hpp"
#include <api/input_layout.hpp>
#include "api/softmax_loss_grad.hpp"
#include <api/data.hpp>
#include <api/topology.hpp>
#include <api/network.hpp>
#include <api/engine.hpp>
#include "test_utils/test_utils.h"
using namespace cldnn;
using namespace tests;
TEST(softmax_loss_grad_f32_fw_gpu, basic1) {
const auto& engine = get_test_engine();
auto input = memory::allocate(engine, { data_types::f32, format::bfyx,{ 2, 1, 4, 1 } });
auto labels = memory::allocate(engine, { data_types::f32, format::bfyx,{ 2, 1, 1, 1 } });
set_values(input, { 8.f, 0.5f, 6.f, 9.f, 1.f, 3.f, 2.f, 4.f });
set_values(labels, { 1.f, 3.f });
topology topology(
input_layout("input", input.get_layout()),
data("labels", labels),
softmax_loss_grad("softmax_loss_grad", "input", "labels")
);
network network(engine, topology);
network.set_input_data("input", input);
auto outputs = network.execute();
EXPECT_EQ(outputs.size(), size_t(1));
EXPECT_EQ(outputs.begin()->first, "softmax_loss_grad");
auto output_prim = outputs.begin()->second.get_memory();
auto output_ptr = output_prim.pointer<float>();
std::vector<float> expected_output_vec = { 8.f, -0.5f, 6.f, 9.f, 1.f, 3.f, 2.f, 3.f };
for (unsigned int i = 0; i < expected_output_vec.size(); i++)
{
EXPECT_FLOAT_EQ(expected_output_vec[i], output_ptr[i]);
}
} | 2,156 | 769 |
#include "stdafx.h"
#include "ParticleBurst.hpp"
#include "Math.hpp"
#include "Game.hpp"
#include "Function.hpp"
#include "Events.hpp"
#include "Sfx.hpp"
#include "ScreenManager.hpp"
#include "Map.hpp"
#include "stdlib.hpp"
struct ParticleBurst_Item
{
FP field_0_x;
FP field_4_y;
FP field_8_z;
FP field_C_x_speed;
FP field_10_y_speed;
FP field_14_z_speed;
AnimationUnknown field_18_anim;
};
ALIVE_ASSERT_SIZEOF(ParticleBurst_Item, 0x88);
ParticleBurst* ParticleBurst::ctor_41CF50(FP xpos, FP ypos, unsigned int numOfParticles, FP scale, BurstType type, signed __int16 count)
{
BaseAnimatedWithPhysicsGameObject_ctor_424930(0);
SetVTable(this, 0x5447DC);
field_4_typeId = Types::eParticleBurst_29;
// TODO: Check it
if (numOfParticles > 5)
{
numOfParticles /= 2;
}
if (count > 13)
{
count = 13;
}
else if (count <= 0)
{
count = 1;
}
field_106_count = count;
field_CC_sprite_scale = scale;
field_F4_ppRes = ResourceManager::Allocate_New_Locked_Resource_49BF40(ResourceManager::ResourceType::Resource_3DGibs, 0, sizeof(ParticleBurst_Item) * numOfParticles);
if (field_F4_ppRes)
{
field_F8_pRes = reinterpret_cast<ParticleBurst_Item*>(*field_F4_ppRes);
for (DWORD i = 0; i < numOfParticles; i++)
{
// Placement new each element
new (&field_F8_pRes[i]) ParticleBurst_Item();
SetVTable(&field_F8_pRes[i].field_18_anim, 0x5447CC);
}
field_104_type = type;
switch (field_104_type)
{
case BurstType::eFallingRocks_0:
Animation_Init_424E10(6484, 71, 36, Add_Resource_4DC130(ResourceManager::Resource_Animation, ResourceID::kDebrisID00), 1, 1u);
field_20_animation.field_4_flags.Clear(AnimFlags::eBit15_bSemiTrans);
field_20_animation.field_4_flags.Set(AnimFlags::eBit16_bBlending);
break;
case BurstType::eSticks_1:
Animation_Init_424E10(1704, 49, 29, Add_Resource_4DC130(ResourceManager::Resource_Animation, ResourceID::kStickGib), 1, 1u);
field_20_animation.field_4_flags.Clear(AnimFlags::eBit15_bSemiTrans);
field_20_animation.field_4_flags.Set(AnimFlags::eBit16_bBlending);
break;
case BurstType::eBigPurpleSparks_2:
Animation_Init_424E10(9912, 122, 43, Add_Resource_4DC130(ResourceManager::Resource_Animation, ResourceID::kDeathFlareResID), 1, 1u);
field_20_animation.field_4_flags.Set(AnimFlags::eBit15_bSemiTrans);
field_20_animation.field_4_flags.Set(AnimFlags::eBit16_bBlending);
field_20_animation.field_B_render_mode = TPageAbr::eBlend_1;
break;
case BurstType::eBigRedSparks_3:
case BurstType::eGreenSparks_5:
case BurstType::eSmallPurpleSparks_6:
Animation_Init_424E10(9912, 122, 43, Add_Resource_4DC130(ResourceManager::Resource_Animation, ResourceID::kDeathFlareResID), 1, 1u);
field_20_animation.field_B_render_mode = TPageAbr::eBlend_1;
field_20_animation.field_4_flags.Set(AnimFlags::eBit15_bSemiTrans);
field_20_animation.field_4_flags.Clear(AnimFlags::eBit16_bBlending);
if (field_104_type == BurstType::eBigRedSparks_3)
{
field_20_animation.field_8_r = 254;
field_20_animation.field_9_g = 148;
field_20_animation.field_A_b = 18;
}
else if (field_104_type == BurstType::eSmallPurpleSparks_6)
{
field_20_animation.field_8_r = 127;
field_20_animation.field_9_g = 127;
field_20_animation.field_A_b = 127;
}
else
{
field_20_animation.field_8_r = 0;
field_20_animation.field_9_g = 255;
field_20_animation.field_A_b = 32;
}
break;
default:
break;
}
if (field_6_flags.Get(BaseGameObject::eListAddFailed_Bit1))
{
field_6_flags.Set(BaseGameObject::eDead_Bit3);
}
else
{
if (field_CC_sprite_scale == FP_FromInteger(1))
{
field_D6_scale = 1;
field_20_animation.field_C_render_layer = Layer::eLayer_39;
}
else
{
field_D6_scale = 0;
field_20_animation.field_C_render_layer = Layer::eLayer_20;
}
field_FC_number_of_particles = static_cast<short>(numOfParticles);
field_100_timer = sGnFrame_5C1B84 + 91;
field_B8_xpos = xpos;
field_BC_ypos = ypos;
for (DWORD i = 0; i < numOfParticles; i++)
{
field_F8_pRes[i].field_18_anim.field_68_anim_ptr = &field_20_animation;
field_F8_pRes[i].field_18_anim.field_C_render_layer = field_20_animation.field_C_render_layer;
field_F8_pRes[i].field_18_anim.field_6C_scale = FP_FromDouble(0.95) * field_CC_sprite_scale;
field_F8_pRes[i].field_18_anim.field_4_flags.Set(AnimFlags::eBit3_Render);
field_F8_pRes[i].field_18_anim.field_4_flags.Set(AnimFlags::eBit25_bDecompressDone); // TODO: HIWORD &= ~0x0100u ??
field_F8_pRes[i].field_18_anim.field_4_flags.Set(AnimFlags::eBit15_bSemiTrans, field_20_animation.field_4_flags.Get(AnimFlags::eBit15_bSemiTrans));
field_F8_pRes[i].field_18_anim.field_4_flags.Set(AnimFlags::eBit16_bBlending, field_20_animation.field_4_flags.Get(AnimFlags::eBit16_bBlending));
if (type == BurstType::eBigPurpleSparks_2)
{
if (i % 2)
{
field_F8_pRes[i].field_18_anim.field_4_flags.Set(AnimFlags::eBit16_bBlending);
}
}
field_F8_pRes[i].field_18_anim.field_8_r = field_20_animation.field_8_r;
field_F8_pRes[i].field_18_anim.field_9_g = field_20_animation.field_9_g;
field_F8_pRes[i].field_18_anim.field_A_b = field_20_animation.field_A_b;
field_F8_pRes[i].field_0_x = field_B8_xpos;
field_F8_pRes[i].field_4_y = field_BC_ypos;
field_F8_pRes[i].field_8_z = FP_FromInteger(0);
Random_Speed_41CEE0(&field_F8_pRes[i].field_C_x_speed);
Random_Speed_41CEE0(&field_F8_pRes[i].field_10_y_speed);
// OG bug sign could be wrong here as it called random again to Abs() it!
FP zRandom = {};
field_F8_pRes[i].field_14_z_speed = -FP_Abs(*Random_Speed_41CEE0(&zRandom));
}
}
}
else
{
field_6_flags.Set(BaseGameObject::eDead_Bit3);
}
return this;
}
BaseGameObject* ParticleBurst::VDestructor(signed int flags)
{
return vdtor_41D4E0(flags);
}
void ParticleBurst::VUpdate()
{
vUpdate_41D590();
}
void ParticleBurst::VRender(PrimHeader** ppOt)
{
vRender_41D7B0(ppOt);
}
FP* ParticleBurst::Random_Speed_41CEE0(FP* random)
{
const FP v2 = FP_FromRaw((Math_NextRandom() - 128) << LOBYTE(field_106_count));
*random = v2 * field_CC_sprite_scale;
return random;
}
ParticleBurst* ParticleBurst::vdtor_41D4E0(signed int flags)
{
dtor_41D510();
if (flags & 1)
{
ae_delete_free_495540(this);
}
return this;
}
void ParticleBurst::dtor_41D510()
{
SetVTable(this, 0x5447DC);
if (field_F4_ppRes)
{
ResourceManager::FreeResource_49C330(field_F4_ppRes);
}
BaseAnimatedWithPhysicsGameObject_dtor_424AD0();
}
void ParticleBurst::vRender_41D7B0(PrimHeader** ppOt)
{
bool bFirst = true;
if (sNum_CamSwappers_5C1B66 == 0)
{
field_20_animation.field_14_scale = field_CC_sprite_scale;
const FP camX = pScreenManager_5BB5F4->field_20_pCamPos->field_0_x;
const FP camY = pScreenManager_5BB5F4->field_20_pCamPos->field_4_y;
for (int i = 0; i < field_FC_number_of_particles; i++)
{
if (field_F8_pRes[i].field_0_x < camX)
{
continue;
}
if (field_F8_pRes[i].field_0_x > camX + FP_FromInteger(640))
{
continue;
}
if (field_F8_pRes[i].field_4_y < camY)
{
continue;
}
if (field_F8_pRes[i].field_4_y > camY + FP_FromInteger(240))
{
continue;
}
const FP zPos = field_F8_pRes[i].field_8_z;
// TODO: Much duplicated code in each branch
if (bFirst)
{
field_20_animation.field_14_scale = FP_FromInteger(100) / (zPos + FP_FromInteger(300));
field_20_animation.field_14_scale *= field_CC_sprite_scale;
field_20_animation.field_14_scale *= FP_FromInteger(field_106_count) / FP_FromInteger(13);
if (field_20_animation.field_14_scale <= FP_FromInteger(1))
{
field_20_animation.vRender_40B820(
FP_GetExponent(field_F8_pRes[i].field_0_x - camX),
FP_GetExponent(field_F8_pRes[i].field_4_y - camY),
ppOt,
0,
0);
bFirst = false;
PSX_RECT frameRect = {};
field_20_animation.Get_Frame_Rect_409E10(&frameRect);
if (field_106_count == 9)
{
if (field_20_animation.field_8_r > 5)
{
field_20_animation.field_8_r -= 6;
}
else
{
field_20_animation.field_8_r = 0;
}
if (field_20_animation.field_9_g > 5)
{
field_20_animation.field_9_g -= 6;
}
else
{
field_20_animation.field_9_g = 0;
}
if (field_20_animation.field_A_b > 5)
{
field_20_animation.field_A_b -= 6;
}
else
{
field_20_animation.field_A_b = 0;
}
}
pScreenManager_5BB5F4->InvalidateRect_40EC90(
frameRect.x,
frameRect.y,
frameRect.w,
frameRect.h,
pScreenManager_5BB5F4->field_3A_idx);
}
}
else
{
field_F8_pRes[i].field_18_anim.field_6C_scale = FP_FromInteger(100) / (zPos + FP_FromInteger(300));
field_F8_pRes[i].field_18_anim.field_6C_scale *= field_CC_sprite_scale;
field_F8_pRes[i].field_18_anim.field_6C_scale *= FP_FromInteger(field_106_count) / FP_FromInteger(13);
if (field_F8_pRes[i].field_18_anim.field_6C_scale <= FP_FromInteger(1))
{
field_F8_pRes[i].field_18_anim.vRender_40B820(
FP_GetExponent(field_F8_pRes[i].field_0_x - camX),
FP_GetExponent(field_F8_pRes[i].field_4_y - camY),
ppOt,
0,
0);
PSX_RECT frameRect = {};
field_F8_pRes[i].field_18_anim.GetRenderedSize_40C980(&frameRect);
if (field_106_count == 9)
{
if (field_F8_pRes[i].field_18_anim.field_8_r > 5)
{
field_F8_pRes[i].field_18_anim.field_8_r -= 6;
}
else
{
field_F8_pRes[i].field_18_anim.field_8_r = 0;
}
if (field_F8_pRes[i].field_18_anim.field_9_g > 5)
{
field_F8_pRes[i].field_18_anim.field_9_g -= 6;
}
else
{
field_F8_pRes[i].field_18_anim.field_9_g = 0;
}
if (field_F8_pRes[i].field_18_anim.field_A_b > 5)
{
field_F8_pRes[i].field_18_anim.field_A_b -= 6;
}
else
{
field_F8_pRes[i].field_18_anim.field_A_b = 0;
}
}
pScreenManager_5BB5F4->InvalidateRect_40EC90(
frameRect.x,
frameRect.y,
frameRect.w,
frameRect.h,
pScreenManager_5BB5F4->field_3A_idx);
}
}
}
}
}
void ParticleBurst::vUpdate_41D590()
{
const int v3 = field_CC_sprite_scale != FP_FromInteger(1) ? 2 : 4;
for (int i = 0; i < field_FC_number_of_particles; i++)
{
field_F8_pRes[i].field_0_x += field_F8_pRes[i].field_C_x_speed;
field_F8_pRes[i].field_4_y += field_F8_pRes[i].field_10_y_speed;
field_F8_pRes[i].field_8_z += field_F8_pRes[i].field_14_z_speed;
field_F8_pRes[i].field_10_y_speed += FP_FromDouble(0.25);
if (field_106_count == 9)
{
if ((sGnFrame_5C1B84 + i) & v3)
{
field_F8_pRes[i].field_0_x -= FP_FromInteger(1);
}
else
{
field_F8_pRes[i].field_0_x += FP_FromInteger(1);
}
}
if (field_F8_pRes[i].field_8_z + FP_FromInteger(300) < FP_FromInteger(15))
{
field_F8_pRes[i].field_14_z_speed = -field_F8_pRes[i].field_14_z_speed;
field_F8_pRes[i].field_8_z += field_F8_pRes[i].field_14_z_speed;
// TODO: Never used by OG ??
//Math_RandomRange_496AB0(-64, 46);
// TODO: This might be wrong
const short volume = static_cast<short>(Math_RandomRange_496AB0(-10, 10) + ((field_100_timer - sGnFrame_5C1B84) / 91) + 25);
const BYTE next_rand = Math_NextRandom();
if (next_rand < 43)
{
SFX_Play_46FC20(SoundEffect::ParticleBurst_27, volume, CameraPos::eCamLeft_3);
}
else if (next_rand >= 85)
{
SFX_Play_46FC20(SoundEffect::ParticleBurst_27, volume, CameraPos::eCamRight_4);
}
else
{
SFX_Play_46FC20(SoundEffect::ParticleBurst_27, volume, CameraPos::eCamCurrent_0);
}
}
}
if (static_cast<int>(sGnFrame_5C1B84) > field_100_timer)
{
field_6_flags.Set(BaseGameObject::eDead_Bit3);
}
if (Event_Get_422C00(kEventDeathReset))
{
field_6_flags.Set(BaseGameObject::eDead_Bit3);
}
}
| 15,456 | 5,667 |
#ifndef RINGBUFFER_H
# define RINGBUFFER_H
# include <cstdint>
# include <memory>
# include <cstring>
# include "ASocket.hpp"
namespace Network {
class RingBuffer
{
public:
RingBuffer(size_t size = 4096);
virtual ~RingBuffer() = default;
void writeBuffer(const Network::Buffer& data);
void readBuffer(Network::Buffer& data, size_t rSize);
size_t getBuffSize() const {return _buffSize;};
void extendRingBuffer(size_t addSize);
void rollbackReadBuffer(size_t rbsize);
inline size_t getLeftRead() const {
return (((_idxW + _buffSize) - _idxR) % _buffSize);
};
inline size_t getLeftWrite() const {
return (((_idxR + _buffSize - 1) - _idxW) % _buffSize);
};
//Iterators
protected:
size_t _buffSize;
size_t _idxR;
size_t _idxW;
std::unique_ptr<uint8_t[]> _buffer;
};
};
#endif // RINGBUFFER_H
| 854 | 345 |
/**
* Created by Joscha Vack on 12/9/2019.
*
**/
#include "GlobalDefinitions.h"
TS3Functions ts3Functions;
char* pluginID = nullptr;
ServerList serverList {}; | 166 | 69 |
#ifdef PEGASUS_OS_SOLARIS
#ifndef __UNIX_PACKAGEINCONNECTOR_PRIVATE_H
#define __UNIX_PACKAGEINCONNECTOR_PRIVATE_H
#endif
#endif
| 134 | 72 |
#include "problem1.h"
#include <iostream>
void problem1BruteForce(long upperLimit) {
printf("Problem 1 - Brute Force\n");
int multiplesOf3And5Count = 0;
for (int i = 0; i < upperLimit; i++)
{
if (i % 3 == 0 || i % 5 == 0)
{
multiplesOf3And5Count += i;
}
}
printf("Multiples of 3 and 5 below %ld = %d", upperLimit, multiplesOf3And5Count);
}
int getMultiples(int argument, int upperLimit) {
int multiplesCount = 0;
int i = 1;
int loops = (upperLimit - 1) / argument;
while (i <= loops) {
int multiple = argument * i;
multiplesCount += multiple;
i++;
}
return multiplesCount;
}
void problem1Multiples(long upperLimit) {
printf("Problem 1 - Multiples\n");
int multiplesOf3And5Count = 0;
multiplesOf3And5Count += getMultiples(3, upperLimit);
multiplesOf3And5Count += getMultiples(5, upperLimit);
multiplesOf3And5Count -= getMultiples(15, upperLimit);
printf("Multiples of 3 and 5 below %ld = %d", upperLimit, multiplesOf3And5Count);
}
| 986 | 400 |
#include<bits/stdc++.h>
using namespace std;
int findset(vector<int> &subset,int u)
{
if(subset[u] == -1) return u;
subset[u] = findset(subset,subset[u]);
return subset[u];
}
void kruskal(vector<pair<int,pair<int,int> > > edge,int V)
{
vector<int> subset(V,-1);
vector<pair<int,pair<int,int> > > MST;
sort(edge.begin(),edge.end());
for(auto E : edge)
{
int setu = findset(subset,E.second.first);
int setv = findset(subset,E.second.second);
if(setu != setv)
{
MST.push_back(E);
subset[setu] = setv;
if(MST.size() == V-1) break;
}
}
for(auto E : MST)
cout<<E.second.first+1<<" "<<E.second.second+1<<'\n';
}
main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int V,E;
cin>>V>>E;
vector<pair<int,pair<int,int> > > edge;
int u,v,w;
for(int i=0;i<E;i++)
{
cin>>u>>v>>w;
u-- , v--;
edge.push_back(make_pair(w,make_pair(u,v)));
}
kruskal(edge,V);
}
| 911 | 467 |
/*
Copyright (c) 2007, 2015, 2017, 2019-2021, Arvid Norberg
All rights reserved.
You may use, distribute and modify this code under the terms of the BSD license,
see LICENSE file.
*/
#include "libtorrent/aux_/session_settings.hpp"
#include "libtorrent/settings_pack.hpp"
#include <functional>
namespace libtorrent { namespace aux {
session_settings::session_settings() = default;
session_settings::session_settings(settings_pack const& p)
{
apply_pack_impl(&p, m_store);
}
void session_settings::bulk_set(std::function<void(session_settings_single_thread&)> f)
{
std::unique_lock<std::mutex> l(m_mutex);
f(m_store);
}
void session_settings::bulk_get(std::function<void(session_settings_single_thread const&)> f) const
{
std::unique_lock<std::mutex> l(m_mutex);
f(m_store);
}
session_settings_single_thread::session_settings_single_thread()
{
initialize_default_settings(*this);
}
} }
| 921 | 358 |
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
/*
题目:
替换空格
请实现一个函数,把字符串中的每个空格替换成“%20”,
例如,输入”We are happy.”,则输出”We%20are%20happy.”。
*/
char *replace_spaces(const char *src, size_t slen)
{
char *desc = NULL;
size_t count = 0;
size_t j = 0;
//malloc mem
for (size_t i = 0; i < slen; i++)
{
if (src[i] == ' ')
{
count++;
}
}
desc = (char *)malloc(slen + count * 2);
//copy
for (size_t i = 0; i < slen; i++)
{
if (src[i] == ' ')
{
desc[j++] = '%';
desc[j++] = '2';
desc[j++] = '0';
}
else
{
desc[j++] = src[i];
}
}
desc[j++] = '\0';
return desc;
}
int main(int argc, const char **argv)
{
char *str = (char *)"We are happy.";
size_t len = strlen(str);
char *dest = replace_spaces(str, len);
if (strcmp(dest, "We%20are%20happy.") == 0)
cout << "dest replace sucess!" << endl;
else
cout << "Error: dest replace failed!" << endl;
return 0;
} | 1,125 | 474 |
//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2010-2013, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "GU/GU_PrimNURBCurve.h"
#include "IECore/DespatchTypedData.h"
#include "IECoreHoudini/ToHoudiniAttribConverter.h"
#include "IECoreHoudini/ToHoudiniCurvesConverter.h"
#include "IECoreHoudini/TypeTraits.h"
using namespace IECore;
using namespace IECoreHoudini;
IE_CORE_DEFINERUNTIMETYPED( ToHoudiniCurvesConverter );
ToHoudiniGeometryConverter::Description<ToHoudiniCurvesConverter> ToHoudiniCurvesConverter::m_description( CurvesPrimitiveTypeId );
ToHoudiniCurvesConverter::ToHoudiniCurvesConverter( const VisibleRenderable *renderable ) :
ToHoudiniGeometryConverter( renderable, "Converts an IECore::CurvesPrimitive to a Houdini GU_Detail." )
{
}
ToHoudiniCurvesConverter::~ToHoudiniCurvesConverter()
{
}
bool ToHoudiniCurvesConverter::doConversion( const VisibleRenderable *renderable, GU_Detail *geo ) const
{
const CurvesPrimitive *curves = static_cast<const CurvesPrimitive *>( renderable );
if ( !curves )
{
return false;
}
bool periodic = curves->periodic();
bool duplicatedEnds = !periodic && ( curves->basis() == CubicBasisf::bSpline() );
size_t numPoints = curves->variableSize( PrimitiveVariable::Vertex );
if ( duplicatedEnds )
{
numPoints -= 4 * curves->numCurves();
}
GA_Range newPoints = appendPoints( geo, numPoints );
if ( !newPoints.isValid() || newPoints.empty() )
{
return false;
}
GA_OffsetList pointOffsets;
pointOffsets.reserve( newPoints.getEntries() );
for ( GA_Iterator it=newPoints.begin(); !it.atEnd(); ++it )
{
pointOffsets.append( it.getOffset() );
}
const std::vector<int> &verticesPerCurve = curves->verticesPerCurve()->readable();
int order = ( curves->basis() == CubicBasisf::bSpline() ) ? 4 : 2;
bool interpEnds = !(periodic && ( curves->basis() == CubicBasisf::bSpline() ));
GA_OffsetList offsets;
offsets.reserve( verticesPerCurve.size() );
size_t vertCount = 0;
size_t numPrims = geo->getNumPrimitives();
for ( size_t c=0; c < verticesPerCurve.size(); c++ )
{
size_t numVerts = duplicatedEnds ? verticesPerCurve[c] - 4 : verticesPerCurve[c];
GU_PrimNURBCurve *curve = GU_PrimNURBCurve::build( geo, numVerts, order, periodic, interpEnds, false );
if ( !curve )
{
return false;
}
offsets.append( geo->primitiveOffset( numPrims + c ) );
for ( size_t v=0; v < numVerts; v++ )
{
curve->setVertexPoint( v, pointOffsets.get( vertCount + v ) );
}
vertCount += numVerts;
}
GA_Range newPrims( geo->getPrimitiveMap(), offsets );
transferAttribs( geo, newPoints, newPrims );
return true;
}
PrimitiveVariable ToHoudiniCurvesConverter::processPrimitiveVariable( const IECore::Primitive *primitive, const PrimitiveVariable &primVar ) const
{
const CurvesPrimitive *curves = static_cast<const CurvesPrimitive *>( primitive );
if ( !curves )
{
return primVar;
}
// adjust for duplicated end points
bool duplicatedEnds = !curves->periodic() && ( curves->basis() == CubicBasisf::bSpline() );
if ( duplicatedEnds && primVar.interpolation == IECore::PrimitiveVariable::Vertex )
{
RemoveDuplicateEnds func( curves->verticesPerCurve()->readable() );
DataPtr data = despatchTypedData<RemoveDuplicateEnds, TypeTraits::IsVectorAttribTypedData, DespatchTypedDataIgnoreError>( primVar.data, func );
return PrimitiveVariable( IECore::PrimitiveVariable::Vertex, data );
}
return primVar;
}
void ToHoudiniCurvesConverter::transferAttribs( GU_Detail *geo, const GA_Range &points, const GA_Range &prims ) const
{
const Primitive *primitive = IECore::runTimeCast<const Primitive>( srcParameter()->getValidatedValue() );
if ( primitive )
{
transferAttribValues( primitive, geo, points, prims, PrimitiveVariable::Vertex );
}
}
ToHoudiniCurvesConverter::RemoveDuplicateEnds::RemoveDuplicateEnds( const std::vector<int> &vertsPerCurve ) : m_vertsPerCurve( vertsPerCurve )
{
}
template <typename T>
ToHoudiniCurvesConverter::RemoveDuplicateEnds::ReturnType ToHoudiniCurvesConverter::RemoveDuplicateEnds::operator()( typename T::ConstPtr data ) const
{
assert( data );
typedef typename T::ValueType::value_type ValueType;
const std::vector<ValueType> &origValues = data->readable();
typename T::Ptr result = new T();
std::vector<ValueType> &newValues = result->writable();
size_t index = 0;
for ( size_t i=0; i < m_vertsPerCurve.size(); i++ )
{
for ( size_t j=0; j < (size_t)m_vertsPerCurve[i]; j++, index++ )
{
if ( j > 1 && j < (size_t)m_vertsPerCurve[i]-2 )
{
newValues.push_back( origValues[index] );
}
}
}
return result;
}
| 6,324 | 2,274 |
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/memory/scoped_ptr.h"
#include "base/memory/scoped_vector.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/autofill/autofill_field.h"
#include "chrome/browser/autofill/autofill_scanner.h"
#include "chrome/browser/autofill/credit_card_field.h"
#include "chrome/common/form_field_data.h"
#include "testing/gtest/include/gtest/gtest.h"
class CreditCardFieldTest : public testing::Test {
public:
CreditCardFieldTest() {}
protected:
ScopedVector<const AutofillField> list_;
scoped_ptr<CreditCardField> field_;
FieldTypeMap field_type_map_;
// Downcast for tests.
static CreditCardField* Parse(AutofillScanner* scanner) {
return static_cast<CreditCardField*>(CreditCardField::Parse(scanner));
}
private:
DISALLOW_COPY_AND_ASSIGN(CreditCardFieldTest);
};
TEST_F(CreditCardFieldTest, Empty) {
AutofillScanner scanner(list_.get());
field_.reset(Parse(&scanner));
ASSERT_EQ(static_cast<CreditCardField*>(NULL), field_.get());
}
TEST_F(CreditCardFieldTest, NonParse) {
list_.push_back(new AutofillField);
AutofillScanner scanner(list_.get());
field_.reset(Parse(&scanner));
ASSERT_EQ(static_cast<CreditCardField*>(NULL), field_.get());
}
TEST_F(CreditCardFieldTest, ParseCreditCardNoNumber) {
FormFieldData field;
field.form_control_type = "text";
field.label = ASCIIToUTF16("Exp Month");
field.name = ASCIIToUTF16("ccmonth");
list_.push_back(new AutofillField(field, ASCIIToUTF16("month1")));
field.label = ASCIIToUTF16("Exp Year");
field.name = ASCIIToUTF16("ccyear");
list_.push_back(new AutofillField(field, ASCIIToUTF16("year2")));
AutofillScanner scanner(list_.get());
field_.reset(Parse(&scanner));
ASSERT_EQ(static_cast<CreditCardField*>(NULL), field_.get());
}
TEST_F(CreditCardFieldTest, ParseCreditCardNoDate) {
FormFieldData field;
field.form_control_type = "text";
field.label = ASCIIToUTF16("Card Number");
field.name = ASCIIToUTF16("card_number");
list_.push_back(new AutofillField(field, ASCIIToUTF16("number1")));
AutofillScanner scanner(list_.get());
field_.reset(Parse(&scanner));
ASSERT_EQ(static_cast<CreditCardField*>(NULL), field_.get());
}
TEST_F(CreditCardFieldTest, ParseMiniumCreditCard) {
FormFieldData field;
field.form_control_type = "text";
field.label = ASCIIToUTF16("Card Number");
field.name = ASCIIToUTF16("card_number");
list_.push_back(new AutofillField(field, ASCIIToUTF16("number1")));
field.label = ASCIIToUTF16("Exp Month");
field.name = ASCIIToUTF16("ccmonth");
list_.push_back(new AutofillField(field, ASCIIToUTF16("month2")));
field.label = ASCIIToUTF16("Exp Year");
field.name = ASCIIToUTF16("ccyear");
list_.push_back(new AutofillField(field, ASCIIToUTF16("year3")));
AutofillScanner scanner(list_.get());
field_.reset(Parse(&scanner));
ASSERT_NE(static_cast<CreditCardField*>(NULL), field_.get());
ASSERT_TRUE(field_->ClassifyField(&field_type_map_));
ASSERT_TRUE(
field_type_map_.find(ASCIIToUTF16("number1")) != field_type_map_.end());
EXPECT_EQ(CREDIT_CARD_NUMBER, field_type_map_[ASCIIToUTF16("number1")]);
ASSERT_TRUE(
field_type_map_.find(ASCIIToUTF16("month2")) != field_type_map_.end());
EXPECT_EQ(CREDIT_CARD_EXP_MONTH, field_type_map_[ASCIIToUTF16("month2")]);
ASSERT_TRUE(
field_type_map_.find(ASCIIToUTF16("year3")) != field_type_map_.end());
EXPECT_EQ(CREDIT_CARD_EXP_4_DIGIT_YEAR,
field_type_map_[ASCIIToUTF16("year3")]);
}
TEST_F(CreditCardFieldTest, ParseFullCreditCard) {
FormFieldData field;
field.form_control_type = "text";
field.label = ASCIIToUTF16("Card Type");
field.name = ASCIIToUTF16("card_type");
list_.push_back(new AutofillField(field, ASCIIToUTF16("type")));
field.label = ASCIIToUTF16("Name on Card");
field.name = ASCIIToUTF16("name_on_card");
list_.push_back(new AutofillField(field, ASCIIToUTF16("name")));
field.label = ASCIIToUTF16("Card Number");
field.name = ASCIIToUTF16("card_number");
list_.push_back(new AutofillField(field, ASCIIToUTF16("number")));
field.label = ASCIIToUTF16("Exp Month");
field.name = ASCIIToUTF16("ccmonth");
list_.push_back(new AutofillField(field, ASCIIToUTF16("month")));
field.label = ASCIIToUTF16("Exp Year");
field.name = ASCIIToUTF16("ccyear");
list_.push_back(new AutofillField(field, ASCIIToUTF16("year")));
field.label = ASCIIToUTF16("Verification");
field.name = ASCIIToUTF16("verification");
list_.push_back(new AutofillField(field, ASCIIToUTF16("cvc")));
AutofillScanner scanner(list_.get());
field_.reset(Parse(&scanner));
ASSERT_NE(static_cast<CreditCardField*>(NULL), field_.get());
ASSERT_TRUE(field_->ClassifyField(&field_type_map_));
ASSERT_TRUE(
field_type_map_.find(ASCIIToUTF16("type")) != field_type_map_.end());
EXPECT_EQ(CREDIT_CARD_TYPE, field_type_map_[ASCIIToUTF16("type")]);
ASSERT_TRUE(
field_type_map_.find(ASCIIToUTF16("name")) != field_type_map_.end());
EXPECT_EQ(CREDIT_CARD_NAME, field_type_map_[ASCIIToUTF16("name")]);
ASSERT_TRUE(
field_type_map_.find(ASCIIToUTF16("number")) != field_type_map_.end());
EXPECT_EQ(CREDIT_CARD_NUMBER, field_type_map_[ASCIIToUTF16("number")]);
ASSERT_TRUE(
field_type_map_.find(ASCIIToUTF16("month")) != field_type_map_.end());
EXPECT_EQ(CREDIT_CARD_EXP_MONTH, field_type_map_[ASCIIToUTF16("month")]);
ASSERT_TRUE(
field_type_map_.find(ASCIIToUTF16("year")) != field_type_map_.end());
EXPECT_EQ(CREDIT_CARD_EXP_4_DIGIT_YEAR,
field_type_map_[ASCIIToUTF16("year")]);
ASSERT_TRUE(
field_type_map_.find(ASCIIToUTF16("cvc")) != field_type_map_.end());
EXPECT_EQ(CREDIT_CARD_VERIFICATION_CODE,
field_type_map_[ASCIIToUTF16("cvc")]);
}
TEST_F(CreditCardFieldTest, ParseExpMonthYear) {
FormFieldData field;
field.form_control_type = "text";
field.label = ASCIIToUTF16("Name on Card");
field.name = ASCIIToUTF16("name_on_card");
list_.push_back(new AutofillField(field, ASCIIToUTF16("name1")));
field.label = ASCIIToUTF16("Card Number");
field.name = ASCIIToUTF16("card_number");
list_.push_back(new AutofillField(field, ASCIIToUTF16("number2")));
field.label = ASCIIToUTF16("ExpDate Month / Year");
field.name = ASCIIToUTF16("ExpDate");
list_.push_back(new AutofillField(field, ASCIIToUTF16("month3")));
field.label = ASCIIToUTF16("ExpDate Month / Year");
field.name = ASCIIToUTF16("ExpDate");
list_.push_back(new AutofillField(field, ASCIIToUTF16("year4")));
AutofillScanner scanner(list_.get());
field_.reset(Parse(&scanner));
ASSERT_NE(static_cast<CreditCardField*>(NULL), field_.get());
ASSERT_TRUE(field_->ClassifyField(&field_type_map_));
ASSERT_TRUE(
field_type_map_.find(ASCIIToUTF16("name1")) != field_type_map_.end());
EXPECT_EQ(CREDIT_CARD_NAME, field_type_map_[ASCIIToUTF16("name1")]);
ASSERT_TRUE(
field_type_map_.find(ASCIIToUTF16("number2")) != field_type_map_.end());
EXPECT_EQ(CREDIT_CARD_NUMBER, field_type_map_[ASCIIToUTF16("number2")]);
ASSERT_TRUE(
field_type_map_.find(ASCIIToUTF16("month3")) != field_type_map_.end());
EXPECT_EQ(CREDIT_CARD_EXP_MONTH, field_type_map_[ASCIIToUTF16("month3")]);
ASSERT_TRUE(
field_type_map_.find(ASCIIToUTF16("year4")) != field_type_map_.end());
EXPECT_EQ(CREDIT_CARD_EXP_4_DIGIT_YEAR,
field_type_map_[ASCIIToUTF16("year4")]);
}
TEST_F(CreditCardFieldTest, ParseExpMonthYear2) {
FormFieldData field;
field.form_control_type = "text";
field.label = ASCIIToUTF16("Name on Card");
field.name = ASCIIToUTF16("name_on_card");
list_.push_back(new AutofillField(field, ASCIIToUTF16("name1")));
field.label = ASCIIToUTF16("Card Number");
field.name = ASCIIToUTF16("card_number");
list_.push_back(new AutofillField(field, ASCIIToUTF16("number2")));
field.label = ASCIIToUTF16("Expiration date Month / Year");
field.name = ASCIIToUTF16("ExpDate");
list_.push_back(new AutofillField(field, ASCIIToUTF16("month3")));
field.label = ASCIIToUTF16("Expiration date Month / Year");
field.name = ASCIIToUTF16("ExpDate");
list_.push_back(new AutofillField(field, ASCIIToUTF16("year4")));
AutofillScanner scanner(list_.get());
field_.reset(Parse(&scanner));
ASSERT_NE(static_cast<CreditCardField*>(NULL), field_.get());
ASSERT_TRUE(field_->ClassifyField(&field_type_map_));
ASSERT_TRUE(
field_type_map_.find(ASCIIToUTF16("name1")) != field_type_map_.end());
EXPECT_EQ(CREDIT_CARD_NAME, field_type_map_[ASCIIToUTF16("name1")]);
ASSERT_TRUE(
field_type_map_.find(ASCIIToUTF16("number2")) != field_type_map_.end());
EXPECT_EQ(CREDIT_CARD_NUMBER, field_type_map_[ASCIIToUTF16("number2")]);
ASSERT_TRUE(
field_type_map_.find(ASCIIToUTF16("month3")) != field_type_map_.end());
EXPECT_EQ(CREDIT_CARD_EXP_MONTH, field_type_map_[ASCIIToUTF16("month3")]);
ASSERT_TRUE(
field_type_map_.find(ASCIIToUTF16("year4")) != field_type_map_.end());
EXPECT_EQ(CREDIT_CARD_EXP_4_DIGIT_YEAR,
field_type_map_[ASCIIToUTF16("year4")]);
}
TEST_F(CreditCardFieldTest, ParseExpField) {
FormFieldData field;
field.form_control_type = "text";
field.label = ASCIIToUTF16("Name on Card");
field.name = ASCIIToUTF16("name_on_card");
list_.push_back(new AutofillField(field, ASCIIToUTF16("name1")));
field.label = ASCIIToUTF16("Card Number");
field.name = ASCIIToUTF16("card_number");
list_.push_back(new AutofillField(field, ASCIIToUTF16("number2")));
field.label = ASCIIToUTF16("Expiration Date (MM/YYYY)");
field.name = ASCIIToUTF16("cc_exp");
list_.push_back(new AutofillField(field, ASCIIToUTF16("exp3")));
AutofillScanner scanner(list_.get());
field_.reset(Parse(&scanner));
ASSERT_NE(static_cast<CreditCardField*>(NULL), field_.get());
ASSERT_TRUE(field_->ClassifyField(&field_type_map_));
ASSERT_TRUE(
field_type_map_.find(ASCIIToUTF16("name1")) != field_type_map_.end());
EXPECT_EQ(CREDIT_CARD_NAME, field_type_map_[ASCIIToUTF16("name1")]);
ASSERT_TRUE(
field_type_map_.find(ASCIIToUTF16("number2")) != field_type_map_.end());
EXPECT_EQ(CREDIT_CARD_NUMBER, field_type_map_[ASCIIToUTF16("number2")]);
ASSERT_TRUE(
field_type_map_.find(ASCIIToUTF16("exp3")) != field_type_map_.end());
EXPECT_EQ(CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR,
field_type_map_[ASCIIToUTF16("exp3")]);
}
TEST_F(CreditCardFieldTest, ParseExpField2DigitYear) {
FormFieldData field;
field.form_control_type = "text";
field.label = ASCIIToUTF16("Name on Card");
field.name = ASCIIToUTF16("name_on_card");
list_.push_back(new AutofillField(field, ASCIIToUTF16("name1")));
field.label = ASCIIToUTF16("Card Number");
field.name = ASCIIToUTF16("card_number");
list_.push_back(new AutofillField(field, ASCIIToUTF16("number2")));
field.label = ASCIIToUTF16("Expiration Date (MM/YY)");
field.name = ASCIIToUTF16("cc_exp");
list_.push_back(new AutofillField(field, ASCIIToUTF16("exp3")));
AutofillScanner scanner(list_.get());
field_.reset(Parse(&scanner));
ASSERT_NE(static_cast<CreditCardField*>(NULL), field_.get());
ASSERT_TRUE(field_->ClassifyField(&field_type_map_));
ASSERT_TRUE(
field_type_map_.find(ASCIIToUTF16("name1")) != field_type_map_.end());
EXPECT_EQ(CREDIT_CARD_NAME, field_type_map_[ASCIIToUTF16("name1")]);
ASSERT_TRUE(
field_type_map_.find(ASCIIToUTF16("number2")) != field_type_map_.end());
EXPECT_EQ(CREDIT_CARD_NUMBER, field_type_map_[ASCIIToUTF16("number2")]);
ASSERT_TRUE(
field_type_map_.find(ASCIIToUTF16("exp3")) != field_type_map_.end());
EXPECT_EQ(CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR,
field_type_map_[ASCIIToUTF16("exp3")]);
}
TEST_F(CreditCardFieldTest, ParseCreditCardHolderNameWithCCFullName) {
FormFieldData field;
field.form_control_type = "text";
field.label = ASCIIToUTF16("Name");
field.name = ASCIIToUTF16("ccfullname");
list_.push_back(new AutofillField(field, ASCIIToUTF16("name1")));
AutofillScanner scanner(list_.get());
field_.reset(Parse(&scanner));
ASSERT_NE(static_cast<CreditCardField*>(NULL), field_.get());
ASSERT_TRUE(field_->ClassifyField(&field_type_map_));
ASSERT_TRUE(
field_type_map_.find(ASCIIToUTF16("name1")) != field_type_map_.end());
EXPECT_EQ(CREDIT_CARD_NAME, field_type_map_[ASCIIToUTF16("name1")]);
}
| 12,441 | 4,883 |
#include "Etterna/Globals/global.h"
#include "Crash.h"
#include "Core/Services/Locator.hpp"
#include "Core/Platform/Platform.hpp"
#include "Core/Misc/AppInfo.hpp"
#include <CoreServices/CoreServices.h>
#include <sys/types.h>
#include <fmt/format.h>
#if defined(HAVE_UNISTD_H)
#include <unistd.h>
#endif
#include <sys/sysctl.h>
std::string
CrashHandler::GetLogsDirectory()
{
FSRef fs;
char dir[PATH_MAX];
if (FSFindFolder(
kUserDomain, kDomainLibraryFolderType, kDontCreateFolder, &fs) ||
FSRefMakePath(&fs, (UInt8*)dir, PATH_MAX)) {
return "/tmp";
}
return fmt::format("{}/Logs/{}", dir, Core::AppInfo::APP_TITLE);
}
// XXX Can we use LocalizedString here instead?
#define LSTRING(b, x) \
CFBundleCopyLocalizedString((b), CFStringCreateWithCString(kCFAllocatorDefault, x, kCFStringEncodingUTF8), NULL, CFSTR("Localizable"))
void
CrashHandler::InformUserOfCrash(const std::string& sPath)
{
CFBundleRef bundle = CFBundleGetMainBundle();
CFStringRef sAlternate = LSTRING(bundle, fmt::format("Quit {}", Core::AppInfo::APP_TITLE).c_str());
/* XXX Translate these and remove the redefine of LSTRING. Another way to do
* this would be to pass bundle's URL to CFUserNotificationDisplayAlert's
* localizationURL parameter and let it do it. This wouldn't work for sBody
* though. */
CFStringRef sDefault = LSTRING(bundle, "File Bug Report");
CFStringRef sOther = LSTRING(bundle, "Open crashinfo.txt");
CFStringRef sTitle = LSTRING(bundle, fmt::format("{} has crashed", Core::AppInfo::APP_TITLE).c_str());
CFStringRef sFormat = LSTRING(bundle, fmt::format("{} has crashed"
"Debugging information has been output to\n\n%s\n\n"
"Please file a bug report at\n\n%s", Core::AppInfo::APP_TITLE).c_str());
CFStringRef sBody = CFStringCreateWithFormat(
kCFAllocatorDefault, NULL, sFormat, sPath.c_str(), Core::AppInfo::BUG_REPORT_URL);
CFOptionFlags response = kCFUserNotificationCancelResponse;
CFTimeInterval timeout = 0.0; // Should we ever time out?
CFUserNotificationDisplayAlert(timeout,kCFUserNotificationStopAlertLevel,
NULL, NULL, NULL,
sTitle,
sBody,
sDefault,
sAlternate,
sOther,
&response);
switch (response) {
case kCFUserNotificationDefaultResponse:
Core::Platform::openWebsite(Core::AppInfo::BUG_REPORT_URL);
// Fall through.
case kCFUserNotificationOtherResponse:
// Open the file with the default application (probably TextEdit).
Core::Platform::openWebsite("file://" + sPath);
break;
}
CFRelease(sBody);
CFRelease(sFormat);
CFRelease(sTitle);
CFRelease(sOther);
CFRelease(sDefault);
CFRelease(sAlternate);
}
/* IMPORTANT: Because the definition of the kinfo_proc structure (in
* <sys/sysctl.h>) is conditionalized by __APPLE_API_UNSTABLE, you should
* restrict use of the [below] code to the debug build of your program.
* http://developer.apple.com/qa/qa2004/qa1361.html */
bool
CrashHandler::IsDebuggerPresent()
{
#ifdef DEBUG
int ret;
int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
struct kinfo_proc info;
size_t size;
// Initialize the flags so that, if sysctl fails for some bizarre
// reason, we get a predictable result.
info.kp_proc.p_flag = 0;
// Call sysctl.
size = sizeof(info);
ret = sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0);
// We're being debugged if the P_TRACED flag is set.
return ret == 0 && (info.kp_proc.p_flag & P_TRACED) != 0;
#else
return false;
#endif
}
void
CrashHandler::DebugBreak()
{
// TODO: Following command is depreciated.
// DebugStr("\pDebugBreak()");
}
/*
* (c) 2003-2006 Steve Checkoway
* All rights reserved.
*
* 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, and/or sell copies of the Software, and to permit persons to
* whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
* THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS
* INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT
* OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
* OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
| 4,988 | 1,795 |
#include <CGeomLight3D.h>
#include <CGeometry3D.h>
#include <CGeomZBuffer.h>
#include <CGeomPyramid3D.h>
#include <CImageMgr.h>
#include "images/Sun.h"
CGeomLight3DMgr::
CGeomLight3DMgr()
{
}
void
CGeomLight3DMgr::
addLight(CGeomLight3D *light)
{
lights_.push_back(light);
light->setMgr(this);
}
void
CGeomLight3DMgr::
deleteLight(CGeomLight3D *light)
{
LightList::iterator plight1 = lights_.begin();
LightList::iterator plight2 = lights_.end ();
for ( ; plight1 != plight2; ++plight1)
if (*plight1 == light)
break;
if (plight1 != plight2) {
LightList::iterator plight0 = plight1;
++plight1;
for ( ; plight1 != plight2; plight0 = plight1++)
*plight0 = *plight1;
lights_.pop_back();
}
}
void
CGeomLight3DMgr::
modelToPixel(const CGeomCamera3D &camera) const
{
LightList::const_iterator plight1 = lights_.begin();
LightList::const_iterator plight2 = lights_.end ();
for ( ; plight1 != plight2; ++plight1)
(*plight1)->getObject()->modelToPixel(camera);
}
void
CGeomLight3DMgr::
drawWireframe(CGeomCamera3D &, CGeomZBuffer *)
{
//LightList::const_iterator plight1 = lights_.begin();
//LightList::const_iterator plight2 = lights_.end ();
//for ( ; plight1 != plight2; ++plight1)
// (*plight1)->drawWireframe(camera, zbuffer);
}
void
CGeomLight3DMgr::
drawSolid(CGeomCamera3D &, CGeomZBuffer *)
{
//LightList::const_iterator plight1 = lights_.begin();
//LightList::const_iterator plight2 = lights_.end ();
//for ( ; plight1 != plight2; ++plight1)
// (*plight1)->drawSolid(camera, zbuffer);
}
CRGBA
CGeomLight3DMgr::
lightPoint(const CPoint3D &point, const CVector3D &normal, const CMaterial &material) const
{
CRGBA rgba = material.getEmission();
rgba += getAmbient()*material.getAmbient();
LightList::const_iterator plight1 = lights_.begin();
LightList::const_iterator plight2 = lights_.end ();
for ( ; plight1 != plight2; ++plight1)
(*plight1)->lightPoint(rgba, point, normal, material);
rgba.setAlpha(material.getDiffuse().getAlpha());
return rgba;
}
CImagePtr
CGeomLight3DMgr::
getImage()
{
static CImagePtr ptr;
static bool read;
if (! read) {
CImageNameSrc src("CGeomLight3D/Sun");
ptr = CImageMgrInst->createImage(src);
ptr->read(Sun_data, SUN_DATA_LEN);
read = false;
}
return ptr;
}
void
CGeomLight3DMgr::
moveX(double dx)
{
LightList::const_iterator plight1 = lights_.begin();
LightList::const_iterator plight2 = lights_.end ();
for ( ; plight1 != plight2; ++plight1)
(*plight1)->getObject()->moveX(dx);
}
void
CGeomLight3DMgr::
moveY(double dy)
{
LightList::const_iterator plight1 = lights_.begin();
LightList::const_iterator plight2 = lights_.end ();
for ( ; plight1 != plight2; ++plight1)
(*plight1)->getObject()->moveY(dy);
}
void
CGeomLight3DMgr::
moveZ(double dz)
{
LightList::const_iterator plight1 = lights_.begin();
LightList::const_iterator plight2 = lights_.end ();
for ( ; plight1 != plight2; ++plight1)
(*plight1)->getObject()->moveZ(dz);
}
void
CGeomLight3DMgr::
rotateX(double dx)
{
LightList::const_iterator plight1 = lights_.begin();
LightList::const_iterator plight2 = lights_.end ();
for ( ; plight1 != plight2; ++plight1)
(*plight1)->getObject()->rotateX(dx);
}
void
CGeomLight3DMgr::
rotateY(double dy)
{
LightList::const_iterator plight1 = lights_.begin();
LightList::const_iterator plight2 = lights_.end ();
for ( ; plight1 != plight2; ++plight1)
(*plight1)->getObject()->rotateY(dy);
}
void
CGeomLight3DMgr::
rotateZ(double dz)
{
LightList::const_iterator plight1 = lights_.begin();
LightList::const_iterator plight2 = lights_.end ();
for ( ; plight1 != plight2; ++plight1)
(*plight1)->getObject()->rotateZ(dz);
}
//----------
CGeomLight3D::
CGeomLight3D(CGeomScene3D *pscene, const std::string &name)
{
object_ = CGeometryInst->createObject3D(pscene, name);
CGeomPyramid3D::addGeometry(object_, 0, 0, 0, 0.1, 0.1);
object_->rotateModelX(-M_PI*0.5);
object_->unsetFaceFlags(CGeomFace3D::LIGHTED);
object_->setFaceColor(CRGBA(1,1,0));
}
CGeomLight3D::
CGeomLight3D(const CGeomLight3D &light) :
mgr_ (light.mgr_),
object_ (light.object_),
data_ (light.data_),
enabled_(light.enabled_)
{
}
CGeomLight3D &
CGeomLight3D::
operator=(const CGeomLight3D &light)
{
mgr_ = light.mgr_;
object_ = light.object_;
data_ = light.data_;
enabled_ = light.enabled_;
return *this;
}
void
CGeomLight3D::
drawImage(CGeomZBuffer *zbuffer)
{
if (mgr_) {
CImagePtr image = mgr_->getImage();
const CPoint3D &pixel = object_->getPositionPoint().getPixel();
zbuffer->drawImage(int(pixel.x), int(pixel.y), pixel.z, image);
}
}
void
CGeomLight3D::
lightPoint(CRGBA &rgba, const CPoint3D &point, const CVector3D &normal,
const CMaterial &material) const
{
if (! getEnabled())
return;
// Ambient
CRGBA ambient = getAmbient()*material.getAmbient();
// Diffuse
CVector3D dlight(point, object_->getPositionPoint().getViewed());
dlight.normalize();
//uncomment if light both sides
//double dot = fabs(dlight.dotProduct(normal));
double dot = dlight.dotProduct(normal);
if (dot < 0.0)
dot = 0.0;
CRGBA diffuse = dot*getDiffuse()*material.getDiffuse();
// Specular
CRGBA specular(0,0,0,1);
if (dot > 0.0) {
CVector3D viewpoint(0,0,1);
CVector3D sum(viewpoint + dlight);
sum.normalize();
double dot1 = sum.dotProduct(normal);
if (dot1 < 0.0)
dot1 = 0.0;
specular = pow(dot1, material.getShininess())*getSpecular()*material.getSpecular();
}
double dist = CVector3D(point, object_->getPositionPoint().getViewed()).length();
rgba += getAttenuation(dist)*getSpotEffect(point)*(ambient + diffuse + specular);
//rgba += diffuse;
rgba.setAlpha(material.getDiffuse().getAlpha());
}
| 5,855 | 2,314 |
//
// main.cpp
// Fast Fibonacci
//
// Created by MacBook on 02/05/17.
// Copyright © 2017 Bruno Botelho. All rights reserved.
//
#include <stdio.h>
#include <math.h>
int main(int argc, const char * argv[]) {
// insert code here...
int n;
double result;
scanf("%d",&n);
result= pow(((1+sqrt(5))/2.0),n)-pow((1-sqrt(5))/2.0, n);
result/=sqrt(5);
printf("%.1lf\n",result);
return 0;
}
| 461 | 202 |
/*
* @Description: GNSS 坐标做观测时使用的先验边
* @Author: Ren Qian
* @Date: 2020-03-01 18:05:35
*/
#ifndef LIDAR_LOCALIZATION_MODELS_GRAPH_OPTIMIZER_G2O_EDGE_EDGE_SE3_PRIORXYZ_HPP_
#define LIDAR_LOCALIZATION_MODELS_GRAPH_OPTIMIZER_G2O_EDGE_EDGE_SE3_PRIORXYZ_HPP_
#include <g2o/types/slam3d/types_slam3d.h>
#include <g2o/types/slam3d_addons/types_slam3d_addons.h>
namespace g2o {
class EdgeSE3PriorXYZ : public g2o::BaseUnaryEdge<3, Eigen::Vector3d, g2o::VertexSE3> {
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
EdgeSE3PriorXYZ()
:g2o::BaseUnaryEdge<3, Eigen::Vector3d, g2o::VertexSE3>() {
}
void computeError() override {
const g2o::VertexSE3* v1 = static_cast<const g2o::VertexSE3*>(_vertices[0]);
Eigen::Vector3d estimate = v1->estimate().translation();
_error = estimate - _measurement;
}
void setMeasurement(const Eigen::Vector3d& m) override {
_measurement = m;
}
virtual bool read(std::istream& is) override {
Eigen::Vector3d v;
is >> v(0) >> v(1) >> v(2);
setMeasurement(Eigen::Vector3d(v));
for (int i = 0; i < information().rows(); ++i) {
for (int j = i; j < information().cols(); ++j) {
is >> information()(i, j);
// update cross-diagonal element:
if (i != j) {
information()(j, i) = information()(i, j);
}
}
}
return true;
}
virtual bool write(std::ostream& os) const override {
Eigen::Vector3d v = _measurement;
os << v(0) << " " << v(1) << " " << v(2) << " ";
for (int i = 0; i < information().rows(); ++i)
for (int j = i; j < information().cols(); ++j)
os << " " << information()(i, j);
return os.good();
}
};
}
#endif
| 1,626 | 767 |
// Copyright 2016-2021 Doug Moen
// Licensed under the Apache License, version 2.0
// See accompanying file LICENSE or https://www.apache.org/licenses/LICENSE-2.0
#include <libcurv/program.h>
#include <libcurv/analyser.h>
#include <libcurv/builtin.h>
#include <libcurv/context.h>
#include <libcurv/definition.h>
#include <libcurv/exception.h>
#include <libcurv/parser.h>
#include <libcurv/scanner.h>
#include <libcurv/system.h>
namespace curv {
struct File_Phrase : public Phrase
{
Src_Loc loc_;
File_Phrase(const Filesystem::path& path, Source::Type type)
:
loc_{make<Source>(path.string(), type), Token{}}
{
}
virtual Src_Loc location() const override { return loc_; }
virtual Shared<Meaning> analyse(Environ& env, Interp) const override
{
throw Exception(At_Phrase(*this, env),
"internal error: File_Phrase::analyse");
}
};
void
Program::compile(Shared<const Source> source, Scanner_Opts scopts,
Environ& env, Interp terp)
{
Scanner scanner(move(source), sstate_, scopts);
phrase_ = parse_program(scanner);
if (auto def = phrase_->as_definition(env, Fail::soft)) {
module_ = analyse_module(*def, env);
} else {
meaning_ = phrase_->analyse(env, terp);
}
frame_ = {make_tail_array<Frame>(env.frame_maxslots_,
sstate_, sstate_.file_frame_, nullptr, nullptr)};
}
void
Program::compile(Shared<const Source> source, Environ& env, Interp terp)
{
compile(move(source), Scanner_Opts(), env, terp);
}
void
Program::compile(Shared<const Source> source)
{
Builtin_Environ env{sstate_.system_.std_namespace(), sstate_};
compile(move(source), env, Interp::expr());
}
void
Program::compile(Shared<const Source> source, Scanner_Opts scopts)
{
Builtin_Environ env{sstate_.system_.std_namespace(), sstate_};
compile(move(source), scopts, env, Interp::expr());
}
void
Program::compile(Filesystem::path path, Source::Type type, Value val)
{
value_ = val;
phrase_ = make<File_Phrase>(path, type);
}
const Phrase&
Program::syntax()
const
{
return *nub_phrase(phrase_);
}
Value
Program::eval()
{
if (value_)
return value_;
else if (module_ != nullptr) {
throw Exception(At_Program(*this),
"definition found; expecting an expression");
} else {
auto expr = meaning_->to_operation(sstate_);
frame_->next_op_ = &*expr;
return tail_eval_frame(move(frame_));
}
}
Shared<Module>
Program::exec(Operation::Executor& ex)
{
if (value_) {
ex.push_value(value_, At_Program(*this));
return nullptr;
} else if (module_) {
return module_->eval_module(*frame_);
} else {
auto op = meaning_->to_operation(sstate_);
op->exec(*frame_, ex);
return nullptr;
}
}
} // namespace curv
| 2,834 | 971 |
#include <set>
#include <queue>
#include <string>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <climits>
#include <iostream>
#include <map>
#include <cmath>
#include <algorithm>
using namespace std;
#define pr(x) //(cout << #x << ' ' << x << ' ')
#define prln(x) //(cout << #x << ' ' << x << endl)
#define ll long long
void file()
{
freopen("in.txt", "r", stdin);
}
int main()
{
//file();
int n;
prln(1111);
scanf("%d", &n);
int cnt = 0;
prln(n);
for (int i = 1; i <= n; ++i){
prln(11);
for (int j = i + 1; j <= n; ++j){
int temp = i * i + j * j;
int k = sqrt(temp);
if (k > n)
continue;
if (k * k != temp)
continue;
if (i + j > k && i + k > j &&
j + k > i)
cnt++;
}
}
prln(12333);
printf("%d\n", cnt);
return 0;
}
| 956 | 371 |
/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* 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 "stdafx.h"
#include "common/shared_types.h"
#include "system/globalenv.h"
#include "context/static_context.h"
#include "runtime/fnput/fnput.h"
#include "store/api/pul.h"
#include "store/api/item_factory.h"
#include "store/api/copymode.h"
#include "zorbatypes/URI.h"
#include <zorba/internal/unique_ptr.h>
namespace zorba
{
/*******************************************************************************
fn:put
********************************************************************************/
bool FnPutIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
store::Item_t node;
store::Item_t uriItem;
zstring uriString;
zstring resolvedUriString;
URI lTargetUri;
store::Item_t resolvedUriItem;
std::unique_ptr<store::PUL> pul;
PlanIteratorState* state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
consumeNext(node, theChildren[0].getp(), planState);
if (node->getNodeKind()==store::StoreConsts::attributeNode)
{
throw XQUERY_EXCEPTION(
err::FOUP0001,
ERROR_LOC( loc )
);
}
consumeNext(uriItem, theChildren[1].getp(), planState);
uriString = uriItem->getStringValue();
#if 1
resolvedUriString = theSctx->resolve_relative_uri(uriString, false);
GENV_ITEMFACTORY->createAnyURI(resolvedUriItem, resolvedUriString);
#else
GENV_ITEMFACTORY->createAnyURI(resolvedUriItem, uriString);
#endif
try
{
lTargetUri = URI(uriString);
}
catch (XQueryException& e)
{
set_source(e, loc);
e.set_diagnostic(err::FOUP0002);
throw;
}
pul.reset(GENV_ITEMFACTORY->createPendingUpdateList());
pul->addPut(&loc, node, resolvedUriItem);
result = pul.release();
STACK_PUSH(true, state);
STACK_END(state);
}
}
/* vim:set et sw=2 ts=2: */
| 2,391 | 823 |
#include "stdafx.h"
#include "PostprocessAnimator.h"
#include "../xrEngine/effectorPP.h"
#include "../xrEngine/ObjectAnimator.h"
#include "object_broker.h"
#include "Actor.h"
void GAME_API AddEffector(CActor* A, int type, const shared_str& sect_name)
{
bool bCyclic = false;
if (pSettings->line_exist(sect_name, "pp_eff_name"))
{
bCyclic = pSettings->r_bool(sect_name, "pp_eff_cyclic");
CPostprocessAnimator* pp_anm = xr_new<CPostprocessAnimator>();
pp_anm->bOverlap = pSettings->r_bool(sect_name, "pp_eff_overlap");
pp_anm->SetType((EEffectorPPType)type);
pp_anm->SetCyclic(bCyclic);
LPCSTR fn = pSettings->r_string(sect_name, "pp_eff_name");
pp_anm->Load(fn);
A->Cameras().AddPPEffector(pp_anm);
}
if (pSettings->line_exist(sect_name, "cam_eff_name"))
{
bCyclic = pSettings->r_bool(sect_name, "cam_eff_cyclic");
CAnimatorCamEffector* cam_anm = xr_new<CAnimatorCamEffector>();
cam_anm->SetType((ECamEffectorType)type);
cam_anm->SetCyclic(bCyclic);
if (pSettings->line_exist(sect_name, "cam_eff_hud_affect"))
cam_anm->SetHudAffect(pSettings->r_bool(sect_name, "cam_eff_hud_affect"));
LPCSTR fn = pSettings->r_string(sect_name, "cam_eff_name");
cam_anm->Start(fn);
A->Cameras().AddCamEffector(cam_anm);
}
}
void GAME_API AddEffector(CActor* A, int type, const shared_str& sect_name, CEffectorController* ec)
{
bool bCyclic = false;
if (pSettings->line_exist(sect_name, "pp_eff_name"))
{
bCyclic = pSettings->r_bool(sect_name, "pp_eff_cyclic");
CPostprocessAnimatorControlled* pp_anm = xr_new<CPostprocessAnimatorControlled>(ec);
pp_anm->SetType((EEffectorPPType)type);
pp_anm->SetCyclic(bCyclic);
pp_anm->bOverlap = pSettings->r_bool(sect_name, "pp_eff_overlap");
LPCSTR fn = pSettings->r_string(sect_name, "pp_eff_name");
pp_anm->Load(fn);
A->Cameras().AddPPEffector(pp_anm);
}
if (pSettings->line_exist(sect_name, "cam_eff_name"))
{
bCyclic = pSettings->r_bool(sect_name, "cam_eff_cyclic");
CCameraEffectorControlled* cam_anm = xr_new<CCameraEffectorControlled>(ec);
cam_anm->SetType((ECamEffectorType)type);
cam_anm->SetCyclic(bCyclic);
if (pSettings->line_exist(sect_name, "cam_eff_hud_affect"))
cam_anm->SetHudAffect(pSettings->r_bool(sect_name, "cam_eff_hud_affect"));
LPCSTR fn = pSettings->r_string(sect_name, "cam_eff_name");
cam_anm->Start(fn);
A->Cameras().AddCamEffector(cam_anm);
}
}
void GAME_API AddEffector(CActor* A, int type, const shared_str& sect_name, GET_KOEFF_FUNC k_func)
{
bool bCyclic = false;
if (pSettings->line_exist(sect_name, "pp_eff_name"))
{
bCyclic = pSettings->r_bool(sect_name, "pp_eff_cyclic");
CPostprocessAnimatorLerp* pp_anm = xr_new<CPostprocessAnimatorLerp>();
pp_anm->SetType((EEffectorPPType)type);
pp_anm->SetCyclic(bCyclic);
pp_anm->bOverlap = !!pSettings->r_bool(sect_name, "pp_eff_overlap");
LPCSTR fn = pSettings->r_string(sect_name, "pp_eff_name");
pp_anm->SetFactorFunc(k_func);
pp_anm->Load(fn);
A->Cameras().AddPPEffector(pp_anm);
}
if (pSettings->line_exist(sect_name, "cam_eff_name"))
{
bCyclic = pSettings->r_bool(sect_name, "cam_eff_cyclic");
CAnimatorCamLerpEffector* cam_anm = xr_new<CAnimatorCamLerpEffector>();
cam_anm->SetFactorFunc(k_func);
cam_anm->SetType((ECamEffectorType)type);
cam_anm->SetCyclic(bCyclic);
if (pSettings->line_exist(sect_name, "cam_eff_hud_affect"))
cam_anm->SetHudAffect(pSettings->r_bool(sect_name, "cam_eff_hud_affect"));
LPCSTR fn = pSettings->r_string(sect_name, "cam_eff_name");
cam_anm->Start(fn);
A->Cameras().AddCamEffector(cam_anm);
}
}
void GAME_API AddEffector(CActor* A, int type, const shared_str& sect_name, float factor)
{
clamp(factor, 0.001f, 1.5f);
bool bCyclic = false;
if (pSettings->line_exist(sect_name, "pp_eff_name"))
{
bCyclic = pSettings->r_bool(sect_name, "pp_eff_cyclic");
CPostprocessAnimatorLerpConst* pp_anm = xr_new<CPostprocessAnimatorLerpConst>();
pp_anm->SetType((EEffectorPPType)type);
pp_anm->SetCyclic(bCyclic);
pp_anm->SetPower(factor);
pp_anm->bOverlap = pSettings->r_bool(sect_name, "pp_eff_overlap");
LPCSTR fn = pSettings->r_string(sect_name, "pp_eff_name");
pp_anm->Load(fn);
A->Cameras().AddPPEffector(pp_anm);
}
if (pSettings->line_exist(sect_name, "cam_eff_name"))
{
bCyclic = pSettings->r_bool(sect_name, "cam_eff_cyclic");
CAnimatorCamLerpEffectorConst* cam_anm = xr_new<CAnimatorCamLerpEffectorConst>();
cam_anm->SetFactor(factor);
cam_anm->SetType((ECamEffectorType)type);
cam_anm->SetCyclic(bCyclic);
if (pSettings->line_exist(sect_name, "cam_eff_hud_affect"))
cam_anm->SetHudAffect(pSettings->r_bool(sect_name, "cam_eff_hud_affect"));
LPCSTR fn = pSettings->r_string(sect_name, "cam_eff_name");
cam_anm->Start(fn);
A->Cameras().AddCamEffector(cam_anm);
}
}
void GAME_API RemoveEffector(CActor* A, int type)
{
A->Cameras().RemoveCamEffector((ECamEffectorType)type);
A->Cameras().RemovePPEffector((EEffectorPPType)type);
}
CEffectorController::~CEffectorController()
{
R_ASSERT(!m_ce&&!m_pe);
}
CAnimatorCamEffector::CAnimatorCamEffector()
{
m_bCyclic = true;
m_objectAnimator = xr_new<CObjectAnimator>();
m_bAbsolutePositioning = false;
m_fov = -1.0f;
}
CAnimatorCamEffector::~CAnimatorCamEffector()
{
delete_data(m_objectAnimator);
}
void CAnimatorCamEffector::Start(LPCSTR fn)
{
m_objectAnimator->Load(fn);
m_objectAnimator->Play(Cyclic());
fLifeTime = m_objectAnimator->GetLength();
}
BOOL CAnimatorCamEffector::Valid()
{
if (Cyclic())
return TRUE;
return inherited::Valid();
}
BOOL CAnimatorCamEffector::ProcessCam(SCamEffectorInfo& info)
{
if (!inherited::ProcessCam(info))
return FALSE;
const Fmatrix& m = m_objectAnimator->XFORM();
m_objectAnimator->Update(Device.fTimeDelta);
if (!m_bAbsolutePositioning)
{
Fmatrix Mdef;
Mdef.identity();
Mdef.j = info.n;
Mdef.k = info.d;
Mdef.i.crossproduct(info.n, info.d);
Mdef.c = info.p;
Fmatrix mr;
mr.mul(Mdef, m);
info.d = mr.k;
info.n = mr.j;
info.p = mr.c;
}
else
{
info.d = m.k;
info.n = m.j;
info.p = m.c;
}
if (m_fov > 0.0f)
info.fFov = m_fov;
return TRUE;
}
BOOL CAnimatorCamLerpEffector::ProcessCam(SCamEffectorInfo& info)
{
if (!inherited::inherited::ProcessCam(info))
return FALSE;
const Fmatrix& m = m_objectAnimator->XFORM();
m_objectAnimator->Update(Device.fTimeDelta);
Fmatrix Mdef;
Mdef.identity();
Mdef.j = info.n;
Mdef.k = info.d;
Mdef.i.crossproduct(info.n, info.d);
Mdef.c = info.p;
Fmatrix mr;
mr.mul(Mdef, m);
Fquaternion q_src, q_dst, q_res;
q_src.set(Mdef);
q_dst.set(mr);
float t = m_func();
clamp(t, 0.0f, 1.0f);
VERIFY(t >= 0.f && t <= 1.f);
q_res.slerp(q_src, q_dst, t);
Fmatrix res;
res.rotation(q_res);
res.c.lerp(info.p, mr.c, t);
info.d = res.k;
info.n = res.j;
info.p = res.c;
if (m_fov > 0.0f)
info.fFov = m_fov;
return TRUE;
}
CAnimatorCamLerpEffectorConst::CAnimatorCamLerpEffectorConst() :m_factor(0.0f)
{
SetFactorFunc(GET_KOEFF_FUNC(this, &CAnimatorCamLerpEffectorConst::GetFactor));
}
CCameraEffectorControlled::CCameraEffectorControlled(CEffectorController* c) : m_controller(c)
{
m_controller->SetCam(this);
SetFactorFunc(GET_KOEFF_FUNC(m_controller, &CEffectorController::GetFactor));
}
CCameraEffectorControlled::~CCameraEffectorControlled()
{
m_controller->SetCam(nullptr);
}
BOOL CCameraEffectorControlled::Valid()
{
return m_controller->Valid();
}
static const float SND_MIN_VOLUME_FACTOR = 0.1f;
SndShockEffector::SndShockEffector()
{
m_snd_length = 0.0f;
m_cur_length = 0.0f;
m_stored_volume = -1.0f;
m_actor = nullptr;
}
SndShockEffector::~SndShockEffector()
{
psSoundVFactor = m_stored_volume;
if (m_actor && (m_ce || m_pe))
RemoveEffector(m_actor, effHit);
R_ASSERT(!m_ce && !m_pe);
}
BOOL SndShockEffector::Valid()
{
return (m_cur_length<=m_snd_length);
}
BOOL SndShockEffector::InWork()
{
return inherited::Valid();
}
float SndShockEffector::GetFactor()
{
float f = (m_end_time - Device.fTimeGlobal) / m_life_time;
float ff = f * m_life_time / 8.0f;
return clampr(ff, 0.0f, 1.0f);
}
void SndShockEffector::Start(CActor* A, float snd_length, float power)
{
clamp(power, 0.1f, 1.5f);
m_actor = A;
m_snd_length = snd_length;
if (m_stored_volume < 0.0f)
m_stored_volume = psSoundVFactor;
m_cur_length = 0;
psSoundVFactor = m_stored_volume * SND_MIN_VOLUME_FACTOR;
static float xxx = 6.0f / 1.50f; //6sec on max power(1.5)
m_life_time = power * xxx;
m_end_time = Device.fTimeGlobal + m_life_time;
AddEffector(A, effHit, "snd_shock_effector", this);
}
void SndShockEffector::Update()
{
m_cur_length += Device.dwTimeDelta;
float x = float(m_cur_length) / m_snd_length;
float y = 2.f * x - 1;
if (y > 0.f)
psSoundVFactor = y * (m_stored_volume - m_stored_volume * SND_MIN_VOLUME_FACTOR) + m_stored_volume * SND_MIN_VOLUME_FACTOR;
}
static const float DELTA_ANGLE_XYZ = 0.5f * PI / 180;
static const float ANGLE_SPEED = 1.5f;
const float _base_fov = 170.f;
const float _max_fov_add = 30.f;
CControllerPsyHitCamEffector::CControllerPsyHitCamEffector(ECamEffectorType type, const Fvector &src_pos, const Fvector &target_pos, float time, float base_fov, float dest_fov)
: inherited(eCEControllerPsyHit, flt_max)
{
m_base_fov = base_fov;
m_dest_fov = dest_fov;
m_time_total = time;
m_time_current = 0;
m_dangle_target.set(angle_normalize(Random.randFs(DELTA_ANGLE_XYZ)), angle_normalize(Random.randFs(DELTA_ANGLE_XYZ)), angle_normalize(Random.randFs(DELTA_ANGLE_XYZ)));
m_dangle_current.set(0.f, 0.f, 0.f);
m_position_source = src_pos;
m_direction.sub(target_pos, src_pos);
m_distance = m_direction.magnitude();
m_direction.normalize();
}
BOOL CControllerPsyHitCamEffector::ProcessCam(SCamEffectorInfo& info)
{
Fmatrix Mdef;
Mdef.identity();
Mdef.j.set(info.n);
Mdef.k.set(m_direction);
Mdef.i.crossproduct(info.n, m_direction);
Mdef.c.set(info.p);
//////////////////////////////////////////////////////////////////////////
if (angle_lerp(m_dangle_current.x, m_dangle_target.x, ANGLE_SPEED, Device.fTimeDelta))
m_dangle_target.x = angle_normalize(Random.randFs(DELTA_ANGLE_XYZ));
if (angle_lerp(m_dangle_current.y, m_dangle_target.y, ANGLE_SPEED, Device.fTimeDelta))
m_dangle_target.y = angle_normalize(Random.randFs(DELTA_ANGLE_XYZ));
if (angle_lerp(m_dangle_current.z, m_dangle_target.z, ANGLE_SPEED, Device.fTimeDelta))
m_dangle_target.z = angle_normalize(Random.randFs(DELTA_ANGLE_XYZ));
//////////////////////////////////////////////////////////////////////////
if (m_time_current > m_time_total)
m_time_current = m_time_total;
float perc_past = m_time_current / m_time_total;
float cur_dist = m_distance * perc_past;
Mdef.c.mad(m_position_source, m_direction, cur_dist);
info.fFov = m_base_fov + (m_dest_fov - m_base_fov) * perc_past;
m_time_current += Device.fTimeDelta;
//////////////////////////////////////////////////////////////////////////
// Установить углы смещения
Fmatrix R;
if (m_time_current > m_time_total)
R.identity();
else
R.setHPB(m_dangle_current.x, m_dangle_current.y, m_dangle_current.z);
Fmatrix mR;
mR.mul(Mdef, R);
info.d.set(mR.k);
info.n.set(mR.j);
info.p.set(mR.c);
return TRUE;
}
bool similar_cam_info(const SCamEffectorInfo& c1, const SCamEffectorInfo& c2)
{
return(c1.p.similar(c2.p, EPS_L) && c1.d.similar(c2.d, EPS_L) && c1.n.similar(c2.n, EPS_L) && c1.r.similar(c2.r, EPS_L));
}
void CActorCameraManager::UpdateCamEffectors()
{
m_cam_info_hud = m_cam_info;
inherited::UpdateCamEffectors();
m_cam_info_hud.d.normalize();
m_cam_info_hud.n.normalize();
m_cam_info_hud.r.crossproduct(m_cam_info_hud.n, m_cam_info_hud.d);
m_cam_info_hud.n.crossproduct(m_cam_info_hud.d, m_cam_info_hud.r);
}
void GAME_API cam_effector_sub(const SCamEffectorInfo& c1, const SCamEffectorInfo& c2, SCamEffectorInfo& dest)
{
dest.p.sub(c1.p, c2.p);
dest.d.sub(c1.d, c2.d);
dest.n.sub(c1.n, c2.n);
dest.r.sub(c1.r, c2.r);
}
void GAME_API cam_effector_add(const SCamEffectorInfo& diff, SCamEffectorInfo& dest)
{
dest.p.add(diff.p);
dest.d.add(diff.d);
dest.n.add(diff.n);
dest.r.add(diff.r);
}
bool CActorCameraManager::ProcessCameraEffector(CEffectorCam* eff)
{
SCamEffectorInfo prev = m_cam_info;
bool res = inherited::ProcessCameraEffector(eff);
if (res)
{
if (eff->GetHudAffect())
{
SCamEffectorInfo affected = m_cam_info;
SCamEffectorInfo diff;
cam_effector_sub(affected, prev, diff);
cam_effector_add(diff, m_cam_info_hud);
}
m_cam_info_hud.fFov = m_cam_info.fFov;
m_cam_info_hud.fFar = m_cam_info.fFar;
m_cam_info_hud.fAspect = m_cam_info.fAspect;
}
return res;
}
void CAnimatorCamEffectorScriptCB::ProcessIfInvalid(SCamEffectorInfo& info)
{
if (m_bAbsolutePositioning)
{
const Fmatrix& m = m_objectAnimator->XFORM();
info.d = m.k;
info.n = m.j;
info.p = m.c;
if (m_fov > 0.0f)
info.fFov = m_fov;
}
}
#include "ai_space.h"
#include "script_engine.h"
#include <luabind/luabind.hpp>
BOOL CAnimatorCamEffectorScriptCB::Valid()
{
BOOL res = inherited::Valid();
if (!res && cb_name.size())
{
luabind::functor<LPCSTR> fl;
R_ASSERT(ai().script_engine().functor<LPCSTR>(*cb_name, fl));
fl();
cb_name = "";
}
return res;
} | 13,202 | 6,187 |
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "miner.h"
#include "amount.h"
#include "chainparams.h"
#include "consensus/consensus.h"
#include "consensus/merkle.h"
#include "consensus/tx_verify.h"
#include "consensus/validation.h"
#include "hash.h"
#include "main.h"
#include "maxblocksize.h"
#include "net.h"
#include "policy/policy.h"
#include "pow.h"
#include "primitives/transaction.h"
#include "timedata.h"
#include "util.h"
#include "utilmoneystr.h"
#include "options.h"
#include "validationinterface.h"
#include <boost/thread.hpp>
#include <boost/tuple/tuple.hpp>
#include <stack>
#include <iomanip>
#include <cmath>
using namespace std;
//////////////////////////////////////////////////////////////////////////////
//
// BitcoinMiner
//
//
// Unconfirmed transactions in the memory pool often depend on other
// transactions in the memory pool. When we select transactions from the
// pool, we select by highest or fee rate, so we might consider
// transactions that depend on transactions that aren't yet in the block.
uint64_t nLastBlockTx = 0;
uint64_t nLastBlockSize = 0;
void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
{
pblock->nTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
// Updating time can change work required on testnet:
if (consensusParams.fPowAllowMinDifficultyBlocks)
pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
}
// BIP100 string:
// - Adds our block size vote (B) if configured.
// - Adds Excessive Block (EB) string. This announces how big blocks we currently accept.
std::vector<unsigned char> BIP100Str(uint64_t hardLimit) {
uint64_t blockVote = Opt().MaxBlockSizeVote();
std::stringstream ss;
ss << "/BIP100/";
if (blockVote)
ss << "B" << blockVote << "/";
double dMaxBlockSize = double(hardLimit)/1000000;
ss << "EB" << std::setprecision(int(log10(dMaxBlockSize))+7) << dMaxBlockSize << "/";
const std::string s = ss.str();
return std::vector<unsigned char>(begin(s), end(s));
}
CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
{
const CChainParams& chainparams = Params();
// Create new block
unique_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
if(!pblocktemplate.get())
return NULL;
CBlock *pblock = &pblocktemplate->block; // pointer for convenience
// Create coinbase tx
CMutableTransaction txNew;
txNew.vin.resize(1);
txNew.vin[0].prevout.SetNull();
txNew.vout.resize(1);
txNew.vout[0].scriptPubKey = scriptPubKeyIn;
// Add dummy coinbase tx as first transaction
pblock->vtx.push_back(CTransaction());
pblocktemplate->vTxFees.push_back(-1); // updated at end
pblocktemplate->vTxSigOps.push_back(-1); // updated at end
// Largest block you're willing to create:
uint64_t hardLimit = GetNextMaxBlockSize(chainActive.Tip(), chainparams.GetConsensus());
uint64_t nBlockMaxSize = GetArg("-blockmaxsize", hardLimit);
// Limit to between 1K and (hard limit - 1K) for sanity:
nBlockMaxSize = std::max((uint64_t)1000, std::min((hardLimit - 1000), nBlockMaxSize));
// For compatibility with bip68-sequence test, set flag to not mine txs with negative fee delta.
const bool fSkipNegativeDelta = GetBoolArg("-bip68hack", false);
// Collect memory pool transactions into the block
CTxMemPool::setEntries inBlock;
CTxMemPool::setEntries gotParents;
std::stack<CTxMemPool::txiter, std::vector<CTxMemPool::txiter>> clearedTxs;
uint64_t nBlockSize = 1000;
uint64_t nBlockTx = 0;
unsigned int nBlockSigOps = 100;
int lastFewTxs = 0;
CAmount nFees = 0;
{
LOCK2(cs_main, mempool.cs);
CBlockIndex* pindexPrev = chainActive.Tip();
const int nHeight = pindexPrev->nHeight + 1;
pblock->nTime = GetAdjustedTime();
const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
pblock->nVersion = ComputeBlockVersion(pindexPrev, chainparams.GetConsensus());
// -regtest only: allow overriding block.nVersion with
// -blockversion=N to test forking scenarios
if (Params().MineBlocksOnDemand())
pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
? nMedianTimePast
: pblock->GetBlockTime();
CTxMemPool::indexed_transaction_set::nth_index<3>::type::iterator mi = mempool.mapTx.get<3>().begin();
CTxMemPool::txiter iter;
while (mi != mempool.mapTx.get<3>().end() || !clearedTxs.empty())
{
if (clearedTxs.empty()) { // add tx with next highest score
iter = mempool.mapTx.project<0>(mi);
mi++;
}
else { // try to add a previously cleared tx
iter = clearedTxs.top();
clearedTxs.pop();
}
if (inBlock.count(iter)) {
continue;
}
const CTransaction& tx = iter->GetTx();
if (fSkipNegativeDelta && mempool.GetFeeModifier().GetDelta(tx.GetHash()) < 0) {
continue;
}
// Our index guarantees that all ancestors are paid for.
// If it has parents, push this tx, then its parents, onto the stack.
// The second time we process a tx, just make sure all parents are in the block
bool fAllParentsInBlock = true;
bool fPushedAParent = false;
bool fFirstTime = !gotParents.count(iter);
gotParents.insert(iter);
BOOST_FOREACH(CTxMemPool::txiter parent, mempool.GetMemPoolParents(iter))
{
if (!inBlock.count(parent)) {
fAllParentsInBlock = false;
if (fFirstTime) {
if (!fPushedAParent) {
clearedTxs.push(iter);
fPushedAParent = true;
}
clearedTxs.push(parent);
}
}
}
if (fPushedAParent || !fAllParentsInBlock) {
continue;
}
unsigned int nTxSize = iter->GetTxSize();
if (nBlockSize + nTxSize >= nBlockMaxSize) {
if (nBlockSize > nBlockMaxSize - 100 || lastFewTxs > 50) {
break;
}
// Once we're within 1000 bytes of a full block, only look at 50 more txs
// to try to fill the remaining space.
if (nBlockSize > nBlockMaxSize - 1000) {
lastFewTxs++;
}
continue;
}
if (!IsFinalTx(tx, nHeight, nLockTimeCutoff))
continue;
// TODO: with more complexity we could make the block bigger when
// sigop-constrained and sigop density in later megabytes is low
unsigned int nTxSigOps = iter->GetSigOpCount();
if (nBlockSigOps + nTxSigOps >= MaxBlockSigops(nBlockSize)) {
if (nBlockSigOps > MaxBlockSigops(nBlockSize) - 2) {
break;
}
continue;
}
CAmount nTxFees = iter->GetFee();
// Added
pblock->vtx.push_back(tx);
pblocktemplate->vTxFees.push_back(nTxFees);
pblocktemplate->vTxSigOps.push_back(nTxSigOps);
nBlockSize += nTxSize;
++nBlockTx;
nBlockSigOps += nTxSigOps;
nFees += nTxFees;
inBlock.insert(iter);
}
nLastBlockTx = nBlockTx;
nLastBlockSize = nBlockSize;
LogPrintf("CreateNewBlock(): total size %u txs: %u fees: %ld sigops %d\n", nBlockSize, nBlockTx, nFees, nBlockSigOps);
// Compute final coinbase transaction.
txNew.vout[0].nValue = nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus());
txNew.vin[0].scriptSig = CScript() << nHeight << BIP100Str(hardLimit) << OP_0;
pblock->vtx[0] = txNew;
pblocktemplate->vTxFees[0] = -nFees;
// Fill in header
pblock->hashPrevBlock = pindexPrev->GetBlockHash();
UpdateTime(pblock, Params().GetConsensus(), pindexPrev);
pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
pblock->nNonce = 0;
pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
CValidationState state;
if (!TestBlockValidity(state, *pblock, pindexPrev, false, false)) {
throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, FormatStateMessage(state)));
}
}
return pblocktemplate.release();
}
void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, uint64_t nMaxBlockSize)
{
// Update nExtraNonce
static uint256 hashPrevBlock;
if (hashPrevBlock != pblock->hashPrevBlock)
{
nExtraNonce = 0;
hashPrevBlock = pblock->hashPrevBlock;
}
++nExtraNonce;
unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
CMutableTransaction txCoinbase(pblock->vtx[0]);
txCoinbase.vin[0].scriptSig = (CScript() << nHeight << BIP100Str(nMaxBlockSize) << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
assert(txCoinbase.vin[0].scriptSig.size() <= 100);
pblock->vtx[0] = txCoinbase;
pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);
}
//////////////////////////////////////////////////////////////////////////////
//
// Internal miner
//
//
// ScanHash scans nonces looking for a hash with at least some zero bits.
// The nonce is usually preserved between calls, but periodically or if the
// nonce is 0xffff0000 or above, the block is rebuilt and nNonce starts over at
// zero.
//
bool static ScanHash(const CBlockHeader *pblock, uint32_t& nNonce, uint256 *phash)
{
// Write the first 76 bytes of the block header to a double-SHA256 state.
CHash256 hasher;
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << *pblock;
assert(ss.size() == 80);
hasher.Write((unsigned char*)&ss[0], 76);
while (true) {
nNonce++;
// Write the last 4 bytes of the block header (the nonce) to a copy of
// the double-SHA256 state, and compute the result.
CHash256(hasher).Write((unsigned char*)&nNonce, 4).Finalize((unsigned char*)phash);
// Return the nonce if the hash has at least some zero bits,
// caller will check if it has enough to reach the target
if (((uint16_t*)phash)[15] == 0)
return true;
// If nothing found after trying for a while, return -1
if ((nNonce & 0xfff) == 0)
return false;
}
}
static bool ProcessBlockFound(CBlock* pblock, const CChainParams& chainparams, CConnman* connman)
{
LogPrintf("%s\n", pblock->ToString());
LogPrintf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue));
// Found a solution
{
LOCK(cs_main);
if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
return error("BitcoinMiner: generated block is stale");
}
// Inform about the new block
GetMainSignals().BlockFound(pblock->GetHash());
// Process this block the same as if we had received it from another node
CValidationState state;
if (!ProcessNewBlock(state, BlockSource{}, pblock, true, nullptr, connman))
return error("BitcoinMiner: ProcessNewBlock, block not accepted");
return true;
}
void static BitcoinMiner(const CChainParams& chainparams, CConnman* connman)
{
LogPrintf("BitcoinMiner started\n");
SetThreadPriority(THREAD_PRIORITY_LOWEST);
RenameThread("bitcoin-miner");
unsigned int nExtraNonce = 0;
boost::shared_ptr<CReserveScript> coinbaseScript;
GetMainSignals().ScriptForMining(coinbaseScript);
try {
// Throw an error if no script was provided. This can happen
// due to some internal error but also if the keypool is empty.
// In the latter case, already the pointer is NULL.
if (!coinbaseScript || coinbaseScript->reserveScript.empty())
throw std::runtime_error("No coinbase script available (mining requires a wallet)");
while (true) {
if (chainparams.MiningRequiresPeers()) {
// Busy-wait for the network to come online so we don't waste time mining
// on an obsolete chain. In regtest mode we expect to fly solo.
do {
bool fvNodesEmpty = bool(connman->GetNodeCount(CConnman::CONNECTIONS_ALL));
if (!fvNodesEmpty && !IsInitialBlockDownload())
break;
MilliSleep(1000);
} while (true);
}
//
// Create new block
//
unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
CBlockIndex* pindexPrev = chainActive.Tip();
unique_ptr<CBlockTemplate> pblocktemplate(CreateNewBlock(coinbaseScript->reserveScript));
if (!pblocktemplate.get())
{
LogPrintf("Error in BitcoinMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
return;
}
CBlock *pblock = &pblocktemplate->block;
uint64_t hardLimit = GetNextMaxBlockSize(pindexPrev, chainparams.GetConsensus());
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce, hardLimit);
LogPrintf("Running BitcoinMiner with %u transactions in block (%u bytes)\n", pblock->vtx.size(),
::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
//
// Search
//
int64_t nStart = GetTime();
arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
uint256 hash;
uint32_t nNonce = 0;
while (true) {
// Check if something found
if (ScanHash(pblock, nNonce, &hash))
{
if (UintToArith256(hash) <= hashTarget)
{
// Found a solution
pblock->nNonce = nNonce;
assert(hash == pblock->GetHash());
SetThreadPriority(THREAD_PRIORITY_NORMAL);
LogPrintf("BitcoinMiner:\n");
LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex(), hashTarget.GetHex());
ProcessBlockFound(pblock, chainparams, connman);
SetThreadPriority(THREAD_PRIORITY_LOWEST);
coinbaseScript->KeepScript();
// In regression test mode, stop mining after a block is found.
if (chainparams.MineBlocksOnDemand())
throw boost::thread_interrupted();
break;
}
}
// Check for stop or if block needs to be rebuilt
boost::this_thread::interruption_point();
// Regtest mode doesn't require peers
bool connected = bool(connman->GetNodeCount(CConnman::CONNECTIONS_ALL));
if (!connected && chainparams.MiningRequiresPeers())
break;
if (nNonce >= 0xffff0000)
break;
if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
break;
if (pindexPrev != chainActive.Tip())
break;
// Update nTime every few seconds
UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks)
{
// Changing pblock->nTime can change work required on testnet:
hashTarget.SetCompact(pblock->nBits);
}
}
}
}
catch (const boost::thread_interrupted&)
{
LogPrintf("BitcoinMiner terminated\n");
throw;
}
catch (const std::runtime_error &e)
{
LogPrintf("BitcoinMiner runtime error: %s\n", e.what());
return;
}
}
void GenerateBitcoins(bool fGenerate, int nThreads, const CChainParams& chainparams, CConnman* connman)
{
static boost::thread_group* minerThreads = NULL;
if (nThreads < 0)
nThreads = GetNumCores();
if (minerThreads != NULL)
{
minerThreads->interrupt_all();
delete minerThreads;
minerThreads = NULL;
}
if (nThreads == 0 || !fGenerate)
return;
minerThreads = new boost::thread_group();
for (int i = 0; i < nThreads; i++)
minerThreads->create_thread(boost::bind(&BitcoinMiner, boost::cref(chainparams), connman));
}
| 17,470 | 5,423 |
/* @@@LICENSE
*
* Copyright (c) 2010-2012 Hewlett-Packard Development Company, L.P.
*
* 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.
*
* LICENSE@@@ */
#include "PhoneKeyboard.h"
#include "KeyLocationRecorder.h"
#include "PalmIMEHelpers.h"
#include "Settings.h"
#include "SingletonTimer.h"
#include "Utils.h"
#include "VirtualKeyboardPreferences.h"
#include <QDebug>
#include <QFile>
#include <QApplication>
#include <stdlib.h>
#include <glib.h>
#include <sys/times.h>
namespace Phone_Keyboard {
/**
* temporary XML filename
*/
#define IME_KDB_XML_FILENAME "/tmp/kdb.xml"
#define CURRENT_TIME SingletonTimer::currentTime()
// #define DOUBLE_TAP_DURATION Settings::LunaSettings()->tapDoubleClickDuration
#define DOUBLE_TAP_DURATION 500
#define DEBUG_TOUCH 0
inline bool KeyCap_TwoVertical(const QPoint & keyCoord, UKey key)
{
return !UKeyIsFunctionKey(key) && (key < Qt::Key_A || key > Qt::Key_Z);
}
const int cFirstRepeatDelay = 350;
const int cFirstRepeatLongDelay = 750;
const int cLetterDeleteRepeatDelay = 120;
const int cWordDeleteRepeatDelay = 275;
const uint64_t cWordDeleteDelay = cFirstRepeatDelay + 1500;
const QPainter::RenderHints cRenderHints = QPainter::SmoothPixmapTransform | QPainter::HighQualityAntialiasing | QPainter::TextAntialiasing;
// constants used to draw the popup for extended keys
const int cPopupFontSize = 22;
const int cPopupLeftSide = 11;
const int cPopupRightSide = 10;
const int cPopupSide = 20;
const int cPopupPointerStart = 37;
const int cPopupPointerWidth = 25;
const int cPopupTopToKey = 10;
const int cPopupSingleLineMax = 5; // if more extended chars that this, break-up in two lines
const int cPressedTranslateH = 0;
const int cPressedTranslateV = 0;
static QFont sFont("Prelude");
static QFont sPopoutFont("Prelude", 32);
static QString sElipsis(QChar(0x2026 /* … */));
const int cElipsisFontSize = 14;
const QColor cActiveColor(0xd2, 0xd2, 0xd2);
const QColor cActiveColor_back(0xd2, 0xd2, 0xd2);
const QColor cDisabledColor(0x80, 0x80, 0x80);
const QColor cDisabledColor_back(0x80, 0x80, 0x80);
const QColor cFunctionColor(0xd2, 0xd2, 0xd2);
const QColor cFunctionColor_back(0xd2, 0xd2, 0xd2);
const QColor cBlueColor(75, 151, 222);
const QColor cBlueColor_back(255, 255, 255);
const QColor cPopoutTextColor(20, 20, 20);
const QColor cPopoutTextColor_back(0xe2, 0xe2, 0xe2);
class PhoneKeyboardFactory : public VirtualKeyboardFactory
{
public:
PhoneKeyboardFactory() : VirtualKeyboardFactory("Phone Keyboard") {}
InputMethod * create(IMEDataInterface * dataInterface) { return new PhoneKeyboard(dataInterface); }
EVirtualKeyboardSupport getSupport(int maxWidth, int maxHeight)
{
// return eVirtualKeyboardSupport_Preferred_SizeAndLocale; // force phone keyboard for testing!
if (maxWidth < 1024 && maxHeight < 1024)
return eVirtualKeyboardSupport_Preferred_Size;
return eVirtualKeyboardSupport_Poor;
}
};
static PhoneKeyboardFactory sPhoneKeyboardFactory;
static gboolean keyboard_idle(gpointer)
{
PhoneKeyboard * keyboard = PhoneKeyboard::getExistingInstance();
if (keyboard)
return keyboard->idle();
return false;
}
typedef DoubleDrawRendererT<GlyphSpec> DoubleDrawRenderer;
PhoneKeyboard * PhoneKeyboard::s_instance = NULL;
PhoneKeyboard::PhoneKeyboard(IMEDataInterface * dataInterface) : VirtualKeyboard(dataInterface),
m_shiftDown(false),
m_symbolDown(false),
m_lastShiftTime(0),
m_lastUnlockTime(0),
m_keyboardTopPading(0),
m_requestedHeight(-1),
m_9tileCorner(22, 22),
m_keyboardBackgound(NULL),
m_keyboardLimitsVersion(0),
m_keyboardDirty(true),
m_candidateBar(m_keymap, m_IMEDataInterface),
m_candidateBarLayoutOutdated(true),
m_generatedKeymapLayout(NULL),
m_timer(this), m_repeatKey(cOutside), m_repeatStartTime(0),
m_extendedKeys(NULL),
m_extendedKeyShown(cKey_None),
m_shortcutsHandler(dataInterface),
m_showPopupKeys(true),
m_idleInit(false),
m_backspace("icon-delete.png"),
m_shift("icon-shift.png"),
m_shift_on("icon-shift-on.png"),
m_shift_lock("icon-shift-lock.png"),
m_hide("icon-hide-keyboard.png"),
m_emoticon_frown("/usr/palm/emoticons/emoticon-frown.png"),
m_emoticon_cry("/usr/palm/emoticons/emoticon-cry.png"),
m_emoticon_smile("/usr/palm/emoticons/emoticon-smile.png"),
m_emoticon_wink("/usr/palm/emoticons/emoticon-wink.png"),
m_emoticon_yuck("/usr/palm/emoticons/emoticon-yuck.png"),
m_emoticon_gasp("/usr/palm/emoticons/emoticon-gasp.png"),
m_emoticon_heart("/usr/palm/emoticons/emoticon-heart.png"),
m_background("keyboard-bg.png"),
m_white_key("key-white.png"),
m_gray_key("key-gray.png"),
m_black_key("key-black.png"),
m_shift_on_key("key-shift-on.png"),
m_shift_lock_key("key-shift-lock.png"),
m_popup("popup-bg.png"),
m_popup_2("popup-bg-2.png"),
m_popup_key("popup-key.png"),
m_glyphCache(600, 800)
{
if (VERIFY(s_instance == NULL))
s_instance = this;
Q_ASSERT(m_IMEDataInterface);
IMEPixmap::setDefaultLocation("keyboard-phone");
for (int r = 0; r < PhoneKeymap::cKeymapRows; ++r)
m_keymap.setRowHeight(r, m_white_key.height() / 2);
m_presetHeight[0] = 377; // portrait
m_presetHeight[1] = 260; // landscape
connect(&m_IMEDataInterface->m_availableSpace, SIGNAL(valueChanged(const QRect &)), SLOT(availableSpaceChanged(const QRect &)));
connect(&m_IMEDataInterface->m_visible, SIGNAL(valueChanged(const bool &)), SLOT(visibleChanged(const bool &)));
connect(&m_IMEDataInterface->m_editorState, SIGNAL(valueChanged(const PalmIME::EditorState &)), SLOT(editorStateChanged(const PalmIME::EditorState &)));
connect(&m_IMEDataInterface->m_autoCap, SIGNAL(valueChanged(const bool &)), SLOT(autoCapChanged(const bool &)));
connect(&m_timer, SIGNAL(timeout()), this, SLOT(repeatChar()));
m_candidateBar.font().setPixelSize(24);
connect(&m_candidateBar, SIGNAL(needsRedraw()), SLOT(triggerRepaint()));
connect(&m_candidateBar, SIGNAL(resized()), SLOT(candidateBarResized()));
// init size
VirtualKeyboardPreferences::instance().applyInitSettings(this);
}
PhoneKeyboard::~PhoneKeyboard()
{
if (VERIFY(s_instance == this))
s_instance = NULL;
}
void PhoneKeyboard::editorStateChanged(const PalmIME::EditorState & state)
{
bool layoutChanged = false;
if (m_keymap.symbolMode() == PhoneKeymap::eSymbolMode_Lock)
if (m_keymap.setSymbolMode(PhoneKeymap::eSymbolMode_Off))
layoutChanged = true;
if (m_keymap.setEditorState(state))
layoutChanged = true;
m_candidateBar.setEditorState(state);
if (layoutChanged)
keyboardLayoutChanged();
m_shortcutsHandler.resetEditor(state);
}
void PhoneKeyboard::autoCapChanged(const bool & autoCap)
{
if (m_keymap.setAutoCap(autoCap))
keyboardLayoutChanged();
}
void PhoneKeyboard::setShiftMode(PhoneKeymap::EShiftMode shiftMode)
{
if (m_keymap.setShiftMode(shiftMode))
keyboardLayoutChanged();
}
void PhoneKeyboard::setSymbolMode(PhoneKeymap::ESymbolMode symbolMode)
{
if (m_keymap.setSymbolMode(symbolMode))
keyboardLayoutChanged();
}
void PhoneKeyboard::setKeyboardCombo(const std::string & layoutName, const std::string & languageName, bool showLanguageKey)
{
const PhoneKeymap::LayoutFamily * layoutFamily = PhoneKeymap::LayoutFamily::findLayoutFamily(layoutName.c_str(), false); // get default if not found
bool changed = false;
if (m_keymap.setLayoutFamily(layoutFamily))
{
changed = true;
KeyLocationRecorder::instance().keyboardSizeChanged(m_keymap.layoutName(), m_keymap.rect());
}
syncKeymap();
if (m_keymap.setLanguageName(showLanguageKey ? languageName : ""))
changed = true;
m_candidateBar.setLanguage(languageName);
if (changed)
keyboardLayoutChanged();
}
void PhoneKeyboard::syncKeymap()
{
if (m_keymap.layoutFamily() != m_generatedKeymapLayout)
{
if (VERIFY(m_keymap.generateKeyboardLayout(IME_KDB_XML_FILENAME)))
m_generatedKeymapLayout = m_keymap.layoutFamily();
else
m_generatedKeymapLayout = NULL;
m_candidateBarLayoutOutdated = true;
}
if (m_candidateBarLayoutOutdated && m_generatedKeymapLayout)
{
if (m_candidateBar.loadKeyboardLayoutFile(IME_KDB_XML_FILENAME, m_generatedKeymapLayout->m_primaryID, m_generatedKeymapLayout->m_secondaryID))
m_candidateBarLayoutOutdated = false;
}
}
void PhoneKeyboard::showSuggestions(bool show)
{
m_candidateBar.setEnabled(show);
if (show)
{
m_candidateBarLayoutOutdated = true;
syncKeymap();
keyboardLayoutChanged();
VirtualKeyboardPreferences::instance().activateCombo(); // for language update...
}
}
void PhoneKeyboard::visibleChanged(const bool & visible)
{
m_candidateBar.clearCandidates();
if (visible)
{
setKeyboardHeight(m_requestedHeight);
}
else
{
m_keymap.setSymbolMode(PhoneKeymap::eSymbolMode_Off);
m_keymap.setShiftMode(PhoneKeymap::eShiftMode_Off);
clearExtendedkeys();
}
}
bool PhoneKeyboard::setBoolOption(const std::string & optionName, bool value)
{
if (optionName == "suggestions")
{
showSuggestions(value);
}
else if (optionName == "popupkeys")
{
m_showPopupKeys = value;
triggerRepaint();
}
else
{
g_warning("PhoneKeyboard::setBoolOption: \"%s\" is not supported.", optionName.c_str());
return false;
}
return true;
}
bool PhoneKeyboard::setIntOption(const std::string & optionName, int value)
{
g_warning("PhoneKeyboard::setIntOption: \"%s\" is not supported.", optionName.c_str());
return false;
}
bool PhoneKeyboard::getValue(const std::string & name, std::string & outValue)
{
if (name == "height")
{
outValue = string_printf("%d", m_requestedHeight);
return true;
}
else if (name == "keyboard_layout")
{
outValue = m_keymap.getKeyboardLayoutAsJson();
return true;
}
else if (name == "autocap")
{
outValue = m_keymap.isAutoCapActive() ? "1" : "0";
return true;
}
return false;
}
void PhoneKeyboard::requestSize(int size)
{
requestHeight(m_presetHeight[inLandscapeOrientation()]);
}
void PhoneKeyboard::requestHeight(int height)
{
m_requestedHeight = height;
setKeyboardHeight(height);
if (height > 0)
queueIdlePrerendering();
}
void PhoneKeyboard::changePresetHeightForSize(int size, int height)
{
bool landscape = (size != 0);
m_presetHeight[landscape] = qBound<int>(10, height, 2 * m_background.height());
if (landscape == inLandscapeOrientation())
requestHeight(height);
}
void PhoneKeyboard::availableSpaceChanged(const QRect & size)
{
m_candidateBar.commit();
m_extendedKeys = NULL;
m_keymap.setRect(0, 0, 0, 0);
m_candidateBar.frame().setRect(0, 0, 0, 0);
m_keyboardTopPading = 0;
// use the height preset for that orientation
m_requestedHeight = m_presetHeight[inLandscapeOrientation()];
setKeyboardHeight(m_requestedHeight);
queueIdlePrerendering();
}
void PhoneKeyboard::setKeyboardHeight(int height, bool notify)
{
const QRect & availableSpace = m_IMEDataInterface->m_availableSpace.get();
int width = availableSpace.width();
int screenHeight = availableSpace.height();
height = qBound<int>(50, height, screenHeight - 28);
if (VERIFY(height > 0))
{
m_keyboardDirty = true;
// assets give us "ideal" non-scaled sizes. Proportionaly adjust m_keyboardTopPading
int fullHeight = m_background.height();
int fullKeymapHeight = PhoneKeymap::cKeymapRows * m_white_key.height() / 2;
if (fullHeight < fullKeymapHeight)
fullHeight = fullKeymapHeight; // if background shorter than assets, stretch background!
int keymapHeight = height * fullKeymapHeight / fullHeight;
m_keyboardTopPading = height - keymapHeight;
if (m_keyboardTopPading < 0)
m_keyboardTopPading = 0;
// PhoneKeymap pushed at the bottom of the available space
m_keymap.setRect(0, availableSpace.height() - keymapHeight, width, keymapHeight);
if (notify)
{
keyboardLayoutChanged();
KeyLocationRecorder::instance().keyboardSizeChanged(m_keymap.layoutName(), m_keymap.rect());
}
int candidateBarHeight = m_candidateBar.enabled() ? m_white_key.height() / 2 : 0;
m_candidateBar.frame().setRect(0, m_keymap.rect().top() - candidateBarHeight - m_keyboardTopPading, width, candidateBarHeight);
//g_debug("PhoneKeyboard::setKeyboardHeight: %d pixels of height, Setting keymap rect to: %d, %d, %dx%d, candidateBar: %d", height, m_keymap.rect().left(), m_keymap.rect().top(), m_keymap.rect().width(), m_keymap.rect().height(), candidateBarHeight);
m_9tileCorner.m_trimV = 0;
m_9tileCorner.m_trimH = 0;
// if (availableSpace.width() < 480)
// m_9tileCorner.m_trimH = 4;
// else if (availableSpace.width() == 480)
// m_9tileCorner.m_trimH = 3;
// else if (keymapHeight >= fullKeymapHeight)
// m_9tileCorner.m_trimH = 0;
// else
// {
// m_9tileCorner.m_trimH = (fullKeymapHeight - keymapHeight) / 40;
// if (m_9tileCorner.m_trimH > 3)
// m_9tileCorner.m_trimH = 3;
// }
//g_critical("9Tile Shrink: %g-%g (%d)", m_9tileCorner.m_trimH, m_9tileCorner.m_trimV, fullKeymapHeight - keymapHeight);
}
else
g_debug("PhoneKeyboard::setKeyboardHeight: FAILED! height: %d, requestedHeight: %d, portrait: %d, landscape %d, background height: %d, keyboard height: %d, available: %d-%d %dx%d.", height, m_requestedHeight,
m_presetHeight[0], m_presetHeight[1], m_background.height(),
m_keymap.rect().height() + m_keyboardTopPading + m_candidateBar.frame().height(), availableSpace.x(), availableSpace.y(), availableSpace.width(), availableSpace.height());
if (notify)
m_IMEDataInterface->m_keyboardHeight.set(m_keymap.rect().height() + m_keyboardTopPading + m_candidateBar.frame().height());
}
void PhoneKeyboard::keyboardLayoutChanged()
{
if (!m_keyboardDirty && m_IMEDataInterface->m_visible.get())
{
m_keyboardDirty = true;
triggerRepaint();
}
m_candidateBar.updateKeyboardLayout(m_keymap.layoutName(), m_keymap.getPage(), m_keymap.rect(), m_keymap.isShiftActive(), m_keymap.isCapsLocked(), m_keymap.isAutoCapActive());
}
void PhoneKeyboard::clearExtendedkeys()
{
if (m_extendedKeys)
{
m_extendedKeys = 0;
m_IMEDataInterface->m_hitRegion.set(QRegion());
if (m_IMEDataInterface->m_visible.get())
triggerRepaint();
}
else if (!m_IMEDataInterface->m_hitRegion.get().isEmpty())
m_IMEDataInterface->m_hitRegion.set(QRegion()); // defensive...
triggerRepaint();
}
void PhoneKeyboard::releaseTouch(int id)
{
Touch & touch = m_touches[id];
#if DEBUG_TOUCH
g_debug("PhoneKeyboard::releaseTouch: '%s', consumed: %d, visible: %d", QString(m_keymap.map(touch.m_keyCoordinate)).toUtf8().data(), touch.m_consumed, touch.m_visible);
#endif
if (m_candidateBar.endTrace(id))
{
triggerRepaint();
}
else if (m_extendedKeys)
{
UKey key;
if (!pointToExtendedPopup(touch.m_lastPosition, key))
{
key = m_keymap.map(touch.m_keyCoordinate);
if (key == Qt::Key_Shift || key == cKey_Symbol)
handleKey(key, touch.m_lastPosition);
else if (!setExtendedKeys(touch.m_keyCoordinate, true) && !touch.m_consumed)
clearExtendedkeys();
else
triggerRepaint();
}
else
{
if (key != cKey_None)
{
g_debug("Extended character selected: %s", QString(m_keymap.getKeyDisplayString(key, true)).toUtf8().data());
handleKey(key, QPointF());
}
clearExtendedkeys();
}
}
else if (touch.m_inCandidateBar)
{
m_candidateBar.releaseTouch(touch.m_lastPosition.x() - touch.m_firstPosition.x());
}
else if (m_keymap.isValidLocation(touch.m_keyCoordinate))
{
bool sendKey = touch.m_visible && !touch.m_consumed;
UKey key = m_keymap.map(touch.m_keyCoordinate);
if (key == cKey_Symbol)
setSymbolKeyDown(false);
else if (key == Qt::Key_Shift)
setShiftKeyDown(false);
else
{
touch.m_visible = false; // the key is no longer considered pressed...
touch.m_consumed = true;
if (m_shiftDown || m_symbolDown)
{ // we are sending the key, which means we are "using" the shift or symbol keypress: when these are released, they are NOT sent out/used again.
for (std::map<int, Touch>::iterator iter = m_touches.begin(); iter != m_touches.end(); ++iter)
{
if (iter->first != id)
{
Touch & touch = iter->second;
UKey key = m_keymap.map(touch.m_keyCoordinate);
if (key == cKey_Symbol || key == Qt::Key_Shift)
touch.m_consumed = true;
}
}
}
}
if (sendKey)
handleKey(key, touch.m_lastPosition);
triggerRepaint();
if (touch.m_keyCoordinate == m_repeatKey)
stopRepeat();
}
}
inline int Min(int a, int b) { return a < b ? a : b; }
inline int MinMax(int min, int v, int max) { return v < min ? min : (v < max ? v : max); }
void PhoneKeyboard::updateTouch(int id, QPointF position)
{
uint64_t now = CURRENT_TIME;
QPointF touchPosition(position.x(), position.y() - m_keymap.rect().top());
UKey extendedKey;
QPoint keyCoordinate = (!pointToExtendedPopup(touchPosition, extendedKey) && position.y() > m_keymap.rect().top() - m_keyboardTopPading) ? m_keymap.pointToKeyboard(position.toPoint()) : cOutside;
bool newTouch = m_touches.find(id) == m_touches.end();
Touch & touch = m_touches[id];
bool inCandidatebar = m_candidateBar.frame().contains(position.x(), position.y());
UKey newKey = m_keymap.map(keyCoordinate);
if (newTouch)
{
touch.m_firstPosition = touchPosition;
touch.m_lastPosition = touchPosition;
touch.m_inCandidateBar = inCandidatebar;
}
//g_debug("Touch bar: %d, %gx%g", inCandidatebar, position.x(), position.y());
if (extendedKey != cKey_None)
{
if (newTouch)
makeSound(extendedKey);
if (extendedKey != m_extendedKeyShown || (touch.m_visible && touch.m_keyCoordinate != keyCoordinate))
triggerRepaint();
}
else if (!m_extendedKeys && newTouch && m_touches.size() == 1 && QChar(newKey).isLetter() && m_candidateBar.tracePoint(touchPosition.toPoint(), newKey, id, true))
{
}
else if (!m_extendedKeys && !newTouch && m_candidateBar.tracePoint(touchPosition.toPoint(), newKey, id, false))
{
stopRepeat();
}
else if (newTouch ||
(!touch.m_inCandidateBar && touch.m_keyCoordinate != keyCoordinate) ||
(touch.m_inCandidateBar && inCandidatebar))
{
triggerRepaint();
if (touch.m_inCandidateBar)
{
m_candidateBar.setScrollOffset(m_candidateBar.scrollOffset() + position.x() - touch.m_lastPosition.x());
//g_debug("Candidate bar offset: %d", m_candidateBar.scrollOffset());
}
else
{
#if DEBUG_TOUCH
g_debug("%s key '%s', consumed: %d, visible: %d", newTouch ? "New" : "Moved", m_keymap.getKeyDisplayString(newKey, true).toUtf8().data(), touch.m_consumed, touch.m_visible);
#endif
if (touch.m_visible && !touch.m_consumed)
{
if (keyCoordinate != m_repeatKey)
{
if (newTouch && newKey == cKey_Emoticon_Options)
{
if (!setExtendedKeys(keyCoordinate, true))
m_extendedKeys = NULL;
touch.m_consumed = true;
stopRepeat();
}
else if (newTouch && (canRepeat(newKey) || m_keymap.getExtendedChars(keyCoordinate) || (newKey == cKey_Hide && m_touches.size() == 1)))
{
m_timer.start(newKey == cKey_Hide || m_candidateBar.isTraceActive() ? cFirstRepeatLongDelay : cFirstRepeatDelay);
m_repeatKey = keyCoordinate;
m_repeatStartTime = CURRENT_TIME;
}
else
stopRepeat();
}
}
if (newTouch)
{ // send pressed keys not already sent out...
makeSound(newKey);
for (std::map<int, Touch>::iterator iter = m_touches.begin(); iter != m_touches.end(); ++iter)
{
if (iter->first != id && !touch.m_inCandidateBar)
{
Touch & othertouch = iter->second;
if (othertouch.m_visible)
{
UKey key = m_keymap.map(othertouch.m_keyCoordinate);
if (key != cKey_Symbol && key != Qt::Key_Shift && key != cKey_Hide && !othertouch.m_consumed)
{
#if DEBUG_TOUCH
g_debug("Consumming pressed key '%s', consumed: %d, visible: %d", m_keymap.getKeyDisplayString(key, true).toUtf8().data(), touch.m_consumed, touch.m_visible);
#endif
handleKey(key, othertouch.m_lastPosition);
othertouch.m_visible = false;
}
othertouch.m_consumed = true;
}
}
}
}
if (touch.m_visible && ((newKey == cKey_Symbol && !m_extendedKeys && setSymbolKeyDown(true)) || (newKey == Qt::Key_Shift && setShiftKeyDown(true))))
{
if (m_extendedKeys)
touch.m_consumed = true;
}
}
}
touch.m_keyCoordinate = keyCoordinate;
if (m_extendedKeys && touch.m_visible != (extendedKey == cKey_None))
{ // show keyboard key when NOT on the extended bar
touch.m_visible = !touch.m_visible;
triggerRepaint();
}
touch.m_lastPosition = touchPosition;
touch.m_lastTouchTime = now;
}
void PhoneKeyboard::handleKey(UKey key, QPointF where)
{
//g_debug("PhoneKeyboard::handleKey: '%s'", QString(key).toUtf8().data());
PhoneKeymap::EShiftMode shiftMode = m_keymap.shiftMode();
PhoneKeymap::ESymbolMode symbolMode = m_keymap.symbolMode();
bool consumeMode = false;
bool commit = false;
bool sendKey = true;
Qt::Key qtkey = Qt::Key_unknown;
if (UKeyIsUnicodeQtKey(key))
{
qtkey = Qt::Key(key); // "normal" case: UKey is also a valid Qt::Key
if (m_candidateBar.enabled())
{
if (QChar(key).isLetter())
sendKey = !m_candidateBar.keyboardTap(where, key);
else
commit = true;
}
else
{
sendKey = true;
}
}
else if (UKeyIsTextShortcutKey(key))
{
commit = true;
qtkey = key;
}
else if (UKeyIsKeyboardComboKey(key))
{
int index = key - cKey_KeyboardComboChoice_First;
VirtualKeyboardPreferences::instance().selectKeyboardCombo(index);
}
else
{
switch ((int)key)
{
case Qt::Key_Backspace:
qtkey = Qt::Key_Backspace;
sendKey = !m_candidateBar.backspace(m_keymap.isShiftDown());
break;
case Qt::Key_Return:
qtkey = key;
commit = true;
break;
case cKey_SymbolPicker:
qtkey = Qt::Key_Control;
break;
case cKey_Symbol:
if (m_extendedKeys)
clearExtendedkeys();
else if (m_keymap.symbolMode() == PhoneKeymap::eSymbolMode_Lock)
symbolMode = PhoneKeymap::eSymbolMode_Off;
else
symbolMode = PhoneKeymap::eSymbolMode_Lock, shiftMode = PhoneKeymap::eShiftMode_Off;
break;
case Qt::Key_Shift:
{
uint64_t now = CURRENT_TIME;
if (m_lastUnlockTime + DOUBLE_TAP_DURATION > now)
{ // quick tap after unlocking: eat that tap, and next tap is like nothing happened before...
m_lastUnlockTime = 0;
now = 0;
}
else if (m_lastShiftTime + DOUBLE_TAP_DURATION > now)
shiftMode = PhoneKeymap::eShiftMode_CapsLock;
else if (shiftMode == PhoneKeymap::eShiftMode_CapsLock)
{
shiftMode = PhoneKeymap::eShiftMode_Off;
m_lastUnlockTime = now;
}
else if (shiftMode == PhoneKeymap::eShiftMode_Off)
shiftMode = PhoneKeymap::eShiftMode_Once;
else
shiftMode = PhoneKeymap::eShiftMode_Off;
m_lastShiftTime = now;
autoCapChanged(false);
break;
}
case cKey_Hide:
m_IMEDataInterface->requestHide();
break;
case cKey_ToggleSuggestions:
showSuggestions(!m_candidateBar.enabled());
break;
case cKey_ShowXT9Regions:
{
PerfMonitor regionMonitor("showXT9Regions");
m_candidateBar.drawXT9Regions(m_keyboardBackgound, m_keyboardTopPading);
triggerRepaint();
break;
}
case cKey_ShowKeymapRegions:
showKeymapRegions();
triggerRepaint();
break;
case cKey_SwitchToQwerty:
VirtualKeyboardPreferences::instance().selectLayoutCombo("qwerty");
break;
case cKey_SwitchToAzerty:
VirtualKeyboardPreferences::instance().selectLayoutCombo("azerty");
break;
case cKey_SwitchToQwertz:
VirtualKeyboardPreferences::instance().selectLayoutCombo("qwertz");
break;
case cKey_StartStopRecording:
{
bool wasRecording = KeyLocationRecorder::instance().isRecording();
KeyLocationRecorder::instance().startStop(m_keymap.layoutName(), m_keymap.rect());
if (KeyLocationRecorder::instance().isRecording())
{
sendKeyDownUp(Qt::Key_Space, Qt::NoModifier);
sendKeyDownUp(Qt::Key_Backspace, Qt::NoModifier);
}
break;
}
case cKey_ToggleLanguage:
VirtualKeyboardPreferences::instance().selectNextKeyboardCombo();
break;
case cKey_CreateDefaultKeyboards:
VirtualKeyboardPreferences::instance().createDefaultKeyboards();
break;
case cKey_ClearDefaultKeyboards:
VirtualKeyboardPreferences::instance().clearDefaultDeyboards();
break;
case cKey_ToggleSoundFeedback:
VirtualKeyboardPreferences::instance().setTapSounds(!VirtualKeyboardPreferences::instance().getTapSounds());
break;
case Qt::Key_Left:
qtkey = Qt::Key_Left; // used to navigate the cursor left
break;
case Qt::Key_Right:
qtkey = Qt::Key_Right; // used to navigate the cursor right
break;
case Qt::Key_Tab:
switch (m_keymap.tabAction())
{
case PhoneKeymap::eTabAction_Next:
m_IMEDataInterface->performEditorAction(PalmIME::FieldAction_Next);
break;
case PhoneKeymap::eTabAction_Previous:
m_IMEDataInterface->performEditorAction(PalmIME::FieldAction_Previous);
break;
case PhoneKeymap::eTabAction_Tab:
default:
qtkey = Qt::Key_Tab;
}
break;
default:
break;
}
}
if (qtkey != Qt::Key_unknown)
{
if (commit)
m_candidateBar.commit();
consumeMode = true;
if (sendKey)
{
if (KeyLocationRecorder::instance().isRecording())
KeyLocationRecorder::instance().record(m_keymap.getKeyDisplayString(key, true), where.toPoint());
if (UKeyIsTextShortcutKey(key))
{
m_IMEDataInterface->commitText(m_keymap.getKeyDisplayString(key).toUtf8().data());
m_shortcutsHandler.resetEditor();
}
else if (m_shortcutsHandler.filterKey(qtkey))
{
if (UKeyIsFunctionKey(qtkey))
{
if (qtkey == Qt::Key_Tab)
m_IMEDataInterface->commitText("\t");
else
sendKeyDownUp(qtkey, m_keymap.isShiftDown() ? Qt::ShiftModifier : Qt::NoModifier);
}
else if (qtkey > 0 && qtkey < 128)
sendKeyDownUp(qtkey, m_keymap.isCapActive() ? Qt::ShiftModifier : Qt::NoModifier); // send as basic keystroke
else if (m_keymap.isCapActive())
sendKeyDownUp((Qt::Key) QChar(qtkey).toUpper().unicode(), Qt::ShiftModifier);
else
sendKeyDownUp((Qt::Key) QChar(qtkey).toLower().unicode(), Qt::NoModifier);
}
}
else
m_shortcutsHandler.resetEditor();
if (qtkey == Qt::Key_Space || qtkey == Qt::Key_Return)
symbolMode = PhoneKeymap::eSymbolMode_Off;
}
if (consumeMode)
{
if (m_keymap.shiftMode() == PhoneKeymap::eShiftMode_Once)
shiftMode = PhoneKeymap::eShiftMode_Off;
}
if (m_keymap.shiftMode() != shiftMode)
setShiftMode(shiftMode);
if (m_keymap.symbolMode() != symbolMode)
setSymbolMode(symbolMode);
}
void PhoneKeyboard::sendKeyDownUp(Qt::Key key, Qt::KeyboardModifiers modifiers)
{
if (m_IMEDataInterface) {
m_IMEDataInterface->sendKeyEvent(QEvent::KeyPress, key, modifiers);
m_IMEDataInterface->sendKeyEvent(QEvent::KeyRelease, key, modifiers);
}
}
inline const char * touchPointState(Qt::TouchPointState state)
{
switch (state)
{
case Qt::TouchPointPressed: return "pressed";
case Qt::TouchPointMoved: return "moved";
case Qt::TouchPointStationary: return "stationary";
case Qt::TouchPointReleased: return "released";
default: return "<unknown>";
}
}
void PhoneKeyboard::touchEvent(const QTouchEvent& te)
{
if (m_IMEDataInterface)
{
const QList<QTouchEvent::TouchPoint> & touchPoints = te.touchPoints();
#if DEBUG_TOUCH
std::string str;
for (QList<QTouchEvent::TouchPoint>::ConstIterator iter = touchPoints.constBegin(); iter != touchPoints.constEnd(); ++iter)
{
const QTouchEvent::TouchPoint & touchPoint = *iter;
QPoint keyPos = m_keymap.pointToKeyboard(touchPoint.pos().toPoint());
Qt::Key key = m_keymap.map(keyPos);
::append_format(str, " Id: %d, location: %gx%g %s, Key: %dx%d = '%s'.\n", touchPoint.id(), touchPoint.pos().x(), touchPoint.pos().y(), touchPointState(touchPoint.state()), keyPos.x(), keyPos.y(), m_keymap.getKeyDisplayString(key, true).toUtf8().data());
}
g_debug("TouchEvent: \n%s", str.c_str());
#endif
if (m_IMEDataInterface->m_visible.get())
{
// handle new presses after handling release & moves
bool presses = false;
for (QList<QTouchEvent::TouchPoint>::ConstIterator iter = touchPoints.constBegin(); iter != touchPoints.constEnd(); ++iter)
{
const QTouchEvent::TouchPoint & touchPoint = *iter;
Qt::TouchPointState state = touchPoint.state();
if (state == Qt::TouchPointReleased)
{
releaseTouch(touchPoint.id());
m_touches.erase(touchPoint.id());
}
else if (state == Qt::TouchPointMoved)
updateTouch(touchPoint.id(), touchPoint.pos());
else if (state == Qt::TouchPointPressed)
presses = true;
}
if (presses)
{
for (QList<QTouchEvent::TouchPoint>::ConstIterator iter = touchPoints.constBegin(); iter != touchPoints.constEnd(); ++iter)
{
const QTouchEvent::TouchPoint & touchPoint = *iter;
if (touchPoint.state() == Qt::TouchPointPressed)
updateTouch(touchPoint.id(), touchPoint.pos());
}
}
}
else
g_warning("TabletKeyboard::touchEvent: hidden (probably being hidden...), so we will ignore these touches.");
// everything is released: make sure we have nothing left in our records...
if (te.type() == QEvent::TouchEnd)
{
if (m_touches.size() > 0)
{
if (m_IMEDataInterface->m_visible.get())
g_critical("Clearing %u non-finished touches!", m_touches.size());
for (QList<QTouchEvent::TouchPoint>::ConstIterator iter = touchPoints.constBegin(); iter != touchPoints.constEnd(); ++iter)
m_candidateBar.endTrace(iter->id());
m_touches.clear();
}
stopRepeat();
setShiftKeyDown(false);
setSymbolKeyDown(false);
}
}
}
void PhoneKeyboard::tapEvent(const QPoint& tapPt)
{
#if DEBUG_TOUCH
g_debug("tapEvent: %d, %d", tapPt.x(), tapPt.y());
#endif
m_candidateBar.tapEvent(tapPt);
}
void PhoneKeyboard::screenEdgeFlickEvent()
{
// Mark all touches as consumed
for (std::map<int, Touch>::iterator iter = m_touches.begin(); iter != m_touches.end(); ++iter) {
iter->second.m_consumed = true;
}
}
void PhoneKeyboard::repeatChar()
{
if (PhoneKeymap::isValidLocation(m_repeatKey))
{
UKey key = m_keymap.map(m_repeatKey);
if (canRepeat(key))
{
makeSound(key);
bool wordDelete = m_keymap.isShiftDown() || (CURRENT_TIME - m_repeatStartTime > cWordDeleteDelay);
if (key == Qt::Key_Backspace)
sendKeyDownUp(Qt::Key_Backspace, wordDelete ? Qt::ShiftModifier : Qt::NoModifier);
else
sendKeyDownUp(Qt::Key(key), m_keymap.isCapActive() ? Qt::ShiftModifier : Qt::NoModifier);
int repeatInterval = wordDelete ? cWordDeleteRepeatDelay : cLetterDeleteRepeatDelay;
if (m_timer.interval() != repeatInterval)
m_timer.setInterval(repeatInterval);
}
else
{
if (setExtendedKeys(m_repeatKey))
{
for (std::map<int, Touch>::iterator iter = m_touches.begin(); iter != m_touches.end(); ++iter)
{
Touch & touch = iter->second;
if (touch.m_keyCoordinate == m_repeatKey)
touch.m_consumed = true;
}
}
stopRepeat();
}
}
else
stopRepeat();
}
bool PhoneKeyboard::setExtendedKeys(QPoint keyCoord, bool cancelIfSame)
{
const UKey * newExtended = m_keymap.getExtendedChars(keyCoord);
if (cancelIfSame && newExtended == m_extendedKeys)
return false;
m_extendedKeys = newExtended;
if (m_extendedKeys)
{
int cellCount, lineCount, lineLength;
getExtendedPopupSpec(cellCount, lineCount, lineLength);
IMEPixmap & popup = (lineCount > 1) ? m_popup_2 : m_popup;
m_extendedKeyShown = cKey_None;
m_keymap.keyboardToKeyZone(keyCoord, m_extendedKeysFrame);
m_extendedKeysPointer = m_extendedKeysFrame.left() + m_extendedKeysFrame.width() / 2;
m_extendedKeysFrame.translate(0, -popup.height() + 10);
int width = cPopupLeftSide + cPopupRightSide + lineLength * m_popup_key.width();
m_extendedKeysFrame.setLeft(m_extendedKeysPointer - m_popup_key.width() / 2 - cPopupLeftSide);
m_extendedKeysFrame.setWidth(width);
m_extendedKeysFrame.setHeight(popup.height());
if (m_extendedKeysFrame.left() < 0)
m_extendedKeysFrame.moveLeft(0);
else if (m_extendedKeysFrame.right() > m_keymap.rect().right())
m_extendedKeysFrame.translate(m_keymap.rect().right() - m_extendedKeysFrame.right(), 0);
if (m_extendedKeysFrame.isValid())
{
m_IMEDataInterface->m_hitRegion.set(QRegion(m_IMEDataInterface->m_availableSpace.get()));
triggerRepaint();
}
return true;
}
else
m_IMEDataInterface->m_hitRegion.set(QRegion());
return false;
}
bool PhoneKeyboard::pointToExtendedPopup(QPointF position, UKey & outKey)
{
outKey = cKey_None;
if (m_extendedKeys && m_extendedKeysFrame.contains(position.x(), position.y() + m_keymap.rect().top()))
{
QPoint where = position.toPoint() - m_extendedKeysFrame.topLeft() - QPoint(cPopupLeftSide, -m_keymap.rect().top() + cPopupTopToKey);
int cellCount, lineCount, lineLength;
getExtendedPopupSpec(cellCount, lineCount, lineLength);
int x = qMin<int>(where.x() / m_popup_key.width(), lineLength - 1);
int y = where.y() / (m_popup_key.height() / 2);
int index = (y == 0) ? x : x + lineLength;
if (index <= cellCount)
outKey = m_extendedKeys[index];
return true;
}
return false;
}
void PhoneKeyboard::getExtendedPopupSpec(int & outCellCount, int & outLineCount, int & outLineLength)
{
outCellCount = 0;
if (m_extendedKeys)
while (m_extendedKeys[outCellCount] != cKey_None)
++outCellCount;
outLineCount = (outCellCount > cPopupSingleLineMax) ? 2 : 1;
outLineLength = (outCellCount + outLineCount - 1) / outLineCount;
}
bool PhoneKeyboard::canRepeat(UKey key) const
{
return (key == Qt::Key_Space || key == Qt::Key_Backspace || key == Qt::Key_Left || key == Qt::Key_Right);
}
void PhoneKeyboard::stopRepeat()
{
m_timer.stop();
m_repeatKey = cOutside;
m_repeatStartTime = 0;
}
void PhoneKeyboard::showKeymapRegions()
{
PerfMonitor regionMonitor("showKeymapRegions");
m_keyboardBackgound->fill(QColor(0, 0, 0));
QRect frame = m_keymap.rect();
QPainter painter(m_keyboardBackgound);
int y_offset = frame.top() - m_keyboardTopPading;
ColorMap colorMap;
for (int x = 0; x < frame.width(); ++x)
for (int y = 0; y < m_keyboardTopPading + frame.height(); ++y)
{
QPoint keycoord = m_keymap.pointToKeyboard(QPoint(x, y_offset + y));
if (keycoord != cOutside)
{
painter.setPen(colorMap[QChar(m_keymap.map(keycoord)).unicode()]); // create or reuse random color for this character
painter.drawPoint(x, y);
}
}
m_keyboardDirty = true;
}
void PhoneKeyboard::paint(QPainter & painter)
{
PerfMonitor perf("PhoneKeyboard::paint");
m_candidateBar.paint(painter, cBlueColor);
const QRect & keymapRect = m_keymap.rect();
QRect keyboardFrame(keymapRect.left(), keymapRect.top() - m_keyboardTopPading, keymapRect.width(), keymapRect.height() + m_keyboardTopPading);
if (updateBackground())
perf.trace("background rebuilt");
painter.setCompositionMode(QPainter::CompositionMode_Source);
painter.drawPixmap(QPointF(keyboardFrame.left(), keyboardFrame.top()), *m_keyboardBackgound);
painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
perf.trace("Draw background");
DoubleDrawRenderer doubleDrawRenderer;
CachedGlyphRenderer<GlyphSpec> renderer(painter, m_glyphCache, doubleDrawRenderer, PhoneKeymap::cKeymapColumns * (PhoneKeymap::cKeymapRows + 1));
for (int y = 0; y < PhoneKeymap::cKeymapRows; ++y)
{
for (int x = 0; x < PhoneKeymap::cKeymapColumns; ++x)
{
QPoint keyCoord(x, y);
UKey plainKey = m_keymap.map(x, y, PhoneKeymap::eLayoutPage_plain);
QRect r;
int count = m_keymap.keyboardToKeyZone(keyCoord, r);
if (count > 0 && plainKey != cKey_None)
{
UKey key = m_keymap.map(x, y);
// if (key == Qt::Key_Shift)
// drawKeyBackground(painter, r, keyCoord, key, false, count);
drawKeyCap(&painter, renderer, r, keyCoord, key, eUse_unpressed);
}
}
}
bool extendedKeysShown = m_extendedKeys && m_extendedKeysFrame.isValid();
QRect r;
if (extendedKeysShown)
{
for (int y = 0; y < PhoneKeymap::cKeymapRows; ++y) // draw caps second (faster to split)
{
for (int x = 0; x < PhoneKeymap::cKeymapColumns; ++x)
{
if (m_keymap.getExtendedChars(QPoint(x, y)) && m_keymap.keyboardToKeyZone(QPoint(x, y), r) > 0)
{
r.setWidth(r.width() - 9 + m_9tileCorner.m_trimH); r.setHeight(r.height() - 9 + m_9tileCorner.m_trimV);
renderer.render(r, GlyphSpec(sElipsis, cElipsisFontSize, false, cActiveColor, cActiveColor_back), sFont, Qt::AlignRight | Qt::AlignBottom);
}
}
}
}
renderer.flush();
perf.trace("Draw labels");
UKey extendedKey = cKey_None;
for (std::map<int, Touch>::iterator iter = m_touches.begin(); iter != m_touches.end(); ++iter)
{
Touch & touch = iter->second;
if (!pointToExtendedPopup(touch.m_lastPosition, extendedKey))
{
if (touch.m_visible)
{
int count = m_keymap.keyboardToKeyZone(touch.m_keyCoordinate, r);
if (count > 0)
{
UKey key = m_keymap.map(touch.m_keyCoordinate);
if (key != cKey_None)
{
painter.setClipRect(r);
painter.drawPixmap(r.left(), keyboardFrame.top(), r.width(), keyboardFrame.height(), m_background.pixmap());
painter.setClipping(false);
drawKeyBackground(painter, r, touch.m_keyCoordinate, key, true, count);
drawKeyCap(&painter, renderer, r, touch.m_keyCoordinate, key, eUse_pressed);
if (extendedKeysShown && m_keymap.getExtendedChars(touch.m_keyCoordinate))
{
QRect elipsisRect(r.left() + cPressedTranslateH, r.top() + cPressedTranslateV, r.width() - 9 + m_9tileCorner.m_trimH, r.height() - 9 + m_9tileCorner.m_trimV);
renderer.render(elipsisRect, GlyphSpec(sElipsis, cElipsisFontSize, false, cActiveColor, cActiveColor_back), sFont, Qt::AlignRight | Qt::AlignBottom);
}
if (!m_extendedKeys && m_showPopupKeys && key != Qt::Key_Shift && key != cKey_Symbol && key != Qt::Key_Space && key != Qt::Key_Return && key != Qt::Key_Backspace)
{
QPoint topLeft((r.left() + r.right() - m_popup.width()) / 2, r.top() - m_popup.height());
painter.drawPixmap(topLeft, m_popup);
QRect destRect(topLeft + QPoint((m_popup.width() - m_popup_key.width()) / 2, cPopupTopToKey), QSize(m_popup_key.width(), m_popup_key.height() / 2));
painter.drawPixmap(destRect.topLeft(), m_popup_key, QRect(0, m_popup_key.height() / 2, destRect.width(), destRect.height()));
drawKeyCap(&painter, renderer, destRect, touch.m_keyCoordinate, key, eUse_preview);
}
//g_debug("'%s' drawn pressed, consumed: %d", QString(key).toUtf8().data(), touch.m_consumed);
}
}
}
}
}
renderer.flush();
m_candidateBar.paintTrace(painter, keyboardFrame.top() + m_keyboardTopPading, cBlueColor, 4);
if (extendedKeysShown)
{
renderer.flush();
painter.setFont(sFont);
int cellCount, lineCount, lineLength;
getExtendedPopupSpec(cellCount, lineCount, lineLength);
IMEPixmap & popup = (lineCount > 1) ? m_popup_2 : m_popup;
QRect r(m_extendedKeysFrame);
int left = r.left() + cPopupSide;
int right = r.right() - cPopupSide + 1;
painter.drawPixmap(r.left(), r.top(), popup.pixmap(), 0, 0, cPopupSide, popup.height());
painter.drawPixmap(right, r.top(), popup.pixmap(), popup.width() - cPopupSide, 0, cPopupSide, popup.height());
int pointerLeft = m_extendedKeysPointer - cPopupPointerWidth / 2;
int pointerRight = pointerLeft + cPopupPointerWidth;
if (left < pointerLeft)
painter.drawPixmap(left, r.top(), pointerLeft - left, popup.height(), popup.pixmap(), cPopupSide, 0, 1, popup.height());
if (pointerRight < right)
painter.drawPixmap(pointerRight, r.top(), right - pointerRight, popup.height(), popup.pixmap(), cPopupSide, 0, 1, popup.height());
painter.drawPixmap(pointerLeft, r.top(), popup.pixmap(), cPopupPointerStart, 0, cPopupPointerWidth, popup.height());
r.translate(cPopupLeftSide, cPopupTopToKey);
UKey key;
for (int k = 0; (key = m_extendedKeys[k]) != cKey_None; ++k)
{
if (k < lineLength)
painter.drawPixmap(r.left() + k * m_popup_key.width(), r.top(), m_popup_key.pixmap(),
0, (extendedKey == key) ? m_popup_key.height() / 2 : 0, m_popup_key.width(), m_popup_key.height() / 2);
else
painter.drawPixmap(r.left() + (k - lineLength) * m_popup_key.width(), r.top() + m_popup_2.height() - m_popup.height(), m_popup_key.pixmap(),
0, (extendedKey == key) ? m_popup_key.height() / 2 : 0, m_popup_key.width(), m_popup_key.height() / 2);
}
r.setWidth(m_popup_key.width() - 3);
r.setHeight(m_popup_key.height() / 2 - 2);
QRect cell(r);
for (int k = 0; (key = m_extendedKeys[k]) != cKey_None; ++k)
{
if (k < lineLength)
cell.moveTopLeft(QPoint(r.left() + k * m_popup_key.width(), r.top()));
else
cell.moveTopLeft(QPoint(r.left() + (k - lineLength) * m_popup_key.width(), r.top() + m_popup_2.height() - m_popup.height()));
QPixmap * pix = (UKeyIsEmoticonKey(key) && m_keymap.showEmoticonsAsGraphics()) ? getPixmapForKey(key) : NULL;
if (pix)
{
drawCenteredPixmap(painter, *pix, cell);
}
else
{
QString text = m_keymap.getKeyDisplayString(key);
int fontSize = (text.length() < 6) ? cPopupFontSize : cPopupFontSize - 8;
if (sFont.pixelSize() != fontSize)
{
sFont.setPixelSize(fontSize);
painter.setFont(sFont);
}
renderer.render(cell, GlyphSpec(text, fontSize, false, cPopoutTextColor, cPopoutTextColor_back), sFont);
}
}
}
m_extendedKeyShown = extendedKey;
#if VKB_SHOW_GLYPH_CACHE
painter.setPen(QColor(255, 0, 0)); painter.drawRect(QRect(QPoint(0, 0), m_glyphCache.pixmap().size())); painter.drawPixmap(0, 0, m_glyphCache.pixmap());
#endif
#if VKB_FORCE_FPS
triggerRepaint();
#endif
if (renderer.getCacheMissCount() > 0 && m_keymap.getCachedGlyphsCount() < 3)
queueIdlePrerendering();
}
bool PhoneKeyboard::updateBackground()
{
if (!m_keyboardBackgound || m_keyboardDirty)
{
QRect keymapFrame(m_keymap.rect());
int width = keymapFrame.width();
int usedHeight = keymapFrame.height() + m_keyboardTopPading;
QRect keyboardFrame(keymapFrame.left(), keymapFrame.top() - m_keyboardTopPading, width, usedHeight);
if (!m_keyboardBackgound || m_keyboardBackgound->width() != width || m_keyboardBackgound->height() != usedHeight)
{
PixmapCache::instance().dispose(m_keyboardBackgound);
m_keyboardBackgound = PixmapCache::instance().get(width, usedHeight);
}
if (m_keymap.updateLimits() != m_keyboardLimitsVersion)
{
//g_critical("Rebuilding BACKGROUND");
m_keyboardLimitsVersion = m_keymap.updateLimits();
QPainter offscreenPainter(m_keyboardBackgound);
//m_keyboardBackgound->fill(QColor(255, 0, 0));
offscreenPainter.drawPixmap(QRect(0, 0, width, usedHeight), m_background.pixmap());
offscreenPainter.translate(0, -keyboardFrame.top());
offscreenPainter.setRenderHints(cRenderHints, true);
m_nineTileSprites.reserve(true);
for (int y = 0; y < PhoneKeymap::cKeymapRows; ++y)
{
for (int x = 0; x < PhoneKeymap::cKeymapColumns; ++x)
{
QPoint keyCoord(x, y);
UKey key = m_keymap.map(x, y);
QRect r;
int count = m_keymap.keyboardToKeyZone(keyCoord, r);
if (count > 0)
{
QSize size = r.size();
if (key == Qt::Key_Shift)
{
m_nineTileSprites.reserve(size, count, m_shift_on_key);
m_nineTileSprites.reserve(size, count, m_shift_lock_key);
m_nineTileSprites.reserve(size, count, m_black_key);
}
else
m_nineTileSprites.reserve(size, count, getKeyBackground(keyCoord, key));
}
}
}
m_nineTileSprites.reserve(false);
for (int y = 0; y < PhoneKeymap::cKeymapRows; ++y)
{
for (int x = 0; x < PhoneKeymap::cKeymapColumns; ++x)
{
UKey plainKey = m_keymap.map(x, y, PhoneKeymap::eLayoutPage_plain);
//if (plainKey != Qt::Key_Shift)
{
QPoint keyCoord(x, y);
QRect r;
int count = m_keymap.keyboardToKeyZone(keyCoord, r);
if (count > 0)
drawKeyBackground(offscreenPainter, r, keyCoord, plainKey, false, count);
}
}
}
}
m_keyboardDirty = false;
return true;
}
return false;
}
QPixmap & PhoneKeyboard::getKeyBackground(const QPoint & keyCoord, UKey key)
{
/*
if (key == Qt::Key_Shift)
{
switch (m_keymap.shiftMode())
{
case PhoneKeymap::eShiftMode_CapsLock: return m_shift_lock_key;
case PhoneKeymap::eShiftMode_Once: return m_shift_on_key;
default:
return m_black_key;
}
}
else
*/
return selectFromKeyType<QPixmap &>(m_keymap.map(keyCoord, PhoneKeymap::eLayoutPage_plain), m_white_key, m_black_key, m_gray_key);
}
QPixmap * PhoneKeyboard::getPixmapForKey(UKey key)
{
switch ((int)key)
{
case Qt::Key_Shift:
switch (m_keymap.shiftMode())
{
case PhoneKeymap::eShiftMode_Once: return &m_shift_on.pixmap(); break;
case PhoneKeymap::eShiftMode_CapsLock: return &m_shift_lock.pixmap(); break;
case PhoneKeymap::eShiftMode_Off:
default:
return m_keymap.isAutoCapActive() ? &m_shift_on.pixmap() : &m_shift.pixmap();
}
break;
case Qt::Key_Backspace: return &m_backspace.pixmap(); break;
case cKey_Hide: return &m_hide.pixmap(); break;
case cKey_Emoticon_Frown: return &m_emoticon_frown.pixmap(); break;
case cKey_Emoticon_Cry: return &m_emoticon_cry.pixmap(); break;
case cKey_Emoticon_Options:
case cKey_Emoticon_Smile: return &m_emoticon_smile.pixmap(); break;
case cKey_Emoticon_Wink: return &m_emoticon_wink.pixmap(); break;
case cKey_Emoticon_Yuck: return &m_emoticon_yuck.pixmap(); break;
case cKey_Emoticon_Gasp: return &m_emoticon_gasp.pixmap(); break;
case cKey_Emoticon_Heart: return &m_emoticon_heart.pixmap(); break;
default: /* NOP */;
}
return NULL;
}
void PhoneKeyboard::drawCenteredPixmap(QPainter & painter, QPixmap & pixmap, const QRect & location)
{
if (pixmap.height() > location.height() || pixmap.width() > location.width())
{
//g_debug("TabletKeyboard::drawKeyCap shrinking \"%s\" by %d pixels", m_keymap.getKeyDisplayString(key, true).toUtf8().data(), location.height() - pixmap.height());
painter.setRenderHints(cRenderHints, true);
if (pixmap.height() * location.width() > location.height() * pixmap.width())
{
int targetWidth = location.height() * pixmap.width() / pixmap.height();
painter.drawPixmap(location.left() + (location.width() - targetWidth) / 2, location.top(), targetWidth, location.height(), pixmap);
}
else
{
int targetHeight = location.width() * pixmap.height() / pixmap.width();
painter.drawPixmap(location.left(), location.top() + (location.height() - targetHeight) / 2, location.width(), targetHeight, pixmap);
}
}
else
painter.drawPixmap((int) location.left() + (location.width() - pixmap.width()) / 2, (int) location.top() + (location.height() - pixmap.height()) / 2, pixmap);
}
inline bool boostSize(QChar c)
{
ushort ci = c.unicode();
return ci == '.' || ci == ',' || ci == ';' || ci == ':' || ci == '\'' || ci == '"';
}
inline bool boostSize(QString s)
{
return s.size() == 1 && boostSize(s[0]);
}
//inline int font_size(const QString & text, const QColor & color, int baseSize, int percent)
//{
// if (color != cActiveColor)
// return baseSize * percent / 100;
// return boostSize(text) ? baseSize + 2 : baseSize;
//}
#define font_size(text, color, baseSize, percent) ((color != activeColor) ? (baseSize * percent / 100) : (boostSize(text) ? baseSize + 2 : baseSize))
void PhoneKeyboard::drawKeyCap(QPainter * painter, GlyphRenderer<GlyphSpec> & renderer, QRect location, const QPoint & keyCoord, UKey key, EUse use)
{
location.setBottom(location.bottom() - 4);
// if (pressed)
// location.translate(cPressedTranslateH, cPressedTranslateV);
QString text, altText;
bool twoHorizontal = false;
bool twoVertical = false;
bool useTwo = false;
QColor activeColor = useWhite(use) ? cActiveColor : cPopoutTextColor;
QColor activeColor_back = useWhite(use) ? cActiveColor_back : cPopoutTextColor_back;
QColor mainCharColor = activeColor;
QColor mainCharColor_back = activeColor_back;
QColor altCharColor = cDisabledColor;
QColor altCharColor_back = cDisabledColor_back;
bool capitalize = m_keymap.isCapOrAutoCapActive();
// bool capitalize = key >= Qt::Key_A && key <= Qt::Key_Z;
if (key == Qt::Key_Space)
text = m_candidateBar.autoSelectCandidate();
else if (UKeyIsUnicodeQtKey(key))
{ // key is also a unicode character...
UKey plain = m_keymap.map(keyCoord, PhoneKeymap::eLayoutPage_plain);
UKey alt = m_keymap.map(keyCoord, PhoneKeymap::eLayoutPage_Alternate);
if (plain != alt && alt != cKey_None)
{
useTwo = twoVertical = KeyCap_TwoVertical(keyCoord, plain);
if (twoVertical)
{
if (key == plain)
{
text = capitalize ? QChar(plain) : QChar(plain).toLower();
altText = QChar(alt).toLower();
}
else
{
mainCharColor = cDisabledColor;
mainCharColor_back = cDisabledColor_back;
altCharColor = activeColor;
altCharColor_back = activeColor_back;
text = QChar(plain).toLower();
altText = capitalize ? QChar(alt) : QChar(alt).toLower();
}
}
else
text = capitalize ? QChar(key) : QChar(key).toLower();
}
else
text = capitalize ? QChar(key) : QChar(key).toLower();
}
else if (((UKeyIsEmoticonKey(key) && m_keymap.showEmoticonsAsGraphics()) || (text = m_keymap.getKeyDisplayString(key)).size() == 0))
{
if (painter)
{
QPixmap * pix = getPixmapForKey(key);
if (pix)
{
int cPixMargin = UKeyIsEmoticonKey(key) ? 8 : 2;
location.adjust(cPixMargin, cPixMargin, - cPixMargin, - cPixMargin);
drawCenteredPixmap(*painter, *pix, location);
}
}
}
if (text.size() > 0)
{
sFont.setBold(useExtraLarge(use));
bool forceAlignHCenter = false; // if too tight, center text for better looking results
int height = location.height();
int fontSize = useExtraLarge(use) ? 32 : 24;
int centerOffset = 1;
if (useTwo && use == eUse_preview)
twoHorizontal = true, centerOffset = 2;
if (height / 2 < fontSize)
fontSize = (height + 1) / 2 + (useExtraLarge(use) ? 4 : 0);
if (text.size() > 1)
{
if (!useExtraLarge(use))
sFont.setBold(UKeyIsFunctionKey(key) && !UKeyIsTextShortcutKey(key));
fontSize = qMin<int>(fontSize, 22);
sFont.setPixelSize(fontSize);
int gap;
while ((gap = QFontMetrics(sFont).width(text) + 16 - location.width()) > 0) {
forceAlignHCenter = true;
int reduction = gap / text.length();
if (reduction < 1)
reduction = 1;
//g_debug("font size %d, Width = %d, gap = %d, reduction = %d", fontSize, location.width(), gap, reduction);
fontSize -= reduction;
sFont.setPixelSize(fontSize);
};
if (gap > -8)
forceAlignHCenter = true;
//g_debug("Using font size %d, Width = %d, text width = %d", fontSize, location.width(), QFontMetrics(sFont).width(text));
}
if (twoHorizontal)
{
if (mainCharColor == activeColor)
location.adjust(4, 1, -5, 1);
else
location.adjust(5, 1, -4, 1);
if (inLandscapeOrientation() == false)
fontSize -= 1;
QRect rect(location.left() + location.width() / 2 - centerOffset, location.top(), location.width() / 2, location.height());
renderer.render(rect, GlyphSpec(text, font_size(text, mainCharColor, fontSize, 75), sFont.bold(), mainCharColor, mainCharColor_back), sFont);
rect.moveLeft(location.left() + centerOffset);
renderer.render(rect, GlyphSpec(altText, font_size(altText, altCharColor, fontSize, 75), sFont.bold(), altCharColor, altCharColor_back), sFont);
}
else if (twoVertical)
{
int boxheight = location.height() / 3;
QRect rect(location.left(), location.bottom() - boxheight - 10 + (boostSize(text) ? -2 : 0), location.width(), boxheight);
renderer.render(rect, GlyphSpec(text, font_size(text, mainCharColor, fontSize, 75), sFont.bold(), mainCharColor, mainCharColor_back), sFont);
rect.moveTop(location.top() + 10);
renderer.render(rect, GlyphSpec(altText, font_size(altText, altCharColor, fontSize, 75), sFont.bold(), altCharColor, altCharColor_back), sFont);
}
else
{
/*
if (key == Qt::Key_Return)
{ // Smaller, bottom right corner...
location.setHeight((location.height()) * 90 / 100);
if (forceAlignHCenter)
renderer.render(location, GlyphSpec(text, qMin<int>(height, fontSize - 2), sFont.bold(), cFunctionColor, cFunctionColor_back), sFont, Qt::AlignBottom | Qt::AlignHCenter);
else
{
location.setWidth(location.width() * 85 / 100 + m_9tileCorner.m_trimH);
renderer.render(location, GlyphSpec(text, qMin<int>(height, fontSize - 2), sFont.bold(), cFunctionColor, cFunctionColor_back), sFont, Qt::AlignBottom | Qt::AlignRight);
}
}
else
*/
{
int size = qMin<int>(height, fontSize);
if (key == cKey_ToggleLanguage && text.endsWith('-')) // special case: strike the language key if the language ends with '-'
{
QString realText = text.left(text.size() - 1);
renderer.render(location, GlyphSpec(realText, size, sFont.bold(), mainCharColor, cFunctionColor_back), sFont);
if (painter)
{
renderer.flush();
painter->setPen(QPen(QBrush(cActiveColor), 4, Qt::SolidLine, Qt::RoundCap));
int width = QFontMetrics(sFont).width(realText) / 2 + 4;
int cx = (location.left() + location.right()) / 2;
int cy = (location.top() + location.bottom()) / 2;
painter->drawLine(cx - width, cy, cx + width, cy);
}
}
else if (key == Qt::Key_Space)
renderer.renderNow(location, GlyphSpec(text, size, sFont.bold(), mainCharColor, cFunctionColor_back), sFont);
else
renderer.render(location, GlyphSpec(text, size, sFont.bold(), mainCharColor, cFunctionColor_back), sFont);
}
}
sFont.setBold(false);
}
}
bool PhoneKeyboard::setShiftKeyDown(bool shiftKeyDown)
{
if (m_keymap.setShiftKeyDown(shiftKeyDown))
{
// if (m_IMEDataInterface)
// m_IMEDataInterface->sendKeyEvent(shiftKeyDown ? QEvent::KeyPress : QEvent::KeyRelease, Qt::Key_Shift, Qt::NoModifier);
keyboardLayoutChanged();
return true;
}
return false;
}
bool PhoneKeyboard::setSymbolKeyDown(bool symbolKeyDown)
{
if (m_keymap.setSymbolKeyDown(symbolKeyDown))
{
keyboardLayoutChanged();
return true;
}
return false;
}
void PhoneKeyboard::makeSound(UKey key)
{
if (VirtualKeyboardPreferences::instance().getTapSounds() && key != cKey_None)
m_IMEDataInterface->keyDownAudioFeedback(key);
}
void PhoneKeyboard::queueIdlePrerendering()
{
if (!m_idleInit)
{
m_idleInit = true;
g_idle_add_full(G_PRIORITY_LOW, keyboard_idle, NULL, NULL);
}
}
bool PhoneKeyboard::idle()
{ // there is only ever one PhoneKeyboard. Using statics to avoid exposing everywhere variables only used here
static int sCount = 0;
static bool sInitExtendedGlyphs = true;
if (m_IMEDataInterface->isUIAnimationActive())
return true;
if (sCount < IMEPixmap::count())
{
IMEPixmap::load(sCount++);
return true;
}
int index = sCount++ - IMEPixmap::count();
int stateIndex = index / PhoneKeymap::cKeymapRows;
int y = index % PhoneKeymap::cKeymapRows;
if (stateIndex < 3)
{ // pre-rendering all keyboards states for the current size, one row at a time...
DoubleDrawRenderer renderer;
GlyphCachePopulator<GlyphSpec> populator(m_glyphCache, renderer);
bool shiftDown = m_keymap.isShiftDown();
bool symbolDown = m_keymap.isSymbolDown();
bool autoCapActive = m_keymap.isAutoCapActive();
PhoneKeymap::EShiftMode shiftMode = m_keymap.shiftMode();
PhoneKeymap::ESymbolMode symbolMode = m_keymap.symbolMode();
m_keymap.setShiftKeyDown(false);
m_keymap.setSymbolKeyDown(false);
m_keymap.setAutoCap(false);
if (stateIndex == 0)
{
m_keymap.setShiftMode(PhoneKeymap::eShiftMode_Off);
m_keymap.setSymbolMode(PhoneKeymap::eSymbolMode_Off);
}
else if (stateIndex == 1)
{
m_keymap.setShiftMode(PhoneKeymap::eShiftMode_Once);
m_keymap.setSymbolMode(PhoneKeymap::eSymbolMode_Off);
}
else
{
m_keymap.setShiftMode(PhoneKeymap::eShiftMode_CapsLock);
m_keymap.setSymbolMode(PhoneKeymap::eSymbolMode_Lock);
}
std::string msg = string_printf("PhoneKeyboard pre-render (%dx%d): shift %d, symbol %d, autoCap %d, index=%d, y=%d", m_keymap.rect().width(), m_keymap.rect().height(), m_keymap.isShiftActive(), m_keymap.isSymbolActive(), m_keymap.isCapOrAutoCapActive(), stateIndex, y);
PerfMonitor perf(msg.c_str());
//g_debug("%s", msg.c_str());
for (int x = 0; x < PhoneKeymap::cKeymapColumns; ++x)
{
QPoint keyCoord(x, y);
UKey key = m_keymap.map(x, y);
QRect r;
int count = m_keymap.keyboardToKeyZone(keyCoord, r);
r.moveTo(0, 0);
if (count > 0 && key != Qt::Key_Space && key != cKey_None)
{
drawKeyCap(NULL, populator, r, keyCoord, key, eUse_unpressed);
drawKeyCap(NULL, populator, r, keyCoord, key, eUse_pressed);
drawKeyCap(NULL, populator, QRect(QPoint(), m_popup_key.size()), keyCoord, key, eUse_preview);
drawKeyCap(NULL, populator, QRect(QPoint(), m_popup_key.size()), keyCoord, key, eUse_extended);
}
}
m_keymap.setShiftKeyDown(shiftDown);
m_keymap.setSymbolKeyDown(symbolDown);
m_keymap.setAutoCap(autoCapActive);
m_keymap.setShiftMode(shiftMode);
m_keymap.setSymbolMode(symbolMode);
return true;
}
else if (stateIndex == 0 && y == 0)
{ // pre-rendering background, with 9-tiled keys
updateBackground();
return true;
}
else if (sInitExtendedGlyphs)
{ // pre-render extended chars, but only once per run (they are always shown at the same size & same color)
DoubleDrawRenderer renderer;
GlyphCachePopulator<GlyphSpec> populator(m_glyphCache, renderer);
static int x = -1;
static int y = -1;
static const UKey * extendedChars = NULL;
static int extendedIndex = 0;
if (x < 0 || y < 0 || x >= PhoneKeymap::cKeymapColumns || y >= PhoneKeymap::cKeymapRows)
{
x = y = 0;
extendedChars = m_keymap.getExtendedChars(QPoint(x, y));
extendedIndex = 0;
}
uint64_t timeLimit = CURRENT_TIME + 10; // process 10ms max
do {
if (extendedChars)
{
//g_debug("pre-render %dx%d %s...", x, y, QString(QChar(extendedChars[extendedIndex])).toUtf8().data());
if (UKeyIsUnicodeQtKey(extendedChars[extendedIndex]))
{
populator.render(QRect(QPoint(), m_popup_key.size()), GlyphSpec(QString(QChar(extendedChars[extendedIndex]).toLower()), cPopupFontSize, false, cPopoutTextColor, cPopoutTextColor_back), sFont);
populator.render(QRect(QPoint(), m_popup_key.size()), GlyphSpec(QString(QChar(extendedChars[extendedIndex]).toUpper()), cPopupFontSize, false, cPopoutTextColor, cPopoutTextColor_back), sFont);
}
if (!extendedChars[++extendedIndex])
extendedChars = NULL;
}
if (!extendedChars)
{
if (++x >= PhoneKeymap::cKeymapColumns)
{
x = 0;
if (++y >= PhoneKeymap::cKeymapRows)
break;
}
extendedChars = m_keymap.getExtendedChars(QPoint(x, y));
extendedIndex = 0;
}
if (CURRENT_TIME > timeLimit)
return true;
} while (true);
sInitExtendedGlyphs = false;
// cache elipsis...
populator.render(QRect(0, 0, 20, 20), GlyphSpec(sElipsis, cElipsisFontSize, false, cActiveColor, cActiveColor_back), sFont);
}
m_keymap.incCachedGlyphs();
sCount = IMEPixmap::count();
m_idleInit = false;
//g_debug("PhoneKeyboard background init complete!");
#if 0
#ifdef TARGET_DEVICE
m_glyphCache.pixmap().toImage().save("/media/internal/glyphcache.png");
#else
m_glyphCache.pixmap().toImage().save(QString(getenv("HOME")) + "/Desktop/glyphcache.png");
#endif
#endif
return false;
}
}; // namespace Phone_Keyboard
| 59,522 | 24,695 |
//#include <afx.h>
#include <R.h>
//#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <math.h>
#include "MyUtils.h"
#include "Tableau.h"
#define AUG_COST -1000000.00
#define LEEWAY ((double) 0.00001)
#define LINE_LEN 1024
#define MAX_SOL 50.00
float SolFactor[3] = // Indexed by TERM_SIGN
{-1.0f, 0.0f, +1.0f};
float SymFactor[3] = // Indexed by TERM_SIGN
{+1.0f, +1.0f, -1.0f};
void Approx (double & p_Value, double p_Point)
{
if (p_Value < p_Point + LEEWAY &&
p_Value > p_Point - LEEWAY)
p_Value = p_Point;
} /* Approx () */
CTableau :: CTableau (
int p_ParamCnt,
int p_Rows,
Label_ p_pParamNames[],
pFloat_ * p_pA,
double * p_pb
//************************
// Ax <= b
//************************
)
{
Setup (p_ParamCnt, p_Rows, p_pParamNames, p_pA, p_pb);
} /* CTableau :: CTableau () */
void CTableau :: Setup (
int p_ParamCnt,
int p_Rows,
Label_ p_pParamNames[],
pFloat_ * p_pA,
double * p_pb
//************************
// Ax <= b
//************************
)
{
int nParam;
int nVar;
int nRow;
int nBasis;
int nAug;
double Coef;
double YCoef;
m_pEnumList = NULL;
m_pEnumCrnt = NULL;
m_EnumListLen = 0;
memset (m_pVertices, NULL, sizeof (m_pVertices));
// Check that the number of rows is greater than the number of parameters.
//
if (p_Rows <= p_ParamCnt)
{
//Rprintf ("ERROR: Let A be a mxn matrix. m must be greater than n.\n");
error ("ERROR: Let A be a mxn matrix. m must be greater than n.\n");
}
//
//****************************************************************
// Get the names of all the parameters.
//
m_ParamCnt = p_ParamCnt;
m_pParamNames = new Label_ [m_ParamCnt];
for (nParam = 0; nParam < m_ParamCnt; nParam++)
strcpy (m_pParamNames [nParam], p_pParamNames [nParam]);
//************************
// Determine how many augmented variables must be added.
// This is just the number of negative entries in the solution
// vector 'b'.
m_AugCnt = 0;
for (nRow = 0; nRow < p_Rows; nRow++)
{
if (p_pb [nRow] < 0.0)
m_AugCnt++;
}
//**********************************************************
// Evaluate the number of variables required and label them.
m_VarCnt = 1 + m_ParamCnt + 1 + p_Rows + m_AugCnt;
m_pVarLabels = new Label_ [m_VarCnt];
strcpy (m_pVarLabels [0], "nz");
for (nParam = 0; nParam < m_ParamCnt; nParam++)
{
nVar = 1 + nParam;
strcpy (m_pVarLabels [nVar], p_pParamNames [nParam]);
}
strcpy (m_pVarLabels [1 + m_ParamCnt], "y");
for (nRow = 0; nRow < p_Rows; nRow++)
{
nVar = 1 + m_ParamCnt + 1 + nRow;
sprintf (m_pVarLabels [nVar], "$%02d", nRow);
}
for (nAug = 0; nAug < m_AugCnt; nAug++)
{
nVar = 1 + m_ParamCnt + 1 + p_Rows + nAug;
sprintf (m_pVarLabels [nVar], "@%02d", nAug);
}
//**************************************
// Determine the size of the basis for this problem.
m_BasisCnt = p_Rows + 1;
//***********************************************************
// Done incorporating optimization problem parameters.
// Allocate the space for the Tableau.
//***********************************************************
m_pOrigBasisVars = new int [m_BasisCnt];
memset (m_pOrigBasisVars, 0, m_BasisCnt * sizeof (int));
m_pBasisVars = new int [m_BasisCnt];
memset (m_pBasisVars, 0, m_BasisCnt * sizeof (int));
m_pOrigSolution = new double [m_BasisCnt];
memset (m_pOrigSolution, 0, m_BasisCnt * sizeof (double));
m_pSolution = new double [m_BasisCnt];
memset (m_pSolution, 0, m_BasisCnt * sizeof (double));
m_pCj = new double [m_VarCnt];
memset (m_pCj, 0, m_VarCnt * sizeof (double));
m_pOrigTable = new pFloat_ [m_BasisCnt];
m_pTable = new pFloat_ [m_BasisCnt];
for (nBasis = 0; nBasis < m_BasisCnt; nBasis++)
{
m_pOrigTable [nBasis] = new double [m_VarCnt];
memset (m_pOrigTable [nBasis], 0, m_VarCnt * sizeof(double));
m_pTable [nBasis] = new double [m_VarCnt];
memset (m_pTable [nBasis], 0, m_VarCnt * sizeof(double));
}
//******************************
// Instantiate the Tableau from the given matrix, A.
m_pOrigTable [0][0] = 1.0;
m_pOrigTable [0][1 + m_ParamCnt] = 1.0;
m_pCj [1 + m_ParamCnt] = 1.0;
nAug = 0;
for (nRow = 0; nRow < p_Rows; nRow++)
{
nBasis = nRow + 1;
//****************************
// Determine the set of variables to use in the basis,
// and set the table coefficients for the augmented
// variables.
// Also determine the coefficient to be used for the
// current basis row.
//***************************
if (p_pb [nRow] < 0)
{
//***********************************
// The slack variable will have a negative
// coefficient; use an augmented variable
// in the basis.
//***********************************
Coef = -1.0;
nVar = 1 + m_ParamCnt + 1 + p_Rows + nAug;
m_pOrigTable [nBasis][nVar] = 1.0;
m_pCj [nVar] = AUG_COST;
m_pOrigBasisVars [nBasis] = nVar;
nAug++;
}
else
{
//************************************
// Use the slack variable in the basis.
//************************************
nVar = 1 + m_ParamCnt + 1 + nRow;
m_pOrigBasisVars [nBasis] = nVar;
Coef = 1.0;
}
//**************************************
// Set the entries corresponding to the user defined
// parameters.
// At the same time compute the coefficient for the
// 'y' variable.
//**************************************
YCoef = 0.0;
for (nParam = 0; nParam < m_ParamCnt; nParam++)
{
nVar = 1 + nParam;
m_pOrigTable [nBasis][nVar] = Coef * p_pA [nRow][nParam];
YCoef += p_pA [nRow][nParam] *
p_pA [nRow][nParam];
}
nVar = 1 + m_ParamCnt;
m_pOrigTable [nBasis][nVar] = Coef * sqrt (YCoef);
//**************************************
// Set the entries corresponding to the slack variables.
//**************************************
nVar = 1 + m_ParamCnt + 1 + nRow;
m_pOrigTable [nBasis][nVar] = Coef;
//*****************************************
// Set the solution value to be non-negative.
//****************************************
m_pOrigSolution [nBasis] = Coef * p_pb [nRow];
}
//*******************************
// Copy the original tableau over to the working copy.
//*******************************
Reset ();
m_VertexCnt = 0;
m_pSlackFlag = new char [m_BasisCnt - 1];
memset (m_pSlackFlag, 0, (m_BasisCnt - 1) * sizeof (char));
} /* CTableau :: Setup () */
CTableau :: CTableau (FILE * p_pFile)
{
char szLine [LINE_LEN];
char szWord [LINE_LEN];
char bMinimize;
int ParamCnt;
int ConstCnt;
Label_ * pParamNames;
String_ * pszConstraints;
String_ szObjective;
int nParam;
int nConst;
int ScanRslt;
char* objGet;
//*****************************************************************
// Determine whether to Minimize or Maximize the objective
// function.
//
while (1)
{
if (fgets (szLine, LINE_LEN, p_pFile) == 0)
{
//printf ("ERROR: didn't find Min/Max specifier\n");
error ("ERROR: didn't find Min/Max specifier\n");
}
sscanf (szLine, "%s", szWord);
if (strcmp (szWord, "MAXIMIZE") == 0)
{
bMinimize = 0;
break;
}
if (strcmp (szWord, "MINIMIZE") == 0)
{
bMinimize = 1;
break;
}
}
//
//****************************************************************
// Get the number of parameters.
//
while (1)
{
if (fgets (szLine, LINE_LEN, p_pFile) == 0)
{
//Rprintf ("ERROR: didn't find 'PARAMETERS'\n");
error ("ERROR: didn't find 'PARAMETERS'\n");
}
sscanf (szLine, "%s", szWord);
if (strcmp (szWord, "PARAMETERS") == 0)
break;
}
ParamCnt = 0;
while (1)
{
if (fgets (szLine, LINE_LEN, p_pFile) == 0)
{
//Rprintf ("ERROR: no 'CONSTRAINTS' line\n");
error ("ERROR: no 'CONSTRAINTS' line\n");
}
if (sscanf (szLine, "%s", szWord) >= 0)
{
if (strcmp (szWord, "CONSTRAINTS") == 0)
break;
else
ParamCnt++;
}
}
pParamNames = new Label_ [ParamCnt];
//
//****************************************************************
// Get the number of constraints.
//
ConstCnt = 0;
while (1)
{
if (fgets (szLine, LINE_LEN, p_pFile) == 0)
{
//Rprintf ("ERROR: no 'OBJECTIVE' line\n");
error ("ERROR: no 'OBJECTIVE' line\n");
}
if (sscanf (szLine, "%s", szWord) >= 0)
{
if (strcmp (szWord, "OBJECTIVE") == 0)
break;
else
ConstCnt++;
}
}
pszConstraints = new String_ [ConstCnt];
//
//******************************************************
// Copy the objective function
//
objGet = fgets (szObjective, LINE_LEN, p_pFile);
// Go back to beginning of file.
rewind (p_pFile);
//
//************************************************
// Find the parameter names and copy them.
//
while (1)
{
if (fgets (szLine, LINE_LEN, p_pFile) == 0)
{
//printf ("ERROR: didn't find 'PARAMETERS'\n");
error ("ERROR: didn't find 'PARAMETERS'\n");
}
sscanf (szLine, "%s", szWord);
if (strcmp (szWord, "PARAMETERS") == 0)
break;
}
nParam = 0;
while (1)
{
if (fgets (szLine, LINE_LEN, p_pFile) == 0)
{
//Rprintf ("ERROR: no 'CONSTRAINTS' line\n");
error ("ERROR: no 'CONSTRAINTS' line\n");
}
if (sscanf (szLine, "%s", szWord) >= 0)
{
if (strcmp (szWord, "CONSTRAINTS") == 0)
break;
else
{
strcpy (pParamNames [nParam], szWord);
nParam++;
}
}
}
//
//****************************************
// Find the constraints and copy them.
//
nConst = 0;
while (1)
{
if (fgets (szLine, LINE_LEN, p_pFile) == 0)
{
//Rprintf ("ERROR: no 'OBJECTIVE' line\n");
error ("ERROR: no 'OBJECTIVE' line\n");
}
if (sscanf (szLine, "%s", szWord) >= 0)
{
if (strcmp (szWord, "OBJECTIVE") == 0)
break;
else
{
strcpy (pszConstraints [nConst], szLine);
nConst++;
}
}
}
// Setup (p_bVertices, bMinimize, ParamCnt, pParamNames,
// ConstCnt, pszConstraints, szObjective);
} /* CTableau :: CTableau () */
//======================================
// FUNCTION: Reset
// PURPOSE:
// Sets the Working Tableau equal to the Original Tableau.
//======================================
void CTableau :: Reset ()
{
int nBasis;
int nVar;
for (nBasis = 0; nBasis < m_BasisCnt; nBasis++)
{
m_pSolution [nBasis] = m_pOrigSolution [nBasis];
m_pBasisVars [nBasis] = m_pOrigBasisVars [nBasis];
}
for (nVar = 0; nVar < m_VarCnt; nVar++)
{
for (nBasis = 0; nBasis < m_BasisCnt; nBasis++)
{
m_pTable [nBasis] [nVar] = m_pOrigTable [nBasis] [nVar];
}
}
} /* CTableau :: Reset () */
CTableau :: ~CTableau ()
{
CEnumRcd * pNextRcd;
CEnumRcd * pEnumRcd;
for (int nBasis = 0; nBasis < m_BasisCnt; nBasis++)
{
delete [] m_pOrigTable [nBasis];
delete [] m_pTable [nBasis];
}
delete [] m_pTable;
delete [] m_pOrigTable;
delete [] m_pBasisVars;
delete [] m_pOrigBasisVars;
delete [] m_pSolution;
delete [] m_pOrigSolution;
delete [] m_pCj;
delete [] m_pSlackFlag;
// delete m_pConstraints;
// delete m_pObjective;
delete m_pVarLabels;
delete m_pParamNames;
for (int nVertex = 0; nVertex < MAX_VERTICES; nVertex++)
if (m_pVertices [nVertex])
delete [] m_pVertices [nVertex];
pEnumRcd = m_pEnumList;
while (pEnumRcd)
{
pNextRcd = pEnumRcd-> m_pNext;
delete [] pEnumRcd-> Contents ();
delete pEnumRcd;
pEnumRcd = pNextRcd;
}
} /* CTableau :: ~CTableau () */
/*=======================================
| FUNCTION: TradeBasis
| PURPOSE:
| Swaps the indicated non-basis variable for the specified
| basis variable.
========================================*/
void CTableau :: TradeBasis (int p_Basis, int p_Var)
{
double Pivot;
double Factor;
int nVar;
int nBasis;
Pivot = m_pTable [p_Basis] [p_Var];
m_pBasisVars [p_Basis] = p_Var;
m_pSolution [p_Basis] /= Pivot;
for (nVar = 0; nVar < m_VarCnt; nVar++)
{
m_pTable [p_Basis] [nVar] /= Pivot;
}
for (nBasis = 0; nBasis < m_BasisCnt; nBasis++)
{
if (nBasis != p_Basis)
{
Factor = m_pTable [nBasis] [p_Var];
m_pSolution [nBasis] -= Factor * m_pSolution [p_Basis];
Approx (m_pSolution [nBasis], 0.0);
for (nVar = 0; nVar < m_VarCnt; nVar++)
{
m_pTable [nBasis] [nVar] -=
Factor * m_pTable [p_Basis] [nVar];
Approx (m_pTable [nBasis][nVar], 0.0);
}
}
}
} /* CTableau :: TradeBasis () */
std::string CTableau :: DecisionDisplay ()
{
int nBasis;
int nVar;
char buffer[100];
std::string result;
result.append ("Basis");
for (nBasis = 0; nBasis < m_BasisCnt; nBasis++)
{
sprintf (buffer, "%7s", m_pVarLabels [m_pBasisVars [nBasis]]);
result.append (buffer);
}
result.append ("\n");
for (nVar = 0; nVar < m_VarCnt; nVar++)
{
// Display only the nonbasis variables.
for (nBasis = 0; nBasis < m_BasisCnt; nBasis++)
if (m_pBasisVars [nBasis] == nVar)
break;
if (nBasis < m_BasisCnt)
continue;
sprintf (buffer, "%7s", m_pVarLabels [nVar]);
result.append(buffer);
for (nBasis = 0; nBasis < m_BasisCnt; nBasis++)
{
sprintf (buffer, "%7.3lf", m_pTable [nBasis][nVar]);
result.append(buffer);
}
result.append ("\n");
}
result.append ( "Sol");
for (nBasis = 0; nBasis < m_BasisCnt; nBasis++)
{
sprintf (buffer, "%7.3lf", m_pSolution [nBasis]);
result.append(buffer);
}
result.append ("\n\n");
return result;
} /* CTableau :: DecisionDisplay () */
/*=================================
| FUNCTION: DetermineSwap
| PURPOSE:
| Determines which non-basis and basis variable to swap.
===================================*/
void CTableau :: DetermineSwap (int & p_Basis, int & p_Var)
{
int nBasis;
int nVar;
int nFirstAug;
double Contr;
double MaxPosContr = 0.0;
double Ratio;
double MinRatio;
p_Var = -1;
for (nVar = 1; nVar < m_VarCnt; nVar++)
{
//===============================
// Compute zj-cj for this column
//===============================
Contr = m_pCj [nVar];
for (nBasis = 1; nBasis < m_BasisCnt; nBasis++)
{
Contr -= m_pTable [nBasis][nVar] *
m_pCj [m_pBasisVars [nBasis]];
}
if (Contr > MaxPosContr)
{
MaxPosContr = Contr;
p_Var = nVar;
}
}
if (p_Var < 0)
{
return;
}
p_Basis = -1;
MinRatio = 1000000.0;
for (nBasis = 1; nBasis < m_BasisCnt; nBasis++)
{
if (m_pTable [nBasis] [p_Var] > LEEWAY)
{
Ratio = m_pSolution [nBasis] / m_pTable [nBasis] [p_Var];
if (Ratio >= 0.0 &&
Ratio < MinRatio)
{
MinRatio = Ratio;
p_Basis = nBasis;
}
}
}
} /* CTableau :: DetermineSwap () */
double CTableau :: GetSolution (char * p_szVarName)
{
for (int nBasis = 0; nBasis < m_BasisCnt; nBasis++)
{
if (strcmp (p_szVarName, m_pVarLabels [m_pBasisVars [nBasis]]) == 0)
{
return m_pSolution [nBasis];
}
}
return 0.0;
} /* CTableau :: GetValue () */
double CTableau :: ObjectiveValue ()
{
return -m_pSolution [0];
} /* CTableau :: ObjectiveValue () */
char CTableau :: Optimize ()
{
int nVar;
int Var;
int Basis;
//#define MYDEBUG
while (1)
{
#ifdef MYDEBUG
DecisionDisplay ();
#endif
DetermineSwap (Basis, Var);
#ifdef MYDEBUG
Rprintf ("Var: %4s, Basis: %4s\n",
m_pVarLabels [Var],
m_pVarLabels [m_pBasisVars[Basis]]);
#endif
if (Var < 0 || Basis < 0)
break;
TradeBasis (Basis, Var);
}
return 1;
} /* CTableau :: Optimize () */
void CTableau :: DisplayBasis ()
{
int nBasis;
for (nBasis = 0; nBasis < m_BasisCnt; nBasis++)
{
Rprintf ("%s: %lf\n", m_pVarLabels [m_pBasisVars [nBasis]],
m_pSolution [nBasis]);
}
} /* CTableau :: DisplayBasis () */
void CTableau :: DisplayParams ()
{
int nVar;
int nBasis;
for (nVar = m_BasisCnt;
nVar < m_BasisCnt + m_ParamCnt; nVar++)
{
for (nBasis = 0; nBasis < m_BasisCnt; nBasis++)
{
if (nVar == m_pBasisVars [nBasis])
{
Rprintf ("%5s: %lf\n", m_pVarLabels [nVar],
m_pSolution [nBasis]);
break;
}
}
}
} /* CTableau :: DisplayParams () */
void CTableau :: DropVars ()
{
m_VarCnt = 1 + m_ParamCnt + 1 + (m_BasisCnt - 1);
m_AugCnt = 0;
// Changing these values will not affect the later deallocation of the
// Tableau.
} /* CTableau :: DropVars () */
//======================================
// FUNCTION: WorkToOrig
// PURPOSE:
// Sets the Original Tableau equal to the Working Tableau.
//======================================
void CTableau :: WorkToOrig ()
{
int nBasis;
int nVar;
for (nBasis = 0; nBasis < m_BasisCnt; nBasis++)
{
m_pOrigSolution [nBasis] = m_pSolution [nBasis];
m_pOrigBasisVars [nBasis] = m_pBasisVars [nBasis];
}
for (nVar = 0; nVar < m_VarCnt; nVar++)
{
for (nBasis = 0; nBasis < m_BasisCnt; nBasis++)
{
m_pOrigTable [nBasis] [nVar] = m_pTable [nBasis] [nVar];
}
}
} /* CTableau :: WorkToOrig () */
WORD * CTableau :: PopFirst ()
{
int * pNonBasics;
CEnumRcd * pNextRcd;
CEnumRcd * pEnumRcd;
double CrntValue;
double NewValue;
int nNonBasis;
if (m_pEnumList == NULL)
return NULL;
if (m_pEnumCrnt == NULL)
{
m_pEnumCrnt = m_pEnumList;
return m_pEnumCrnt-> Contents ();
}
if (m_pEnumCrnt-> m_pNext == NULL)
{
// printf ("No more records, deleting all:\n");
// DisplayEnumRcds ();
return NULL;
}
CrntValue = m_pEnumCrnt-> Value ();
NewValue = m_pEnumCrnt-> m_pNext-> Value ();
m_pEnumCrnt = m_pEnumCrnt-> m_pNext;
if (NewValue > CrntValue + LEEWAY)
{
//Rprintf ("ERROR: The list is not monotonically non-increasing.\n");
error ("ERROR: The list is not monotonically non-increasing.\n");
}
if (NewValue < CrntValue - LEEWAY)
{
//=================================
// Remove all the preceding elements in the
// list. They are no longer needed for eliminating
// duplicates.
//==================================
pEnumRcd = m_pEnumList;
while (pEnumRcd != m_pEnumCrnt)
{
// printf ("Deleting record: %6.3lf :", pEnumRcd-> Value ());
// for (nNonBasis = 0; nNonBasis < m_VarCnt - m_BasisCnt;
// nNonBasis++)
// {
// printf (" %4s", m_pVarLabels [
// (pEnumRcd-> Contents ()) [nNonBasis]]);
// }
// printf ("\n");
pNextRcd = pEnumRcd-> m_pNext;
delete [] pEnumRcd-> Contents ();
delete pEnumRcd;
pEnumRcd = pNextRcd;
m_EnumListLen--;
}
m_pEnumList = m_pEnumCrnt;
// DisplayEnumRcds ();
}
return m_pEnumCrnt-> Contents ();
} /* CTableau :: PopFirst () */
void CTableau :: AddUnique (double p_Value, WORD * p_pNonBasics)
{
CEnumRcd * pCurrent;
CEnumRcd ** ppPrior;
CEnumRcd * pNew;
double Value;
int nNonBasis;
// printf (":v%lf", p_Value);
ppPrior = &m_pEnumList;
pCurrent = m_pEnumList;
while (pCurrent != NULL)
{
Value = pCurrent-> Value ();
if (p_Value < Value + LEEWAY &&
p_Value > Value - LEEWAY)
{
// See if the new record is non-unique.
// This assumes that the non-basic variables are
// always ordered by index value.
for (nNonBasis = 0; nNonBasis < m_VarCnt - m_BasisCnt; nNonBasis++)
{
if (p_pNonBasics [nNonBasis] !=
(pCurrent-> Contents ())[nNonBasis])
break;
}
if (nNonBasis == m_VarCnt - m_BasisCnt)
{
// NonBasis is not unique; do not add to list.
delete [] p_pNonBasics;
return;
}
}
else if (p_Value > Value)
{
pNew = new CEnumRcd (p_Value, p_pNonBasics);
*ppPrior = pNew;
pNew-> m_pNext = pCurrent;
m_EnumListLen++;
return;
}
ppPrior = &(pCurrent-> m_pNext);
pCurrent = pCurrent-> m_pNext;
}
pNew = new CEnumRcd (p_Value, p_pNonBasics);
*ppPrior = pNew;
m_EnumListLen++;
} /* CTableau :: AddUnique () */
void CTableau :: DisplayEnumRcds ()
{
CEnumRcd * pCurrent;
WORD * pNonBasis;
int nNonBasis;
Rprintf ("Contents of Enum List\n");
pCurrent = m_pEnumList;
while (pCurrent != NULL)
{
Rprintf ("\t%6.3lf : ", pCurrent-> Value ());
pNonBasis = pCurrent-> Contents ();
for (nNonBasis = 0; nNonBasis < m_VarCnt - m_BasisCnt; nNonBasis++)
{
Rprintf ("%4s ", m_pVarLabels [pNonBasis [nNonBasis]]);
}
if (pCurrent == m_pEnumCrnt)
Rprintf (" **");
Rprintf ("\n");
pCurrent = pCurrent-> m_pNext;
}
} /* CTableau :: DisplayEnumRcds () */
std::string CTableau :: VertexEnumerate ()
{
int nBasis;
int nNonBasis;
int nSlack;
WORD * pNonBasics;
int nVar;
int PivotBasis;
double MinRatio;
double Ratio;
double * pNewSol;
int * pBasisVars;
double Factor;
double Pivot;
char szResponse[100];
char buffer[1024];
std::string result;
result.append ("Table before optimizing Y.\n");
result.append ("--------------------------\n");
pNewSol = new double [m_BasisCnt];
pBasisVars = new int [m_BasisCnt];
result.append(DecisionDisplay ());
Optimize ();
DropVars ();
WorkToOrig ();
AddEnumRcd (m_pBasisVars, - m_pSolution[0]);
// DisplayEnumRcds ();
while ((pNonBasics = PopFirst ()) != NULL)
{
// printf ("Analyzing: ");
// for (nNonBasis = 0; nNonBasis < m_VarCnt - m_BasisCnt; nNonBasis++)
// {
// printf (" %4s", m_pVarLabels [pNonBasics [nNonBasis]]);
// }
// printf ("\n");
R_CheckUserInterrupt();
GenerateTableau (pNonBasics);
// Flag all the nonbasic slack variables. This is later used to
// identify relevant constraints.
for (nNonBasis = 0; nNonBasis < m_VarCnt - m_BasisCnt; nNonBasis++)
{
m_pSlackFlag [pNonBasics [nNonBasis] - m_ParamCnt - 2] = 1;
}
// DecisionDisplay ();
for (nNonBasis = 0; nNonBasis < m_VarCnt - m_BasisCnt; nNonBasis++)
{
nVar = pNonBasics [nNonBasis];
#ifdef MYDEBUG
Rprintf ("NonBasis [%d] = %4s\n", nNonBasis,
m_pVarLabels [pNonBasics [nNonBasis]]);
#endif
if (m_pTable [0][nVar] > LEEWAY)
continue;
//==============================
// Find the basis to pivot on.
//==============================
MinRatio = 1000000.0;
for (nBasis = 1; nBasis < m_BasisCnt; nBasis++)
{
if (m_pTable [nBasis] [nVar] > LEEWAY &&
m_pSolution [nBasis] >= -LEEWAY)
{
Ratio = m_pSolution [nBasis] / m_pTable [nBasis] [nVar];
if (Ratio >= - LEEWAY &&
Ratio < MinRatio)
{
MinRatio = Ratio;
}
}
}
for (PivotBasis = 1; PivotBasis < m_BasisCnt; PivotBasis++)
{
R_CheckUserInterrupt();
if (m_pTable [PivotBasis] [nVar] <= LEEWAY)
continue;
Ratio = m_pSolution [PivotBasis] /
m_pTable [PivotBasis] [nVar];
if (Ratio < -LEEWAY ||
Ratio > MinRatio + LEEWAY)
continue;
if (m_pBasisVars [PivotBasis] >= 1 &&
m_pBasisVars [PivotBasis] < 1 + m_ParamCnt)
//==================================
// Pivot is a user-defined parameter.
//==================================
continue;
for (nBasis = 0; nBasis < m_BasisCnt; nBasis++)
{
pNewSol [nBasis] = m_pSolution [nBasis];
pBasisVars [nBasis] = m_pBasisVars [nBasis];
}
//===============================
// Evaluate the new solutions and basis
// variables given the pivot point.
//===============================
Pivot = m_pTable [PivotBasis] [nVar];
pBasisVars [PivotBasis] = nVar;
pNewSol [PivotBasis] /= Pivot;
for (nBasis = 0; nBasis < m_BasisCnt; nBasis++)
{
if (nBasis != PivotBasis)
{
Factor = m_pTable [nBasis] [nVar];
pNewSol [nBasis] -= Factor * pNewSol [PivotBasis];
}
}
// printf ("Pivot %5s for %5s\n",
// m_pVarLabels [nVar],
// m_pVarLabels [m_pBasisVars [PivotBasis]]);
if (m_pBasisVars [PivotBasis] == 1 + m_ParamCnt)
{
//===================================
// Pivot is Y.
//===================================
AddVertex (pBasisVars, pNewSol);
// printf ("\nVERTEX:\n");
// for (nBasis = 0; nBasis < m_BasisCnt; nBasis++)
// {
// printf ("\t%5s: %lf\n",
// m_pVarLabels [pBasisVars [nBasis]],
// pNewSol [nBasis]);
// }
}
else
{
//===================================
// Pivot is a slack variable.
//===================================
// If Y = 0.0, then the solution corresponds to a
// point in the n-dim space, K; therefore, do not
// add the point as a subsystem in the (n+1)-dim
// space (currently, I do not know if this is
// absolutely correct).
if (- pNewSol [0] > LEEWAY)
{
AddEnumRcd (pBasisVars, - pNewSol [0]);
}
}
}
}
}
result.append(DisplayVertices ());
result.append ("Irrelevant contraints:\n");
for (nSlack = 0; nSlack < m_BasisCnt - 1; nSlack++)
{
if (m_pSlackFlag [nSlack] == 0)
{
sprintf (buffer, "\t%d\n", nSlack);
result.append(buffer);
}
}
delete [] pNewSol;
return result;
} /* CTableau :: VertexEnumerate () */
void CTableau :: GenerateTableau (WORD * p_pNonBasics)
{
int nRow;
int nVar;
int nNonBasis = 0;
char * pbBasis;
int nBasis;
int MaxRow;
double MaxAbs;
double FTemp;
pbBasis = new char [m_VarCnt];
Reset ();
memset (pbBasis, 1, m_VarCnt * sizeof (char));
for (nNonBasis = 0; nNonBasis < m_VarCnt - m_BasisCnt; nNonBasis++)
pbBasis [p_pNonBasics [nNonBasis]] = 0;
nBasis = 1;
for (nVar = 1; nVar < m_VarCnt; nVar++)
{
if (pbBasis [nVar])
{
m_pBasisVars [nBasis] = nVar;
nBasis++;
}
}
if (nBasis != m_BasisCnt)
{
//Rprintf ("ERROR: GenerateTableau: incorrect basis count.\n");
error ("ERROR: GenerateTableau: incorrect basis count.\n");
}
for (nBasis = 1; nBasis < m_BasisCnt; nBasis++)
{
nVar = m_pBasisVars [nBasis];
if (m_pTable [nBasis][nVar] < LEEWAY &&
m_pTable [nBasis][nVar] > -LEEWAY)
{
//===========================
// Make sure the pivot element is not zero.
//=============================
MaxRow = 0;
MaxAbs = 0.0;
for (nRow = nBasis; nRow < m_BasisCnt; nRow++)
{
FTemp = m_pTable [nRow][nVar];
FTemp = fabs(FTemp);
if (FTemp > MaxAbs)
{
MaxRow = nRow;
MaxAbs = FTemp;
}
}
FactorAddRows (MaxRow, nBasis, 1.0);
}
DivideRow (nBasis, m_pTable [nBasis][nVar]);
for (nRow = 0; nRow < m_BasisCnt; nRow++)
{
if (nRow != nBasis)
FactorAddRows (nBasis, nRow, -m_pTable [nRow][nVar]);
}
}
delete [] pbBasis;
} /* CTableau :: GenerateTableau () */
void CTableau :: DivideRow (int p_Basis, double p_Divisor)
{
int nVar;
if (p_Divisor < LEEWAY &&
p_Divisor > -LEEWAY)
return;
m_pSolution [p_Basis] /= p_Divisor;
for (nVar = 1; nVar < m_VarCnt; nVar++)
{
m_pTable [p_Basis][nVar] /= p_Divisor;
}
} /* CTableau :: DivideRow () */
void CTableau :: FactorAddRows (int p_SrcRow, int p_TgtRow, double p_Factor)
{
int nVar;
m_pSolution [p_TgtRow] +=
p_Factor * m_pSolution [p_SrcRow];
for (nVar = 1; nVar < m_VarCnt; nVar++)
{
m_pTable [p_TgtRow][nVar] +=
p_Factor * m_pTable [p_SrcRow][nVar];
}
} /* CTableau :: AddRows () */
void CTableau :: AddEnumRcd (int * p_pBasisVars, double p_Value)
{
int nVar;
int nBasis;
char * pbBasis;
WORD * pNonBasis;
int nNonBasis;
pbBasis = new char [m_VarCnt];
pNonBasis = new /*int*/ WORD [m_VarCnt - m_BasisCnt];
memset (pbBasis, 0, m_VarCnt * sizeof (char));
for (nBasis = 0; nBasis < m_BasisCnt; nBasis++)
{
pbBasis[p_pBasisVars [nBasis]] = 1;
}
nNonBasis = 0;
for (nVar = 0; nVar < m_VarCnt; nVar++)
{
if (pbBasis [nVar] == 0)
{
pNonBasis[nNonBasis] = (WORD) nVar;
nNonBasis++;
}
}
AddUnique (p_Value, pNonBasis);
//printf (":%d", m_EnumListLen);
delete [] pbBasis;
// printf ("\nAdding Enum Record: %6.3lf :", p_Value);
// for (nNonBasis = 0; nNonBasis < m_VarCnt - m_BasisCnt; nNonBasis++)
// {
// printf (" %4s", m_pVarLabels [pNonBasis [nNonBasis]]);
// }
// printf ("\n");
// DisplayEnumRcds ();
} /* CTableau :: AddEnumRcd () */
void CTableau :: AddVertex (int * p_pBasisVars, double * p_pSolution)
{
double * pVertex;
int nBasis;
int nParam;
int nVertex;
double NewVal;
double OldVal;
if (m_VertexCnt >= MAX_VERTICES)
{
error ("ERROR: Exceeded maximum number of vertices.\n");
return;
}
pVertex = new double [m_ParamCnt];
memset (pVertex, 0, m_ParamCnt * sizeof (double));
for (nBasis = 1; nBasis < m_BasisCnt; nBasis++)
{
if (p_pBasisVars [nBasis] >= 1 &&
p_pBasisVars [nBasis] <= m_ParamCnt)
{
pVertex [p_pBasisVars [nBasis] - 1] =
p_pSolution [nBasis];
}
}
//============================
// Check that all coordinates in the vertex are
// not positively extreme. Otherwise, do not add vertex.
//============================
for (nVertex = 0; nVertex < m_ParamCnt; nVertex++)
{
if (pVertex [nVertex] > MAX_SOL)
{
delete [] pVertex;
//printf ("-");
return;
}
}
//============================
// Check vertex for uniqueness.
//============================
for (nVertex = 0; nVertex < m_VertexCnt; nVertex++)
{
for (nParam = 0; nParam < m_ParamCnt; nParam++)
{
NewVal = pVertex [nParam];
OldVal = m_pVertices [nVertex][nParam];
if (NewVal < OldVal - LEEWAY ||
NewVal > OldVal + LEEWAY)
break;
}
if (nParam == m_ParamCnt)
break; // Duplicate found.
}
if (nVertex == m_VertexCnt)
{
// Vertex is unique.
m_pVertices [m_VertexCnt] = pVertex;
m_VertexCnt++;
//printf ("\nADDED Unique Vertex!\n");
// DisplayVertices ();
// DecisionDisplay ();
}
else
{
delete [] pVertex;
//printf ("\n+");
}
} /* CTableau :: AddVertex () */
std::string CTableau :: DisplayVertices ()
{
int nVertex;
int nParam;
char buffer[1024];
std::string result;
result.append ("\n\n");
for (nParam = 0; nParam < m_ParamCnt; nParam++)
{
sprintf (buffer, "%6s ", m_pVarLabels [nParam + 1]);
result.append(buffer);
}
result.append ("\n\n");
for (nVertex = 0; nVertex < m_VertexCnt; nVertex++)
{
for (nParam = 0; nParam < m_ParamCnt; nParam++)
{
sprintf (buffer, "%6.3lf ", m_pVertices [nVertex][nParam]);
result.append(buffer);
}
result.append ("\n");
}
return result;
} /* CTableau :: DisplayVertices () */
BOOL CTableau :: GetVertex (int p_nVertex, double * p_pVertex, int p_VertexLength)
{
int nParam;
if (p_VertexLength != m_ParamCnt)
return FALSE;
if (p_nVertex >= m_VertexCnt)
return FALSE;
for (nParam = 0; nParam < m_ParamCnt; nParam++)
p_pVertex [nParam] = m_pVertices [p_nVertex][nParam];
return TRUE;
}
| 30,109 | 14,206 |
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other GpuMaterials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation 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.
//
//M*/
#ifndef __OPENCV_GPU_HPP__
#define __OPENCV_GPU_HPP__
#include <vector>
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/gpu/gpumat.hpp"
namespace cv
{
namespace gpu
{
//////////////////////////////// Initialization & Info ////////////////////////
//! This is the only function that do not throw exceptions if the library is compiled without Cuda.
CV_EXPORTS int getCudaEnabledDeviceCount();
//! Functions below throw cv::Expception if the library is compiled without Cuda.
CV_EXPORTS void setDevice(int device);
CV_EXPORTS int getDevice();
//! Explicitly destroys and cleans up all resources associated with the current device in the current process.
//! Any subsequent API call to this device will reinitialize the device.
CV_EXPORTS void resetDevice();
enum FeatureSet
{
FEATURE_SET_COMPUTE_10 = 10,
FEATURE_SET_COMPUTE_11 = 11,
FEATURE_SET_COMPUTE_12 = 12,
FEATURE_SET_COMPUTE_13 = 13,
FEATURE_SET_COMPUTE_20 = 20,
FEATURE_SET_COMPUTE_21 = 21,
GLOBAL_ATOMICS = FEATURE_SET_COMPUTE_11,
NATIVE_DOUBLE = FEATURE_SET_COMPUTE_13
};
// Gives information about what GPU archs this OpenCV GPU module was
// compiled for
class CV_EXPORTS TargetArchs
{
public:
static bool builtWith(FeatureSet feature_set);
static bool has(int major, int minor);
static bool hasPtx(int major, int minor);
static bool hasBin(int major, int minor);
static bool hasEqualOrLessPtx(int major, int minor);
static bool hasEqualOrGreater(int major, int minor);
static bool hasEqualOrGreaterPtx(int major, int minor);
static bool hasEqualOrGreaterBin(int major, int minor);
private:
TargetArchs();
};
// Gives information about the given GPU
class CV_EXPORTS DeviceInfo
{
public:
// Creates DeviceInfo object for the current GPU
DeviceInfo() : device_id_(getDevice()) { query(); }
// Creates DeviceInfo object for the given GPU
DeviceInfo(int device_id) : device_id_(device_id) { query(); }
string name() const { return name_; }
// Return compute capability versions
int majorVersion() const { return majorVersion_; }
int minorVersion() const { return minorVersion_; }
int multiProcessorCount() const { return multi_processor_count_; }
size_t freeMemory() const;
size_t totalMemory() const;
// Checks whether device supports the given feature
bool supports(FeatureSet feature_set) const;
// Checks whether the GPU module can be run on the given device
bool isCompatible() const;
int deviceID() const { return device_id_; }
private:
void query();
void queryMemory(size_t& free_memory, size_t& total_memory) const;
int device_id_;
string name_;
int multi_processor_count_;
int majorVersion_;
int minorVersion_;
};
//////////////////////////////// Error handling ////////////////////////
CV_EXPORTS void error(const char *error_string, const char *file, const int line, const char *func);
CV_EXPORTS void nppError( int err, const char *file, const int line, const char *func);
//////////////////////////////// CudaMem ////////////////////////////////
// CudaMem is limited cv::Mat with page locked memory allocation.
// Page locked memory is only needed for async and faster coping to GPU.
// It is convertable to cv::Mat header without reference counting
// so you can use it with other opencv functions.
// Page-locks the matrix m memory and maps it for the device(s)
CV_EXPORTS void registerPageLocked(Mat& m);
// Unmaps the memory of matrix m, and makes it pageable again.
CV_EXPORTS void unregisterPageLocked(Mat& m);
class CV_EXPORTS CudaMem
{
public:
enum { ALLOC_PAGE_LOCKED = 1, ALLOC_ZEROCOPY = 2, ALLOC_WRITE_COMBINED = 4 };
CudaMem();
CudaMem(const CudaMem& m);
CudaMem(int rows, int cols, int type, int _alloc_type = ALLOC_PAGE_LOCKED);
CudaMem(Size size, int type, int alloc_type = ALLOC_PAGE_LOCKED);
//! creates from cv::Mat with coping data
explicit CudaMem(const Mat& m, int alloc_type = ALLOC_PAGE_LOCKED);
~CudaMem();
CudaMem& operator = (const CudaMem& m);
//! returns deep copy of the matrix, i.e. the data is copied
CudaMem clone() const;
//! allocates new matrix data unless the matrix already has specified size and type.
void create(int rows, int cols, int type, int alloc_type = ALLOC_PAGE_LOCKED);
void create(Size size, int type, int alloc_type = ALLOC_PAGE_LOCKED);
//! decrements reference counter and released memory if needed.
void release();
//! returns matrix header with disabled reference counting for CudaMem data.
Mat createMatHeader() const;
operator Mat() const;
//! maps host memory into device address space and returns GpuMat header for it. Throws exception if not supported by hardware.
GpuMat createGpuMatHeader() const;
operator GpuMat() const;
//returns if host memory can be mapperd to gpu address space;
static bool canMapHostMemory();
// Please see cv::Mat for descriptions
bool isContinuous() const;
size_t elemSize() const;
size_t elemSize1() const;
int type() const;
int depth() const;
int channels() const;
size_t step1() const;
Size size() const;
bool empty() const;
// Please see cv::Mat for descriptions
int flags;
int rows, cols;
size_t step;
uchar* data;
int* refcount;
uchar* datastart;
uchar* dataend;
int alloc_type;
};
//////////////////////////////// CudaStream ////////////////////////////////
// Encapculates Cuda Stream. Provides interface for async coping.
// Passed to each function that supports async kernel execution.
// Reference counting is enabled
class CV_EXPORTS Stream
{
public:
Stream();
~Stream();
Stream(const Stream&);
Stream& operator=(const Stream&);
bool queryIfComplete();
void waitForCompletion();
//! downloads asynchronously.
// Warning! cv::Mat must point to page locked memory (i.e. to CudaMem data or to its subMat)
void enqueueDownload(const GpuMat& src, CudaMem& dst);
void enqueueDownload(const GpuMat& src, Mat& dst);
//! uploads asynchronously.
// Warning! cv::Mat must point to page locked memory (i.e. to CudaMem data or to its ROI)
void enqueueUpload(const CudaMem& src, GpuMat& dst);
void enqueueUpload(const Mat& src, GpuMat& dst);
void enqueueCopy(const GpuMat& src, GpuMat& dst);
void enqueueMemSet(GpuMat& src, Scalar val);
void enqueueMemSet(GpuMat& src, Scalar val, const GpuMat& mask);
// converts matrix type, ex from float to uchar depending on type
void enqueueConvert(const GpuMat& src, GpuMat& dst, int type, double a = 1, double b = 0);
static Stream& Null();
operator bool() const;
private:
void create();
void release();
struct Impl;
Impl *impl;
friend struct StreamAccessor;
explicit Stream(Impl* impl);
};
//////////////////////////////// Filter Engine ////////////////////////////////
/*!
The Base Class for 1D or Row-wise Filters
This is the base class for linear or non-linear filters that process 1D data.
In particular, such filters are used for the "horizontal" filtering parts in separable filters.
*/
class CV_EXPORTS BaseRowFilter_GPU
{
public:
BaseRowFilter_GPU(int ksize_, int anchor_) : ksize(ksize_), anchor(anchor_) {}
virtual ~BaseRowFilter_GPU() {}
virtual void operator()(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null()) = 0;
int ksize, anchor;
};
/*!
The Base Class for Column-wise Filters
This is the base class for linear or non-linear filters that process columns of 2D arrays.
Such filters are used for the "vertical" filtering parts in separable filters.
*/
class CV_EXPORTS BaseColumnFilter_GPU
{
public:
BaseColumnFilter_GPU(int ksize_, int anchor_) : ksize(ksize_), anchor(anchor_) {}
virtual ~BaseColumnFilter_GPU() {}
virtual void operator()(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null()) = 0;
int ksize, anchor;
};
/*!
The Base Class for Non-Separable 2D Filters.
This is the base class for linear or non-linear 2D filters.
*/
class CV_EXPORTS BaseFilter_GPU
{
public:
BaseFilter_GPU(const Size& ksize_, const Point& anchor_) : ksize(ksize_), anchor(anchor_) {}
virtual ~BaseFilter_GPU() {}
virtual void operator()(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null()) = 0;
Size ksize;
Point anchor;
};
/*!
The Base Class for Filter Engine.
The class can be used to apply an arbitrary filtering operation to an image.
It contains all the necessary intermediate buffers.
*/
class CV_EXPORTS FilterEngine_GPU
{
public:
virtual ~FilterEngine_GPU() {}
virtual void apply(const GpuMat& src, GpuMat& dst, Rect roi = Rect(0,0,-1,-1), Stream& stream = Stream::Null()) = 0;
};
//! returns the non-separable filter engine with the specified filter
CV_EXPORTS Ptr<FilterEngine_GPU> createFilter2D_GPU(const Ptr<BaseFilter_GPU>& filter2D, int srcType, int dstType);
//! returns the separable filter engine with the specified filters
CV_EXPORTS Ptr<FilterEngine_GPU> createSeparableFilter_GPU(const Ptr<BaseRowFilter_GPU>& rowFilter,
const Ptr<BaseColumnFilter_GPU>& columnFilter, int srcType, int bufType, int dstType);
//! returns horizontal 1D box filter
//! supports only CV_8UC1 source type and CV_32FC1 sum type
CV_EXPORTS Ptr<BaseRowFilter_GPU> getRowSumFilter_GPU(int srcType, int sumType, int ksize, int anchor = -1);
//! returns vertical 1D box filter
//! supports only CV_8UC1 sum type and CV_32FC1 dst type
CV_EXPORTS Ptr<BaseColumnFilter_GPU> getColumnSumFilter_GPU(int sumType, int dstType, int ksize, int anchor = -1);
//! returns 2D box filter
//! supports CV_8UC1 and CV_8UC4 source type, dst type must be the same as source type
CV_EXPORTS Ptr<BaseFilter_GPU> getBoxFilter_GPU(int srcType, int dstType, const Size& ksize, Point anchor = Point(-1, -1));
//! returns box filter engine
CV_EXPORTS Ptr<FilterEngine_GPU> createBoxFilter_GPU(int srcType, int dstType, const Size& ksize,
const Point& anchor = Point(-1,-1));
//! returns 2D morphological filter
//! only MORPH_ERODE and MORPH_DILATE are supported
//! supports CV_8UC1 and CV_8UC4 types
//! kernel must have CV_8UC1 type, one rows and cols == ksize.width * ksize.height
CV_EXPORTS Ptr<BaseFilter_GPU> getMorphologyFilter_GPU(int op, int type, const Mat& kernel, const Size& ksize,
Point anchor=Point(-1,-1));
//! returns morphological filter engine. Only MORPH_ERODE and MORPH_DILATE are supported.
CV_EXPORTS Ptr<FilterEngine_GPU> createMorphologyFilter_GPU(int op, int type, const Mat& kernel,
const Point& anchor = Point(-1,-1), int iterations = 1);
//! returns 2D filter with the specified kernel
//! supports CV_8UC1 and CV_8UC4 types
CV_EXPORTS Ptr<BaseFilter_GPU> getLinearFilter_GPU(int srcType, int dstType, const Mat& kernel, const Size& ksize,
Point anchor = Point(-1, -1));
//! returns the non-separable linear filter engine
CV_EXPORTS Ptr<FilterEngine_GPU> createLinearFilter_GPU(int srcType, int dstType, const Mat& kernel,
const Point& anchor = Point(-1,-1));
//! returns the primitive row filter with the specified kernel.
//! supports only CV_8UC1, CV_8UC4, CV_16SC1, CV_16SC2, CV_32SC1, CV_32FC1 source type.
//! there are two version of algorithm: NPP and OpenCV.
//! NPP calls when srcType == CV_8UC1 or srcType == CV_8UC4 and bufType == srcType,
//! otherwise calls OpenCV version.
//! NPP supports only BORDER_CONSTANT border type.
//! OpenCV version supports only CV_32F as buffer depth and
//! BORDER_REFLECT101, BORDER_REPLICATE and BORDER_CONSTANT border types.
CV_EXPORTS Ptr<BaseRowFilter_GPU> getLinearRowFilter_GPU(int srcType, int bufType, const Mat& rowKernel,
int anchor = -1, int borderType = BORDER_CONSTANT);
//! returns the primitive column filter with the specified kernel.
//! supports only CV_8UC1, CV_8UC4, CV_16SC1, CV_16SC2, CV_32SC1, CV_32FC1 dst type.
//! there are two version of algorithm: NPP and OpenCV.
//! NPP calls when dstType == CV_8UC1 or dstType == CV_8UC4 and bufType == dstType,
//! otherwise calls OpenCV version.
//! NPP supports only BORDER_CONSTANT border type.
//! OpenCV version supports only CV_32F as buffer depth and
//! BORDER_REFLECT101, BORDER_REPLICATE and BORDER_CONSTANT border types.
CV_EXPORTS Ptr<BaseColumnFilter_GPU> getLinearColumnFilter_GPU(int bufType, int dstType, const Mat& columnKernel,
int anchor = -1, int borderType = BORDER_CONSTANT);
//! returns the separable linear filter engine
CV_EXPORTS Ptr<FilterEngine_GPU> createSeparableLinearFilter_GPU(int srcType, int dstType, const Mat& rowKernel,
const Mat& columnKernel, const Point& anchor = Point(-1,-1), int rowBorderType = BORDER_DEFAULT,
int columnBorderType = -1);
//! returns filter engine for the generalized Sobel operator
CV_EXPORTS Ptr<FilterEngine_GPU> createDerivFilter_GPU(int srcType, int dstType, int dx, int dy, int ksize,
int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1);
//! returns the Gaussian filter engine
CV_EXPORTS Ptr<FilterEngine_GPU> createGaussianFilter_GPU(int type, Size ksize, double sigma1, double sigma2 = 0,
int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1);
//! returns maximum filter
CV_EXPORTS Ptr<BaseFilter_GPU> getMaxFilter_GPU(int srcType, int dstType, const Size& ksize, Point anchor = Point(-1,-1));
//! returns minimum filter
CV_EXPORTS Ptr<BaseFilter_GPU> getMinFilter_GPU(int srcType, int dstType, const Size& ksize, Point anchor = Point(-1,-1));
//! smooths the image using the normalized box filter
//! supports CV_8UC1, CV_8UC4 types
CV_EXPORTS void boxFilter(const GpuMat& src, GpuMat& dst, int ddepth, Size ksize, Point anchor = Point(-1,-1), Stream& stream = Stream::Null());
//! a synonym for normalized box filter
static inline void blur(const GpuMat& src, GpuMat& dst, Size ksize, Point anchor = Point(-1,-1), Stream& stream = Stream::Null()) { boxFilter(src, dst, -1, ksize, anchor, stream); }
//! erodes the image (applies the local minimum operator)
CV_EXPORTS void erode( const GpuMat& src, GpuMat& dst, const Mat& kernel, Point anchor = Point(-1, -1), int iterations = 1, Stream& stream = Stream::Null());
//! dilates the image (applies the local maximum operator)
CV_EXPORTS void dilate( const GpuMat& src, GpuMat& dst, const Mat& kernel, Point anchor = Point(-1, -1), int iterations = 1, Stream& stream = Stream::Null());
//! applies an advanced morphological operation to the image
CV_EXPORTS void morphologyEx( const GpuMat& src, GpuMat& dst, int op, const Mat& kernel, Point anchor = Point(-1, -1), int iterations = 1, Stream& stream = Stream::Null());
//! applies non-separable 2D linear filter to the image
CV_EXPORTS void filter2D(const GpuMat& src, GpuMat& dst, int ddepth, const Mat& kernel, Point anchor=Point(-1,-1), Stream& stream = Stream::Null());
//! applies separable 2D linear filter to the image
CV_EXPORTS void sepFilter2D(const GpuMat& src, GpuMat& dst, int ddepth, const Mat& kernelX, const Mat& kernelY,
Point anchor = Point(-1,-1), int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1, Stream& stream = Stream::Null());
//! applies generalized Sobel operator to the image
CV_EXPORTS void Sobel(const GpuMat& src, GpuMat& dst, int ddepth, int dx, int dy, int ksize = 3, double scale = 1,
int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1, Stream& stream = Stream::Null());
//! applies the vertical or horizontal Scharr operator to the image
CV_EXPORTS void Scharr(const GpuMat& src, GpuMat& dst, int ddepth, int dx, int dy, double scale = 1,
int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1, Stream& stream = Stream::Null());
//! smooths the image using Gaussian filter.
CV_EXPORTS void GaussianBlur(const GpuMat& src, GpuMat& dst, Size ksize, double sigma1, double sigma2 = 0,
int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1, Stream& stream = Stream::Null());
//! applies Laplacian operator to the image
//! supports only ksize = 1 and ksize = 3
CV_EXPORTS void Laplacian(const GpuMat& src, GpuMat& dst, int ddepth, int ksize = 1, double scale = 1, Stream& stream = Stream::Null());
////////////////////////////// Arithmetics ///////////////////////////////////
//! transposes the matrix
//! supports matrix with element size = 1, 4 and 8 bytes (CV_8UC1, CV_8UC4, CV_16UC2, CV_32FC1, etc)
CV_EXPORTS void transpose(const GpuMat& src1, GpuMat& dst, Stream& stream = Stream::Null());
//! reverses the order of the rows, columns or both in a matrix
//! supports CV_8UC1, CV_8UC4 types
CV_EXPORTS void flip(const GpuMat& a, GpuMat& b, int flipCode, Stream& stream = Stream::Null());
//! transforms 8-bit unsigned integers using lookup table: dst(i)=lut(src(i))
//! destination array will have the depth type as lut and the same channels number as source
//! supports CV_8UC1, CV_8UC3 types
CV_EXPORTS void LUT(const GpuMat& src, const Mat& lut, GpuMat& dst, Stream& stream = Stream::Null());
//! makes multi-channel array out of several single-channel arrays
CV_EXPORTS void merge(const GpuMat* src, size_t n, GpuMat& dst, Stream& stream = Stream::Null());
//! makes multi-channel array out of several single-channel arrays
CV_EXPORTS void merge(const vector<GpuMat>& src, GpuMat& dst, Stream& stream = Stream::Null());
//! copies each plane of a multi-channel array to a dedicated array
CV_EXPORTS void split(const GpuMat& src, GpuMat* dst, Stream& stream = Stream::Null());
//! copies each plane of a multi-channel array to a dedicated array
CV_EXPORTS void split(const GpuMat& src, vector<GpuMat>& dst, Stream& stream = Stream::Null());
//! computes magnitude of complex (x(i).re, x(i).im) vector
//! supports only CV_32FC2 type
CV_EXPORTS void magnitude(const GpuMat& x, GpuMat& magnitude, Stream& stream = Stream::Null());
//! computes squared magnitude of complex (x(i).re, x(i).im) vector
//! supports only CV_32FC2 type
CV_EXPORTS void magnitudeSqr(const GpuMat& x, GpuMat& magnitude, Stream& stream = Stream::Null());
//! computes magnitude of each (x(i), y(i)) vector
//! supports only floating-point source
CV_EXPORTS void magnitude(const GpuMat& x, const GpuMat& y, GpuMat& magnitude, Stream& stream = Stream::Null());
//! computes squared magnitude of each (x(i), y(i)) vector
//! supports only floating-point source
CV_EXPORTS void magnitudeSqr(const GpuMat& x, const GpuMat& y, GpuMat& magnitude, Stream& stream = Stream::Null());
//! computes angle (angle(i)) of each (x(i), y(i)) vector
//! supports only floating-point source
CV_EXPORTS void phase(const GpuMat& x, const GpuMat& y, GpuMat& angle, bool angleInDegrees = false, Stream& stream = Stream::Null());
//! converts Cartesian coordinates to polar
//! supports only floating-point source
CV_EXPORTS void cartToPolar(const GpuMat& x, const GpuMat& y, GpuMat& magnitude, GpuMat& angle, bool angleInDegrees = false, Stream& stream = Stream::Null());
//! converts polar coordinates to Cartesian
//! supports only floating-point source
CV_EXPORTS void polarToCart(const GpuMat& magnitude, const GpuMat& angle, GpuMat& x, GpuMat& y, bool angleInDegrees = false, Stream& stream = Stream::Null());
//////////////////////////// Per-element operations ////////////////////////////////////
//! adds one matrix to another (c = a + b)
//! supports CV_8UC1, CV_8UC4, CV_32SC1, CV_32FC1 types
CV_EXPORTS void add(const GpuMat& a, const GpuMat& b, GpuMat& c, Stream& stream = Stream::Null());
//! adds scalar to a matrix (c = a + s)
//! supports CV_32FC1 and CV_32FC2 type
CV_EXPORTS void add(const GpuMat& a, const Scalar& sc, GpuMat& c, Stream& stream = Stream::Null());
//! subtracts one matrix from another (c = a - b)
//! supports CV_8UC1, CV_8UC4, CV_32SC1, CV_32FC1 types
CV_EXPORTS void subtract(const GpuMat& a, const GpuMat& b, GpuMat& c, Stream& stream = Stream::Null());
//! subtracts scalar from a matrix (c = a - s)
//! supports CV_32FC1 and CV_32FC2 type
CV_EXPORTS void subtract(const GpuMat& a, const Scalar& sc, GpuMat& c, Stream& stream = Stream::Null());
//! computes element-wise product of the two arrays (c = a * b)
//! supports CV_8UC1, CV_8UC4, CV_32SC1, CV_32FC1 types
CV_EXPORTS void multiply(const GpuMat& a, const GpuMat& b, GpuMat& c, Stream& stream = Stream::Null());
//! multiplies matrix to a scalar (c = a * s)
//! supports CV_32FC1 type
CV_EXPORTS void multiply(const GpuMat& a, const Scalar& sc, GpuMat& c, Stream& stream = Stream::Null());
//! computes element-wise quotient of the two arrays (c = a / b)
//! supports CV_8UC1, CV_8UC4, CV_32SC1, CV_32FC1 types
CV_EXPORTS void divide(const GpuMat& a, const GpuMat& b, GpuMat& c, Stream& stream = Stream::Null());
//! computes element-wise quotient of matrix and scalar (c = a / s)
//! supports CV_32FC1 type
CV_EXPORTS void divide(const GpuMat& a, const Scalar& sc, GpuMat& c, Stream& stream = Stream::Null());
//! computes exponent of each matrix element (b = e**a)
//! supports only CV_32FC1 type
CV_EXPORTS void exp(const GpuMat& a, GpuMat& b, Stream& stream = Stream::Null());
//! computes power of each matrix element:
// (dst(i,j) = pow( src(i,j) , power), if src.type() is integer
// (dst(i,j) = pow(fabs(src(i,j)), power), otherwise
//! supports all, except depth == CV_64F
CV_EXPORTS void pow(const GpuMat& src, double power, GpuMat& dst, Stream& stream = Stream::Null());
//! computes natural logarithm of absolute value of each matrix element: b = log(abs(a))
//! supports only CV_32FC1 type
CV_EXPORTS void log(const GpuMat& a, GpuMat& b, Stream& stream = Stream::Null());
//! computes element-wise absolute difference of two arrays (c = abs(a - b))
//! supports CV_8UC1, CV_8UC4, CV_32SC1, CV_32FC1 types
CV_EXPORTS void absdiff(const GpuMat& a, const GpuMat& b, GpuMat& c, Stream& stream = Stream::Null());
//! computes element-wise absolute difference of array and scalar (c = abs(a - s))
//! supports only CV_32FC1 type
CV_EXPORTS void absdiff(const GpuMat& a, const Scalar& s, GpuMat& c, Stream& stream = Stream::Null());
//! compares elements of two arrays (c = a <cmpop> b)
//! supports CV_8UC4, CV_32FC1 types
CV_EXPORTS void compare(const GpuMat& a, const GpuMat& b, GpuMat& c, int cmpop, Stream& stream = Stream::Null());
//! performs per-elements bit-wise inversion
CV_EXPORTS void bitwise_not(const GpuMat& src, GpuMat& dst, const GpuMat& mask=GpuMat(), Stream& stream = Stream::Null());
//! calculates per-element bit-wise disjunction of two arrays
CV_EXPORTS void bitwise_or(const GpuMat& src1, const GpuMat& src2, GpuMat& dst, const GpuMat& mask=GpuMat(), Stream& stream = Stream::Null());
//! calculates per-element bit-wise conjunction of two arrays
CV_EXPORTS void bitwise_and(const GpuMat& src1, const GpuMat& src2, GpuMat& dst, const GpuMat& mask=GpuMat(), Stream& stream = Stream::Null());
//! calculates per-element bit-wise "exclusive or" operation
CV_EXPORTS void bitwise_xor(const GpuMat& src1, const GpuMat& src2, GpuMat& dst, const GpuMat& mask=GpuMat(), Stream& stream = Stream::Null());
//! computes per-element minimum of two arrays (dst = min(src1, src2))
CV_EXPORTS void min(const GpuMat& src1, const GpuMat& src2, GpuMat& dst, Stream& stream = Stream::Null());
//! computes per-element minimum of array and scalar (dst = min(src1, src2))
CV_EXPORTS void min(const GpuMat& src1, double src2, GpuMat& dst, Stream& stream = Stream::Null());
//! computes per-element maximum of two arrays (dst = max(src1, src2))
CV_EXPORTS void max(const GpuMat& src1, const GpuMat& src2, GpuMat& dst, Stream& stream = Stream::Null());
//! computes per-element maximum of array and scalar (dst = max(src1, src2))
CV_EXPORTS void max(const GpuMat& src1, double src2, GpuMat& dst, Stream& stream = Stream::Null());
////////////////////////////// Image processing //////////////////////////////
//! DST[x,y] = SRC[xmap[x,y],ymap[x,y]] with bilinear interpolation.
//! supports CV_8UC1, CV_8UC3 source types and CV_32FC1 map type
CV_EXPORTS void remap(const GpuMat& src, GpuMat& dst, const GpuMat& xmap, const GpuMat& ymap);
//! Does mean shift filtering on GPU.
CV_EXPORTS void meanShiftFiltering(const GpuMat& src, GpuMat& dst, int sp, int sr,
TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 5, 1));
//! Does mean shift procedure on GPU.
CV_EXPORTS void meanShiftProc(const GpuMat& src, GpuMat& dstr, GpuMat& dstsp, int sp, int sr,
TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 5, 1));
//! Does mean shift segmentation with elimination of small regions.
CV_EXPORTS void meanShiftSegmentation(const GpuMat& src, Mat& dst, int sp, int sr, int minsize,
TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 5, 1));
//! Does coloring of disparity image: [0..ndisp) -> [0..240, 1, 1] in HSV.
//! Supported types of input disparity: CV_8U, CV_16S.
//! Output disparity has CV_8UC4 type in BGRA format (alpha = 255).
CV_EXPORTS void drawColorDisp(const GpuMat& src_disp, GpuMat& dst_disp, int ndisp, Stream& stream = Stream::Null());
//! Reprojects disparity image to 3D space.
//! Supports CV_8U and CV_16S types of input disparity.
//! The output is a 4-channel floating-point (CV_32FC4) matrix.
//! Each element of this matrix will contain the 3D coordinates of the point (x,y,z,1), computed from the disparity map.
//! Q is the 4x4 perspective transformation matrix that can be obtained with cvStereoRectify.
CV_EXPORTS void reprojectImageTo3D(const GpuMat& disp, GpuMat& xyzw, const Mat& Q, Stream& stream = Stream::Null());
//! converts image from one color space to another
CV_EXPORTS void cvtColor(const GpuMat& src, GpuMat& dst, int code, int dcn = 0, Stream& stream = Stream::Null());
//! applies fixed threshold to the image
CV_EXPORTS double threshold(const GpuMat& src, GpuMat& dst, double thresh, double maxval, int type, Stream& stream = Stream::Null());
//! resizes the image
//! Supports INTER_NEAREST, INTER_LINEAR
//! supports CV_8UC1, CV_8UC4 types
CV_EXPORTS void resize(const GpuMat& src, GpuMat& dst, Size dsize, double fx=0, double fy=0, int interpolation = INTER_LINEAR, Stream& stream = Stream::Null());
//! warps the image using affine transformation
//! Supports INTER_NEAREST, INTER_LINEAR, INTER_CUBIC
CV_EXPORTS void warpAffine(const GpuMat& src, GpuMat& dst, const Mat& M, Size dsize, int flags = INTER_LINEAR, Stream& stream = Stream::Null());
//! warps the image using perspective transformation
//! Supports INTER_NEAREST, INTER_LINEAR, INTER_CUBIC
CV_EXPORTS void warpPerspective(const GpuMat& src, GpuMat& dst, const Mat& M, Size dsize, int flags = INTER_LINEAR, Stream& stream = Stream::Null());
//! builds plane warping maps
CV_EXPORTS void buildWarpPlaneMaps(Size src_size, Rect dst_roi, const Mat& R, double f, double s, double dist,
GpuMat& map_x, GpuMat& map_y, Stream& stream = Stream::Null());
//! builds cylindrical warping maps
CV_EXPORTS void buildWarpCylindricalMaps(Size src_size, Rect dst_roi, const Mat& R, double f, double s,
GpuMat& map_x, GpuMat& map_y, Stream& stream = Stream::Null());
//! builds spherical warping maps
CV_EXPORTS void buildWarpSphericalMaps(Size src_size, Rect dst_roi, const Mat& R, double f, double s,
GpuMat& map_x, GpuMat& map_y, Stream& stream = Stream::Null());
//! rotate 8bit single or four channel image
//! Supports INTER_NEAREST, INTER_LINEAR, INTER_CUBIC
//! supports CV_8UC1, CV_8UC4 types
CV_EXPORTS void rotate(const GpuMat& src, GpuMat& dst, Size dsize, double angle, double xShift = 0, double yShift = 0, int interpolation = INTER_LINEAR, Stream& stream = Stream::Null());
//! copies 2D array to a larger destination array and pads borders with user-specifiable constant
//! supports CV_8UC1, CV_8UC4, CV_32SC1 and CV_32FC1 types
CV_EXPORTS void copyMakeBorder(const GpuMat& src, GpuMat& dst, int top, int bottom, int left, int right, const Scalar& value = Scalar(), Stream& stream = Stream::Null());
//! computes the integral image
//! sum will have CV_32S type, but will contain unsigned int values
//! supports only CV_8UC1 source type
CV_EXPORTS void integral(const GpuMat& src, GpuMat& sum, Stream& stream = Stream::Null());
//! buffered version
CV_EXPORTS void integralBuffered(const GpuMat& src, GpuMat& sum, GpuMat& buffer, Stream& stream = Stream::Null());
//! computes the integral image and integral for the squared image
//! sum will have CV_32S type, sqsum - CV32F type
//! supports only CV_8UC1 source type
CV_EXPORTS void integral(const GpuMat& src, GpuMat& sum, GpuMat& sqsum, Stream& stream = Stream::Null());
//! computes squared integral image
//! result matrix will have 64F type, but will contain 64U values
//! supports source images of 8UC1 type only
CV_EXPORTS void sqrIntegral(const GpuMat& src, GpuMat& sqsum, Stream& stream = Stream::Null());
//! computes vertical sum, supports only CV_32FC1 images
CV_EXPORTS void columnSum(const GpuMat& src, GpuMat& sum);
//! computes the standard deviation of integral images
//! supports only CV_32SC1 source type and CV_32FC1 sqr type
//! output will have CV_32FC1 type
CV_EXPORTS void rectStdDev(const GpuMat& src, const GpuMat& sqr, GpuMat& dst, const Rect& rect, Stream& stream = Stream::Null());
//! computes Harris cornerness criteria at each image pixel
CV_EXPORTS void cornerHarris(const GpuMat& src, GpuMat& dst, int blockSize, int ksize, double k, int borderType=BORDER_REFLECT101);
CV_EXPORTS void cornerHarris(const GpuMat& src, GpuMat& dst, GpuMat& Dx, GpuMat& Dy, int blockSize, int ksize, double k, int borderType=BORDER_REFLECT101);
//! computes minimum eigen value of 2x2 derivative covariation matrix at each pixel - the cornerness criteria
CV_EXPORTS void cornerMinEigenVal(const GpuMat& src, GpuMat& dst, int blockSize, int ksize, int borderType=BORDER_REFLECT101);
CV_EXPORTS void cornerMinEigenVal(const GpuMat& src, GpuMat& dst, GpuMat& Dx, GpuMat& Dy, int blockSize, int ksize, int borderType=BORDER_REFLECT101);
//! performs per-element multiplication of two full (not packed) Fourier spectrums
//! supports 32FC2 matrixes only (interleaved format)
CV_EXPORTS void mulSpectrums(const GpuMat& a, const GpuMat& b, GpuMat& c, int flags, bool conjB=false);
//! performs per-element multiplication of two full (not packed) Fourier spectrums
//! supports 32FC2 matrixes only (interleaved format)
CV_EXPORTS void mulAndScaleSpectrums(const GpuMat& a, const GpuMat& b, GpuMat& c, int flags,
float scale, bool conjB=false);
//! Performs a forward or inverse discrete Fourier transform (1D or 2D) of floating point matrix.
//! Param dft_size is the size of DFT transform.
//!
//! If the source matrix is not continous, then additional copy will be done,
//! so to avoid copying ensure the source matrix is continous one. If you want to use
//! preallocated output ensure it is continuous too, otherwise it will be reallocated.
//!
//! Being implemented via CUFFT real-to-complex transform result contains only non-redundant values
//! in CUFFT's format. Result as full complex matrix for such kind of transform cannot be retrieved.
//!
//! For complex-to-real transform it is assumed that the source matrix is packed in CUFFT's format.
CV_EXPORTS void dft(const GpuMat& src, GpuMat& dst, Size dft_size, int flags=0);
//! computes convolution (or cross-correlation) of two images using discrete Fourier transform
//! supports source images of 32FC1 type only
//! result matrix will have 32FC1 type
CV_EXPORTS void convolve(const GpuMat& image, const GpuMat& templ, GpuMat& result,
bool ccorr=false);
struct CV_EXPORTS ConvolveBuf;
//! buffered version
CV_EXPORTS void convolve(const GpuMat& image, const GpuMat& templ, GpuMat& result,
bool ccorr, ConvolveBuf& buf);
struct CV_EXPORTS ConvolveBuf
{
ConvolveBuf() {}
ConvolveBuf(Size image_size, Size templ_size)
{ create(image_size, templ_size); }
void create(Size image_size, Size templ_size);
private:
static Size estimateBlockSize(Size result_size, Size templ_size);
friend void convolve(const GpuMat&, const GpuMat&, GpuMat&, bool, ConvolveBuf&);
Size result_size;
Size block_size;
Size dft_size;
int spect_len;
GpuMat image_spect, templ_spect, result_spect;
GpuMat image_block, templ_block, result_data;
};
//! computes the proximity map for the raster template and the image where the template is searched for
CV_EXPORTS void matchTemplate(const GpuMat& image, const GpuMat& templ, GpuMat& result, int method);
//! downsamples image
CV_EXPORTS void downsample(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null());
//! upsamples image
CV_EXPORTS void upsample(const GpuMat& src, GpuMat &dst, Stream& stream = Stream::Null());
//! smoothes the source image and downsamples it
CV_EXPORTS void pyrDown(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null());
struct CV_EXPORTS PyrDownBuf;
CV_EXPORTS void pyrDown(const GpuMat& src, GpuMat& dst, PyrDownBuf& buf, Stream& stream = Stream::Null());
struct CV_EXPORTS PyrDownBuf
{
PyrDownBuf() : image_type(-1) {}
PyrDownBuf(Size image_size, int image_type_) : image_type(-1) { create(image_size, image_type_); }
void create(Size image_size, int image_type_);
private:
friend void pyrDown(const GpuMat&, GpuMat&, PyrDownBuf&, Stream& stream);
static Mat ker;
GpuMat buf;
Ptr<FilterEngine_GPU> filter;
int image_type;
};
//! upsamples the source image and then smoothes it
CV_EXPORTS void pyrUp(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null());
struct CV_EXPORTS PyrUpBuf;
CV_EXPORTS void pyrUp(const GpuMat& src, GpuMat& dst, PyrUpBuf& buf, Stream& stream = Stream::Null());
struct CV_EXPORTS PyrUpBuf
{
PyrUpBuf() : image_type(-1) {}
PyrUpBuf(Size image_size, int image_type_) : image_type(-1) { create(image_size, image_type_); }
void create(Size image_size, int image_type_);
private:
friend void pyrUp(const GpuMat&, GpuMat&, PyrUpBuf&, Stream& stream);
static Mat ker;
GpuMat buf;
Ptr<FilterEngine_GPU> filter;
int image_type;
};
//! performs linear blending of two images
//! to avoid accuracy errors sum of weigths shouldn't be very close to zero
CV_EXPORTS void blendLinear(const GpuMat& img1, const GpuMat& img2, const GpuMat& weights1, const GpuMat& weights2,
GpuMat& result, Stream& stream = Stream::Null());
struct CV_EXPORTS CannyBuf;
CV_EXPORTS void Canny(const GpuMat& image, GpuMat& edges, double low_thresh, double high_thresh, int apperture_size = 3, bool L2gradient = false);
CV_EXPORTS void Canny(const GpuMat& image, CannyBuf& buf, GpuMat& edges, double low_thresh, double high_thresh, int apperture_size = 3, bool L2gradient = false);
CV_EXPORTS void Canny(const GpuMat& dx, const GpuMat& dy, GpuMat& edges, double low_thresh, double high_thresh, bool L2gradient = false);
CV_EXPORTS void Canny(const GpuMat& dx, const GpuMat& dy, CannyBuf& buf, GpuMat& edges, double low_thresh, double high_thresh, bool L2gradient = false);
struct CV_EXPORTS CannyBuf
{
CannyBuf() {}
explicit CannyBuf(const Size& image_size, int apperture_size = 3) {create(image_size, apperture_size);}
CannyBuf(const GpuMat& dx_, const GpuMat& dy_);
void create(const Size& image_size, int apperture_size = 3);
void release();
GpuMat dx, dy;
GpuMat dx_buf, dy_buf;
GpuMat edgeBuf;
GpuMat trackBuf1, trackBuf2;
Ptr<FilterEngine_GPU> filterDX, filterDY;
};
////////////////////////////// Matrix reductions //////////////////////////////
//! computes mean value and standard deviation of all or selected array elements
//! supports only CV_8UC1 type
CV_EXPORTS void meanStdDev(const GpuMat& mtx, Scalar& mean, Scalar& stddev);
//! computes norm of array
//! supports NORM_INF, NORM_L1, NORM_L2
//! supports all matrices except 64F
CV_EXPORTS double norm(const GpuMat& src1, int normType=NORM_L2);
//! computes norm of array
//! supports NORM_INF, NORM_L1, NORM_L2
//! supports all matrices except 64F
CV_EXPORTS double norm(const GpuMat& src1, int normType, GpuMat& buf);
//! computes norm of the difference between two arrays
//! supports NORM_INF, NORM_L1, NORM_L2
//! supports only CV_8UC1 type
CV_EXPORTS double norm(const GpuMat& src1, const GpuMat& src2, int normType=NORM_L2);
//! computes sum of array elements
//! supports only single channel images
CV_EXPORTS Scalar sum(const GpuMat& src);
//! computes sum of array elements
//! supports only single channel images
CV_EXPORTS Scalar sum(const GpuMat& src, GpuMat& buf);
//! computes sum of array elements absolute values
//! supports only single channel images
CV_EXPORTS Scalar absSum(const GpuMat& src);
//! computes sum of array elements absolute values
//! supports only single channel images
CV_EXPORTS Scalar absSum(const GpuMat& src, GpuMat& buf);
//! computes squared sum of array elements
//! supports only single channel images
CV_EXPORTS Scalar sqrSum(const GpuMat& src);
//! computes squared sum of array elements
//! supports only single channel images
CV_EXPORTS Scalar sqrSum(const GpuMat& src, GpuMat& buf);
//! finds global minimum and maximum array elements and returns their values
CV_EXPORTS void minMax(const GpuMat& src, double* minVal, double* maxVal=0, const GpuMat& mask=GpuMat());
//! finds global minimum and maximum array elements and returns their values
CV_EXPORTS void minMax(const GpuMat& src, double* minVal, double* maxVal, const GpuMat& mask, GpuMat& buf);
//! finds global minimum and maximum array elements and returns their values with locations
CV_EXPORTS void minMaxLoc(const GpuMat& src, double* minVal, double* maxVal=0, Point* minLoc=0, Point* maxLoc=0,
const GpuMat& mask=GpuMat());
//! finds global minimum and maximum array elements and returns their values with locations
CV_EXPORTS void minMaxLoc(const GpuMat& src, double* minVal, double* maxVal, Point* minLoc, Point* maxLoc,
const GpuMat& mask, GpuMat& valbuf, GpuMat& locbuf);
//! counts non-zero array elements
CV_EXPORTS int countNonZero(const GpuMat& src);
//! counts non-zero array elements
CV_EXPORTS int countNonZero(const GpuMat& src, GpuMat& buf);
///////////////////////////// Calibration 3D //////////////////////////////////
CV_EXPORTS void transformPoints(const GpuMat& src, const Mat& rvec, const Mat& tvec,
GpuMat& dst, Stream& stream = Stream::Null());
CV_EXPORTS void projectPoints(const GpuMat& src, const Mat& rvec, const Mat& tvec,
const Mat& camera_mat, const Mat& dist_coef, GpuMat& dst,
Stream& stream = Stream::Null());
CV_EXPORTS void solvePnPRansac(const Mat& object, const Mat& image, const Mat& camera_mat,
const Mat& dist_coef, Mat& rvec, Mat& tvec, bool use_extrinsic_guess=false,
int num_iters=100, float max_dist=8.0, int min_inlier_count=100,
vector<int>* inliers=NULL);
//////////////////////////////// Image Labeling ////////////////////////////////
//!performs labeling via graph cuts
CV_EXPORTS void graphcut(GpuMat& terminals, GpuMat& leftTransp, GpuMat& rightTransp, GpuMat& top, GpuMat& bottom, GpuMat& labels, GpuMat& buf, Stream& stream = Stream::Null());
////////////////////////////////// Histograms //////////////////////////////////
//! Compute levels with even distribution. levels will have 1 row and nLevels cols and CV_32SC1 type.
CV_EXPORTS void evenLevels(GpuMat& levels, int nLevels, int lowerLevel, int upperLevel);
//! Calculates histogram with evenly distributed bins for signle channel source.
//! Supports CV_8UC1, CV_16UC1 and CV_16SC1 source types.
//! Output hist will have one row and histSize cols and CV_32SC1 type.
CV_EXPORTS void histEven(const GpuMat& src, GpuMat& hist, int histSize, int lowerLevel, int upperLevel, Stream& stream = Stream::Null());
CV_EXPORTS void histEven(const GpuMat& src, GpuMat& hist, GpuMat& buf, int histSize, int lowerLevel, int upperLevel, Stream& stream = Stream::Null());
//! Calculates histogram with evenly distributed bins for four-channel source.
//! All channels of source are processed separately.
//! Supports CV_8UC4, CV_16UC4 and CV_16SC4 source types.
//! Output hist[i] will have one row and histSize[i] cols and CV_32SC1 type.
CV_EXPORTS void histEven(const GpuMat& src, GpuMat hist[4], int histSize[4], int lowerLevel[4], int upperLevel[4], Stream& stream = Stream::Null());
CV_EXPORTS void histEven(const GpuMat& src, GpuMat hist[4], GpuMat& buf, int histSize[4], int lowerLevel[4], int upperLevel[4], Stream& stream = Stream::Null());
//! Calculates histogram with bins determined by levels array.
//! levels must have one row and CV_32SC1 type if source has integer type or CV_32FC1 otherwise.
//! Supports CV_8UC1, CV_16UC1, CV_16SC1 and CV_32FC1 source types.
//! Output hist will have one row and (levels.cols-1) cols and CV_32SC1 type.
CV_EXPORTS void histRange(const GpuMat& src, GpuMat& hist, const GpuMat& levels, Stream& stream = Stream::Null());
CV_EXPORTS void histRange(const GpuMat& src, GpuMat& hist, const GpuMat& levels, GpuMat& buf, Stream& stream = Stream::Null());
//! Calculates histogram with bins determined by levels array.
//! All levels must have one row and CV_32SC1 type if source has integer type or CV_32FC1 otherwise.
//! All channels of source are processed separately.
//! Supports CV_8UC4, CV_16UC4, CV_16SC4 and CV_32FC4 source types.
//! Output hist[i] will have one row and (levels[i].cols-1) cols and CV_32SC1 type.
CV_EXPORTS void histRange(const GpuMat& src, GpuMat hist[4], const GpuMat levels[4], Stream& stream = Stream::Null());
CV_EXPORTS void histRange(const GpuMat& src, GpuMat hist[4], const GpuMat levels[4], GpuMat& buf, Stream& stream = Stream::Null());
//! Calculates histogram for 8u one channel image
//! Output hist will have one row, 256 cols and CV32SC1 type.
CV_EXPORTS void calcHist(const GpuMat& src, GpuMat& hist, Stream& stream = Stream::Null());
CV_EXPORTS void calcHist(const GpuMat& src, GpuMat& hist, GpuMat& buf, Stream& stream = Stream::Null());
//! normalizes the grayscale image brightness and contrast by normalizing its histogram
CV_EXPORTS void equalizeHist(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null());
CV_EXPORTS void equalizeHist(const GpuMat& src, GpuMat& dst, GpuMat& hist, Stream& stream = Stream::Null());
CV_EXPORTS void equalizeHist(const GpuMat& src, GpuMat& dst, GpuMat& hist, GpuMat& buf, Stream& stream = Stream::Null());
//////////////////////////////// StereoBM_GPU ////////////////////////////////
class CV_EXPORTS StereoBM_GPU
{
public:
enum { BASIC_PRESET = 0, PREFILTER_XSOBEL = 1 };
enum { DEFAULT_NDISP = 64, DEFAULT_WINSZ = 19 };
//! the default constructor
StereoBM_GPU();
//! the full constructor taking the camera-specific preset, number of disparities and the SAD window size. ndisparities must be multiple of 8.
StereoBM_GPU(int preset, int ndisparities = DEFAULT_NDISP, int winSize = DEFAULT_WINSZ);
//! the stereo correspondence operator. Finds the disparity for the specified rectified stereo pair
//! Output disparity has CV_8U type.
void operator() ( const GpuMat& left, const GpuMat& right, GpuMat& disparity, Stream& stream = Stream::Null());
//! Some heuristics that tries to estmate
// if current GPU will be faster than CPU in this algorithm.
// It queries current active device.
static bool checkIfGpuCallReasonable();
int preset;
int ndisp;
int winSize;
// If avergeTexThreshold == 0 => post procesing is disabled
// If avergeTexThreshold != 0 then disparity is set 0 in each point (x,y) where for left image
// SumOfHorizontalGradiensInWindow(x, y, winSize) < (winSize * winSize) * avergeTexThreshold
// i.e. input left image is low textured.
float avergeTexThreshold;
private:
GpuMat minSSD, leBuf, riBuf;
};
////////////////////////// StereoBeliefPropagation ///////////////////////////
// "Efficient Belief Propagation for Early Vision"
// P.Felzenszwalb
class CV_EXPORTS StereoBeliefPropagation
{
public:
enum { DEFAULT_NDISP = 64 };
enum { DEFAULT_ITERS = 5 };
enum { DEFAULT_LEVELS = 5 };
static void estimateRecommendedParams(int width, int height, int& ndisp, int& iters, int& levels);
//! the default constructor
explicit StereoBeliefPropagation(int ndisp = DEFAULT_NDISP,
int iters = DEFAULT_ITERS,
int levels = DEFAULT_LEVELS,
int msg_type = CV_32F);
//! the full constructor taking the number of disparities, number of BP iterations on each level,
//! number of levels, truncation of data cost, data weight,
//! truncation of discontinuity cost and discontinuity single jump
//! DataTerm = data_weight * min(fabs(I2-I1), max_data_term)
//! DiscTerm = min(disc_single_jump * fabs(f1-f2), max_disc_term)
//! please see paper for more details
StereoBeliefPropagation(int ndisp, int iters, int levels,
float max_data_term, float data_weight,
float max_disc_term, float disc_single_jump,
int msg_type = CV_32F);
//! the stereo correspondence operator. Finds the disparity for the specified rectified stereo pair,
//! if disparity is empty output type will be CV_16S else output type will be disparity.type().
void operator()(const GpuMat& left, const GpuMat& right, GpuMat& disparity, Stream& stream = Stream::Null());
//! version for user specified data term
void operator()(const GpuMat& data, GpuMat& disparity, Stream& stream = Stream::Null());
int ndisp;
int iters;
int levels;
float max_data_term;
float data_weight;
float max_disc_term;
float disc_single_jump;
int msg_type;
private:
GpuMat u, d, l, r, u2, d2, l2, r2;
std::vector<GpuMat> datas;
GpuMat out;
};
/////////////////////////// StereoConstantSpaceBP ///////////////////////////
// "A Constant-Space Belief Propagation Algorithm for Stereo Matching"
// Qingxiong Yang, Liang Wang, Narendra Ahuja
// http://vision.ai.uiuc.edu/~qyang6/
class CV_EXPORTS StereoConstantSpaceBP
{
public:
enum { DEFAULT_NDISP = 128 };
enum { DEFAULT_ITERS = 8 };
enum { DEFAULT_LEVELS = 4 };
enum { DEFAULT_NR_PLANE = 4 };
static void estimateRecommendedParams(int width, int height, int& ndisp, int& iters, int& levels, int& nr_plane);
//! the default constructor
explicit StereoConstantSpaceBP(int ndisp = DEFAULT_NDISP,
int iters = DEFAULT_ITERS,
int levels = DEFAULT_LEVELS,
int nr_plane = DEFAULT_NR_PLANE,
int msg_type = CV_32F);
//! the full constructor taking the number of disparities, number of BP iterations on each level,
//! number of levels, number of active disparity on the first level, truncation of data cost, data weight,
//! truncation of discontinuity cost, discontinuity single jump and minimum disparity threshold
StereoConstantSpaceBP(int ndisp, int iters, int levels, int nr_plane,
float max_data_term, float data_weight, float max_disc_term, float disc_single_jump,
int min_disp_th = 0,
int msg_type = CV_32F);
//! the stereo correspondence operator. Finds the disparity for the specified rectified stereo pair,
//! if disparity is empty output type will be CV_16S else output type will be disparity.type().
void operator()(const GpuMat& left, const GpuMat& right, GpuMat& disparity, Stream& stream = Stream::Null());
int ndisp;
int iters;
int levels;
int nr_plane;
float max_data_term;
float data_weight;
float max_disc_term;
float disc_single_jump;
int min_disp_th;
int msg_type;
bool use_local_init_data_cost;
private:
GpuMat u[2], d[2], l[2], r[2];
GpuMat disp_selected_pyr[2];
GpuMat data_cost;
GpuMat data_cost_selected;
GpuMat temp;
GpuMat out;
};
/////////////////////////// DisparityBilateralFilter ///////////////////////////
// Disparity map refinement using joint bilateral filtering given a single color image.
// Qingxiong Yang, Liang Wang, Narendra Ahuja
// http://vision.ai.uiuc.edu/~qyang6/
class CV_EXPORTS DisparityBilateralFilter
{
public:
enum { DEFAULT_NDISP = 64 };
enum { DEFAULT_RADIUS = 3 };
enum { DEFAULT_ITERS = 1 };
//! the default constructor
explicit DisparityBilateralFilter(int ndisp = DEFAULT_NDISP, int radius = DEFAULT_RADIUS, int iters = DEFAULT_ITERS);
//! the full constructor taking the number of disparities, filter radius,
//! number of iterations, truncation of data continuity, truncation of disparity continuity
//! and filter range sigma
DisparityBilateralFilter(int ndisp, int radius, int iters, float edge_threshold, float max_disc_threshold, float sigma_range);
//! the disparity map refinement operator. Refine disparity map using joint bilateral filtering given a single color image.
//! disparity must have CV_8U or CV_16S type, image must have CV_8UC1 or CV_8UC3 type.
void operator()(const GpuMat& disparity, const GpuMat& image, GpuMat& dst, Stream& stream = Stream::Null());
private:
int ndisp;
int radius;
int iters;
float edge_threshold;
float max_disc_threshold;
float sigma_range;
GpuMat table_color;
GpuMat table_space;
};
//////////////// HOG (Histogram-of-Oriented-Gradients) Descriptor and Object Detector //////////////
struct CV_EXPORTS HOGDescriptor
{
enum { DEFAULT_WIN_SIGMA = -1 };
enum { DEFAULT_NLEVELS = 64 };
enum { DESCR_FORMAT_ROW_BY_ROW, DESCR_FORMAT_COL_BY_COL };
HOGDescriptor(Size win_size=Size(64, 128), Size block_size=Size(16, 16),
Size block_stride=Size(8, 8), Size cell_size=Size(8, 8),
int nbins=9, double win_sigma=DEFAULT_WIN_SIGMA,
double threshold_L2hys=0.2, bool gamma_correction=true,
int nlevels=DEFAULT_NLEVELS);
size_t getDescriptorSize() const;
size_t getBlockHistogramSize() const;
void setSVMDetector(const vector<float>& detector);
static vector<float> getDefaultPeopleDetector();
static vector<float> getPeopleDetector48x96();
static vector<float> getPeopleDetector64x128();
void detect(const GpuMat& img, vector<Point>& found_locations,
double hit_threshold=0, Size win_stride=Size(),
Size padding=Size());
void detectMultiScale(const GpuMat& img, vector<Rect>& found_locations,
double hit_threshold=0, Size win_stride=Size(),
Size padding=Size(), double scale0=1.05,
int group_threshold=2);
void getDescriptors(const GpuMat& img, Size win_stride,
GpuMat& descriptors,
int descr_format=DESCR_FORMAT_COL_BY_COL);
Size win_size;
Size block_size;
Size block_stride;
Size cell_size;
int nbins;
double win_sigma;
double threshold_L2hys;
bool gamma_correction;
int nlevels;
protected:
void computeBlockHistograms(const GpuMat& img);
void computeGradient(const GpuMat& img, GpuMat& grad, GpuMat& qangle);
double getWinSigma() const;
bool checkDetectorSize() const;
static int numPartsWithin(int size, int part_size, int stride);
static Size numPartsWithin(Size size, Size part_size, Size stride);
// Coefficients of the separating plane
float free_coef;
GpuMat detector;
// Results of the last classification step
GpuMat labels, labels_buf;
Mat labels_host;
// Results of the last histogram evaluation step
GpuMat block_hists, block_hists_buf;
// Gradients conputation results
GpuMat grad, qangle, grad_buf, qangle_buf;
// returns subbuffer with required size, reallocates buffer if nessesary.
static GpuMat getBuffer(const Size& sz, int type, GpuMat& buf);
static GpuMat getBuffer(int rows, int cols, int type, GpuMat& buf);
std::vector<GpuMat> image_scales;
};
////////////////////////////////// BruteForceMatcher //////////////////////////////////
class CV_EXPORTS BruteForceMatcher_GPU_base
{
public:
enum DistType {L1Dist = 0, L2Dist, HammingDist};
explicit BruteForceMatcher_GPU_base(DistType distType = L2Dist);
// Add descriptors to train descriptor collection.
void add(const std::vector<GpuMat>& descCollection);
// Get train descriptors collection.
const std::vector<GpuMat>& getTrainDescriptors() const;
// Clear train descriptors collection.
void clear();
// Return true if there are not train descriptors in collection.
bool empty() const;
// Return true if the matcher supports mask in match methods.
bool isMaskSupported() const;
// Find one best match for each query descriptor.
// trainIdx.at<int>(0, queryIdx) will contain best train index for queryIdx
// distance.at<float>(0, queryIdx) will contain distance
void matchSingle(const GpuMat& queryDescs, const GpuMat& trainDescs,
GpuMat& trainIdx, GpuMat& distance,
const GpuMat& mask = GpuMat(), Stream& stream = Stream::Null());
// Download trainIdx and distance and convert it to CPU vector with DMatch
static void matchDownload(const GpuMat& trainIdx, const GpuMat& distance, std::vector<DMatch>& matches);
// Convert trainIdx and distance to vector with DMatch
static void matchConvert(const Mat& trainIdx, const Mat& distance, std::vector<DMatch>& matches);
// Find one best match for each query descriptor.
void match(const GpuMat& queryDescs, const GpuMat& trainDescs, std::vector<DMatch>& matches,
const GpuMat& mask = GpuMat());
// Make gpu collection of trains and masks in suitable format for matchCollection function
void makeGpuCollection(GpuMat& trainCollection, GpuMat& maskCollection,
const vector<GpuMat>& masks = std::vector<GpuMat>());
// Find one best match from train collection for each query descriptor.
// trainIdx.at<int>(0, queryIdx) will contain best train index for queryIdx
// imgIdx.at<int>(0, queryIdx) will contain best image index for queryIdx
// distance.at<float>(0, queryIdx) will contain distance
void matchCollection(const GpuMat& queryDescs, const GpuMat& trainCollection,
GpuMat& trainIdx, GpuMat& imgIdx, GpuMat& distance,
const GpuMat& maskCollection, Stream& stream = Stream::Null());
// Download trainIdx, imgIdx and distance and convert it to vector with DMatch
static void matchDownload(const GpuMat& trainIdx, const GpuMat& imgIdx, const GpuMat& distance, std::vector<DMatch>& matches);
// Convert trainIdx, imgIdx and distance to vector with DMatch
static void matchConvert(const Mat& trainIdx, const Mat& imgIdx, const Mat& distance, std::vector<DMatch>& matches);
// Find one best match from train collection for each query descriptor.
void match(const GpuMat& queryDescs, std::vector<DMatch>& matches, const std::vector<GpuMat>& masks = std::vector<GpuMat>());
// Find k best matches for each query descriptor (in increasing order of distances).
// trainIdx.at<int>(queryIdx, i) will contain index of i'th best trains (i < k).
// distance.at<float>(queryIdx, i) will contain distance.
// allDist is a buffer to store all distance between query descriptors and train descriptors
// it have size (nQuery,nTrain) and CV_32F type
// allDist.at<float>(queryIdx, trainIdx) will contain FLT_MAX, if trainIdx is one from k best,
// otherwise it will contain distance between queryIdx and trainIdx descriptors
void knnMatch(const GpuMat& queryDescs, const GpuMat& trainDescs,
GpuMat& trainIdx, GpuMat& distance, GpuMat& allDist, int k, const GpuMat& mask = GpuMat(), Stream& stream = Stream::Null());
// Download trainIdx and distance and convert it to vector with DMatch
// compactResult is used when mask is not empty. If compactResult is false matches
// vector will have the same size as queryDescriptors rows. If compactResult is true
// matches vector will not contain matches for fully masked out query descriptors.
static void knnMatchDownload(const GpuMat& trainIdx, const GpuMat& distance,
std::vector< std::vector<DMatch> >& matches, bool compactResult = false);
// Convert trainIdx and distance to vector with DMatch
static void knnMatchConvert(const Mat& trainIdx, const Mat& distance,
std::vector< std::vector<DMatch> >& matches, bool compactResult = false);
// Find k best matches for each query descriptor (in increasing order of distances).
// compactResult is used when mask is not empty. If compactResult is false matches
// vector will have the same size as queryDescriptors rows. If compactResult is true
// matches vector will not contain matches for fully masked out query descriptors.
void knnMatch(const GpuMat& queryDescs, const GpuMat& trainDescs,
std::vector< std::vector<DMatch> >& matches, int k, const GpuMat& mask = GpuMat(),
bool compactResult = false);
// Find k best matches for each query descriptor (in increasing order of distances).
// compactResult is used when mask is not empty. If compactResult is false matches
// vector will have the same size as queryDescriptors rows. If compactResult is true
// matches vector will not contain matches for fully masked out query descriptors.
void knnMatch(const GpuMat& queryDescs, std::vector< std::vector<DMatch> >& matches, int knn,
const std::vector<GpuMat>& masks = std::vector<GpuMat>(), bool compactResult = false );
// Find best matches for each query descriptor which have distance less than maxDistance.
// nMatches.at<unsigned int>(0, queruIdx) will contain matches count for queryIdx.
// carefully nMatches can be greater than trainIdx.cols - it means that matcher didn't find all matches,
// because it didn't have enough memory.
// trainIdx.at<int>(queruIdx, i) will contain ith train index (i < min(nMatches.at<unsigned int>(0, queruIdx), trainIdx.cols))
// distance.at<int>(queruIdx, i) will contain ith distance (i < min(nMatches.at<unsigned int>(0, queruIdx), trainIdx.cols))
// If trainIdx is empty, then trainIdx and distance will be created with size nQuery x nTrain,
// otherwize user can pass own allocated trainIdx and distance with size nQuery x nMaxMatches
// Matches doesn't sorted.
void radiusMatch(const GpuMat& queryDescs, const GpuMat& trainDescs,
GpuMat& trainIdx, GpuMat& nMatches, GpuMat& distance, float maxDistance,
const GpuMat& mask = GpuMat(), Stream& stream = Stream::Null());
// Download trainIdx, nMatches and distance and convert it to vector with DMatch.
// matches will be sorted in increasing order of distances.
// compactResult is used when mask is not empty. If compactResult is false matches
// vector will have the same size as queryDescriptors rows. If compactResult is true
// matches vector will not contain matches for fully masked out query descriptors.
static void radiusMatchDownload(const GpuMat& trainIdx, const GpuMat& nMatches, const GpuMat& distance,
std::vector< std::vector<DMatch> >& matches, bool compactResult = false);
// Convert trainIdx, nMatches and distance to vector with DMatch.
static void radiusMatchConvert(const Mat& trainIdx, const Mat& nMatches, const Mat& distance,
std::vector< std::vector<DMatch> >& matches, bool compactResult = false);
// Find best matches for each query descriptor which have distance less than maxDistance
// in increasing order of distances).
void radiusMatch(const GpuMat& queryDescs, const GpuMat& trainDescs,
std::vector< std::vector<DMatch> >& matches, float maxDistance,
const GpuMat& mask = GpuMat(), bool compactResult = false);
// Find best matches from train collection for each query descriptor which have distance less than
// maxDistance (in increasing order of distances).
void radiusMatch(const GpuMat& queryDescs, std::vector< std::vector<DMatch> >& matches, float maxDistance,
const std::vector<GpuMat>& masks = std::vector<GpuMat>(), bool compactResult = false);
DistType distType;
private:
std::vector<GpuMat> trainDescCollection;
};
template <class Distance>
class CV_EXPORTS BruteForceMatcher_GPU;
template <typename T>
class CV_EXPORTS BruteForceMatcher_GPU< L1<T> > : public BruteForceMatcher_GPU_base
{
public:
explicit BruteForceMatcher_GPU() : BruteForceMatcher_GPU_base(L1Dist) {}
explicit BruteForceMatcher_GPU(L1<T> /*d*/) : BruteForceMatcher_GPU_base(L1Dist) {}
};
template <typename T>
class CV_EXPORTS BruteForceMatcher_GPU< L2<T> > : public BruteForceMatcher_GPU_base
{
public:
explicit BruteForceMatcher_GPU() : BruteForceMatcher_GPU_base(L2Dist) {}
explicit BruteForceMatcher_GPU(L2<T> /*d*/) : BruteForceMatcher_GPU_base(L2Dist) {}
};
template <> class CV_EXPORTS BruteForceMatcher_GPU< HammingLUT > : public BruteForceMatcher_GPU_base
{
public:
explicit BruteForceMatcher_GPU() : BruteForceMatcher_GPU_base(HammingDist) {}
explicit BruteForceMatcher_GPU(HammingLUT /*d*/) : BruteForceMatcher_GPU_base(HammingDist) {}
};
template <> class CV_EXPORTS BruteForceMatcher_GPU< Hamming > : public BruteForceMatcher_GPU_base
{
public:
explicit BruteForceMatcher_GPU() : BruteForceMatcher_GPU_base(HammingDist) {}
explicit BruteForceMatcher_GPU(Hamming /*d*/) : BruteForceMatcher_GPU_base(HammingDist) {}
};
////////////////////////////////// CascadeClassifier_GPU //////////////////////////////////////////
// The cascade classifier class for object detection.
class CV_EXPORTS CascadeClassifier_GPU
{
public:
CascadeClassifier_GPU();
CascadeClassifier_GPU(const string& filename);
~CascadeClassifier_GPU();
bool empty() const;
bool load(const string& filename);
void release();
/* returns number of detected objects */
int detectMultiScale( const GpuMat& image, GpuMat& objectsBuf, double scaleFactor=1.2, int minNeighbors=4, Size minSize=Size());
bool findLargestObject;
bool visualizeInPlace;
Size getClassifierSize() const;
private:
struct CascadeClassifierImpl;
CascadeClassifierImpl* impl;
};
////////////////////////////////// SURF //////////////////////////////////////////
class CV_EXPORTS SURF_GPU : public CvSURFParams
{
public:
enum KeypointLayout
{
SF_X = 0,
SF_Y,
SF_LAPLACIAN,
SF_SIZE,
SF_DIR,
SF_HESSIAN,
SF_FEATURE_STRIDE
};
//! the default constructor
SURF_GPU();
//! the full constructor taking all the necessary parameters
explicit SURF_GPU(double _hessianThreshold, int _nOctaves=4,
int _nOctaveLayers=2, bool _extended=false, float _keypointsRatio=0.01f, bool _upright = false);
//! returns the descriptor size in float's (64 or 128)
int descriptorSize() const;
//! upload host keypoints to device memory
void uploadKeypoints(const vector<KeyPoint>& keypoints, GpuMat& keypointsGPU);
//! download keypoints from device to host memory
void downloadKeypoints(const GpuMat& keypointsGPU, vector<KeyPoint>& keypoints);
//! download descriptors from device to host memory
void downloadDescriptors(const GpuMat& descriptorsGPU, vector<float>& descriptors);
//! finds the keypoints using fast hessian detector used in SURF
//! supports CV_8UC1 images
//! keypoints will have nFeature cols and 6 rows
//! keypoints.ptr<float>(SF_X)[i] will contain x coordinate of i'th feature
//! keypoints.ptr<float>(SF_Y)[i] will contain y coordinate of i'th feature
//! keypoints.ptr<float>(SF_LAPLACIAN)[i] will contain laplacian sign of i'th feature
//! keypoints.ptr<float>(SF_SIZE)[i] will contain size of i'th feature
//! keypoints.ptr<float>(SF_DIR)[i] will contain orientation of i'th feature
//! keypoints.ptr<float>(SF_HESSIAN)[i] will contain response of i'th feature
void operator()(const GpuMat& img, const GpuMat& mask, GpuMat& keypoints);
//! finds the keypoints and computes their descriptors.
//! Optionally it can compute descriptors for the user-provided keypoints and recompute keypoints direction
void operator()(const GpuMat& img, const GpuMat& mask, GpuMat& keypoints, GpuMat& descriptors,
bool useProvidedKeypoints = false);
void operator()(const GpuMat& img, const GpuMat& mask, std::vector<KeyPoint>& keypoints);
void operator()(const GpuMat& img, const GpuMat& mask, std::vector<KeyPoint>& keypoints, GpuMat& descriptors,
bool useProvidedKeypoints = false);
void operator()(const GpuMat& img, const GpuMat& mask, std::vector<KeyPoint>& keypoints, std::vector<float>& descriptors,
bool useProvidedKeypoints = false);
void releaseMemory();
//! max keypoints = min(keypointsRatio * img.size().area(), 65535)
float keypointsRatio;
GpuMat sum, mask1, maskSum, intBuffer;
GpuMat det, trace;
GpuMat maxPosBuffer;
};
}
//! Speckle filtering - filters small connected components on diparity image.
//! It sets pixel (x,y) to newVal if it coresponds to small CC with size < maxSpeckleSize.
//! Threshold for border between CC is diffThreshold;
CV_EXPORTS void filterSpeckles( Mat& img, uchar newVal, int maxSpeckleSize, uchar diffThreshold, Mat& buf);
}
#include "opencv2/gpu/matrix_operations.hpp"
#endif /* __OPENCV_GPU_HPP__ */
| 78,451 | 23,422 |
/******************************************************************************
*
* @file: discrete_function.hpp
*
* @date: 12/06/2012 01:39:53 PM (CET)
*
* @author: Marco Müller <muelma@gmail.com>
*
******************************************************************************/
#pragma once
#include <vector>
#include <cassert>
#include <iostream>
#include <iomanip> // stream manipulators
#include <sstream> // string streams used for output
#include <limits>
#include <cmath>
#include "dlib/serialize.h"
/// class to manage a functional dependency y = f(x) with automatic
/// discretisation in x
///
/// The naming of the class is as follows:\n
/// x is called the abscissa\n
/// y is called the ordinate\n
/// The interval [abscissa_min, abscissa_max] is divided in a number of
/// nr_bins subintervals of a given length bin_width_ where each subinterval
/// holds exactly one value for the ordinate.\n
/// Subintervals are also referred to as "bins".
template<class T>
class discrete_function {
public:
typedef typename std::vector<T>::iterator iterator;
typedef typename std::vector<T>::reverse_iterator reverse_iterator;
typedef typename std::vector<T>::const_iterator const_iterator;
typedef typename std::vector<T>::const_reverse_iterator const_reverse_iterator;
typedef T value_type;
/// constructor defining
/// interval limits and length of one subinterval
discrete_function(double abscissa_min_, double abscissa_max_, double bin_width_);
// members defining the discretisation:
double abscissa_min; ///< minimum of the interval
double abscissa_max; ///< maximum of the interval
double bin_width; ///< length of a subinterval
size_t nr_bins;
size_t normalization;
// vector storing the ordinates
std::vector<T> data;
/// access by index
T& operator[]( size_t index );
const T& operator[]( size_t index ) const;
/// access by value for the abscissa
T& operator[]( double abscissa_val );
const T& operator[]( double abscissa_val ) const;
/// returns iterator to begin of underlying data
iterator begin() { return data.begin(); }
/// returns const iterator to begin of underlying data
const_iterator begin() const { return data.begin(); }
/// returns const iterator to begin of underlying data
const_iterator cbegin() const { return data.cbegin(); }
/// returns iterator to end of underlying data
iterator end() { return data.end(); }
/// returns const iterator to end of underlying data
const_iterator end() const { return data.end(); }
/// returns const iterator to end of underlying data
const_iterator cend() const { return data.cend(); }
/// returns reverse iterator to begin of underlying data
reverse_iterator rbegin() { return data.rbegin(); }
/// returns const reverse iterator to begin of underlying data
const_reverse_iterator rbegin() const { return data.rbegin(); }
/// returns const reverse iterator to begin of underlying data
const_reverse_iterator crbegin() const { return data.crbegin(); }
/// returns reverse iterator to end of underlying data
reverse_iterator rend() { return data.rend(); }
/// returns const reverse iterator to end of underlying data
const_reverse_iterator rend() const { return data.rend(); }
/// returns const reverse iterator to end of underlying data
const_reverse_iterator crend() const { return data.crend(); }
/// get internal vector storing ordinates
std::vector<T>& get_data() { return data; }
/// get lower limit of the interval
double get_abscissa_min() const { return abscissa_min; }
/// get upper limit of the interval
double get_abscissa_max() const { return abscissa_max; }
/// get size of a subinterval
double get_bin_width() const { return bin_width; }
/// return normalization
size_t get_norm() const { return normalization; }
/// get number of subintervals
size_t size() const;
/// get index for a value of the abscissa
size_t get_index( double abscissa_val ) const;
/// get the abscissa for an index interpolated to be the
/// mean value of the subinterval
double get_abscissa(size_t index) const;
/// get a string representation
std::string to_string() const;
//template<class T2>
//friend std::ostream& operator<<(std::ostream& os, discrete_function<T2>& func);
}; // class discrete_function
// constructor definition
template<class T>
discrete_function<T>
::discrete_function(double abscissa_min_, double abscissa_max_, double bin_width_)
: abscissa_min(abscissa_min_)
, abscissa_max(abscissa_max_)
, bin_width(bin_width_)
, normalization( std::numeric_limits<double>::quiet_NaN() ){
const double diff = abscissa_max - abscissa_min;
// Error:
// either the lower bound of the interval is greater than
// the upper bound or they are equal
assert( diff > 0 && "Error: creating discrete_function failed due to improper definition of the interval.");
nr_bins = static_cast<size_t>( (diff / bin_width) );
abscissa_max = abscissa_min + nr_bins*bin_width;
// Error:
// length of a subinterval is bigger than the length of the
// whole interval
assert( nr_bins > 0 && "Error: discrete_function needs at least one subinterval.");
data.resize(nr_bins);
}
// number of subintervals
template<class T>
size_t discrete_function<T>
::size() const { return nr_bins; }
// access by index
template<class T>
const T& discrete_function<T>
::operator[](size_t index) const {
assert( index < nr_bins );
return data[index];
}
template<class T>
T& discrete_function<T>
::operator[](size_t index) {
assert( index < nr_bins );
return data[index];
}
// access by value
template<class T>
inline const T& discrete_function<T>
::operator[](double abscissa) const {
return data[get_index(abscissa)];
}
template<class T>
inline T& discrete_function<T>
::operator[](double abscissa) {
return data[get_index(abscissa)];
}
template<class T>
inline size_t discrete_function<T>
::get_index( double abscissa_val ) const {
size_t index = 0;
index = static_cast<size_t>((abscissa_val - abscissa_min)/bin_width);
assert( index < nr_bins );
return index;
}
template<class T>
double discrete_function<T>
::get_abscissa(size_t index) const{
double tmp =static_cast<double>(abscissa_min) + static_cast<double>(bin_width) * (index + 0.5);
return tmp;
}
template<class T>
std::string discrete_function<T>
::to_string() const {
std::ostringstream os;
os << "# discrete function:\n"
<< "# abscissa_min = " << std::scientific << std::setprecision(16) << abscissa_min << "\n"
<< "# abscissa_max = " << std::scientific << std::setprecision(16) << abscissa_max << "\n"
<< "# bin_width = " << std::scientific << std::setprecision(16) << bin_width << "\n"
<< "# nr_bins = " << nr_bins << "\n"
<< "# -----\n" << "# Every line represents a right-open subinterval of the abscissa with its ordinate\n"
<< "#" << std::setw(29) << "x_mean" << std::setw(31) << "f[x_min, x_max)\n";
// TODO: how to write type information ... logval vs. double ...
os.setf(std::ios::scientific);
os.precision(16);
for ( size_t i = 0; i < nr_bins; i++ ) {
double mean = this->get_abscissa(i) ;
os << std::setw(30) << mean << " "
<< std::setw(29) << this->operator[](i) << " "
<< "\n";
}
return os.str();
}
template<class T>
std::ostream& operator<<(std::ostream& os, discrete_function<T>& func){
os << func.to_string();
return os;
}
template<class T>
void serialize (const discrete_function<T>& df, std::ostream& out)
{
/*
serialize() just needs to write the state of item to the output stream.
You can do this however you like. Below, I'm using the serialize functions
for int and std::string which come with dlib. But again, you can do whatever
you want here.
*/
dlib::serialize(df.abscissa_min, out);
dlib::serialize(df.abscissa_max, out);
dlib::serialize(df.bin_width, out);
dlib::serialize(df.nr_bins, out);
dlib::serialize(df.normalization, out);
dlib::serialize(df.data, out);
}
template<class T>
void deserialize (discrete_function<T>& df, std::istream& in)
{
/*
deserialize() is just the inverse of serialize(). Again, you can do
whatever you want here so long as it correctly reconstructs item. This
also means that deserialize() must always consume as many bytes as serialize()
generates.
*/
dlib::deserialize(df.abscissa_min, in);
dlib::deserialize(df.abscissa_max, in);
dlib::deserialize(df.bin_width, in);
dlib::deserialize(df.nr_bins, in);
dlib::deserialize(df.normalization, in);
dlib::deserialize(df.data, in);
}
| 8,951 | 2,754 |
#include "Simulation.h"
#include "OrderParameterRegistry.h"
Simulation::Simulation(
const std::string& data_set_label, const double t_min, const double t_max,
const double temperature, const bool use_floored_times,
const OrderParameterRegistry& op_registry
):
data_set_label_(data_set_label),
t_min_(t_min), t_max_(t_max),
temperature_(temperature),
kBT_(Constants::k_B * temperature_), beta_(1.0/kBT_),
use_floored_times_(use_floored_times),
op_registry_ptr_(&op_registry)
{
// Read time series
const auto& time_series_files = op_registry_ptr_->getSimulationFiles(data_set_label);
const int num_ops = time_series_files.size();
time_series_.reserve(num_ops);
for ( int p=0; p<num_ops; ++p ) {
int data_col = op_registry_ptr_->getTimeSeriesDataCol(p);
time_series_.emplace_back( time_series_files[p], data_col, t_min_, t_max_, use_floored_times );
}
checkTimeSeries();
}
const TimeSeries& Simulation::getTimeSeriesForOrderParameter(const std::string& op_name) const {
FANCY_ASSERT(op_registry_ptr_ != nullptr, "order parameter registry is missing");
const int op_index = op_registry_ptr_->nameToIndex(op_name);
return time_series_[op_index];
}
void Simulation::setShuffledFromOther(const Simulation& other, const std::vector<int>& indices)
{
FANCY_ASSERT(this != &other, "unsupported usage");
*this = other;
const int num_time_series = other.time_series_.size();
for ( int p=0; p<num_time_series; ++p ) {
time_series_[p].setShuffledFromOther( other.time_series_[p], indices );
}
}
void Simulation::checkTimeSeries() const
{
FANCY_ASSERT(op_registry_ptr_ != nullptr, "order parameter registry is missing");
// Check number present
const int num_time_series = time_series_.size();
const int num_ops = op_registry_ptr_->getNumRegistered();
FANCY_ASSERT( num_time_series == num_ops,
"Error setting up Simulation with data set label " << data_set_label_ << "\n"
<< " Mismatch between number of time series files parsed (" << num_time_series
<< ") and number of order parameters (" << num_ops << "\n" );
if ( num_time_series == 0 ) {
return; // nothing to do
}
const auto& time_series_ref = time_series_.front();
for ( int p=1; p<num_time_series; ++p ) {
// Check sampled times
const auto& time_series_p = time_series_[p];
if ( time_series_p.get_times() != time_series_ref.get_times() ) {
std::stringstream err_ss;
err_ss << "Error setting up Simulation with data set label " << data_set_label_ << "\n"
<< " Mismatch in times sampled for the following order parameters\n";
std::vector<int> op_indices = {{ 0, p }};
for ( auto j : op_indices ) {
const auto& time_series_j = time_series_[j];
err_ss << " " << op_registry_ptr_->indexToName(j) << ": " << time_series_j.size() << " points from file "
<< time_series_j.getFile() << "\n";
}
throw std::runtime_error( err_ss.str() );
}
}
}
| 2,922 | 1,093 |
/*
MIT License
Copyright (c) 2019 Bart Bilos
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 <command_mini.h>
#include <stddef.h>
#include <board.hpp>
#include <chip.h>
#include <stream_uart.hpp>
#include <strings.hpp>
#include <parsedigit.h>
#include <string.h>
#include <print.h>
result cmdPrintVerHandler(const char *argument);
result cmdSpiTestHandler(const char *argument);
result cmdSwdEnableHandler(const char *argument);
result cmdSwdDisableHandler(const char *argument);
result cmdGeneralTestHandler(const char *argument);
const char cmdPrintVer[] = "pv";
const char cmdSpiTest[] = "ts";
const char cmdSwdEnable[] = "swde";
const char cmdSwdDisable[] = "swdd";
const char cmdGeneralTest[] = "test";
commandEntry_t sqProgCommands[] =
{
{cmdPrintVer, cmdPrintVerHandler},
{cmdSpiTest, cmdSpiTestHandler},
{cmdSwdEnable, cmdSwdEnableHandler},
{cmdSwdDisable, cmdSwdDisableHandler},
{cmdGeneralTest, cmdGeneralTestHandler},
{NULL, NULL},
};
// commands may not use an argument and this is fine, ignore warning
#pragma GCC diagnostic ignored "-Wunused-parameter"
result cmdPrintVerHandler(const char *argument)
{
dsPuts(&streamUart, strHello);
return noError;
}
result cmdGeneralTestHandler(const char *argument)
{
Chip_GPIO_SetPinDIROutput(LPC_GPIO_PORT, 0, JTAG_TCK_GPIO);
Chip_GPIO_SetPinToggle(LPC_GPIO_PORT, 0, JTAG_TCK_GPIO);
}
// now we want warnings on arguments missing again
#pragma GCC diagnostic pop
result cmdSpiTestHandler(const char *argument)
{
const char *s = argument;
unsigned int bitCount;
if(parseDigit(*s, &bitCount) != parseOk)
return invalidArg;
s++;
// we know bit count, now check rest
unsigned int charCount = (bitCount / 4 + 1);
if(strlen(s) != charCount)
return invalidArg;
// we increment bit count so we cover a range from 1 to 16
bitCount++;
// parse data characters
uint16_t spiData = 0;
for(unsigned int i = 0; i < charCount; i++)
{
spiData = spiData << 4;
unsigned int data;
if(parseDigit(*s, &data) != parseOk)
return invalidArg;
s++;
spiData = spiData | (uint16_t) data;
}
// transfer
uint32_t transfer = spiData |
(0xE << 16) |
SPI_TXDATCTL_EOT |
SPI_TXDATCTL_FLEN(bitCount-1);
Chip_SPI_ClearStatus(LPC_SPI0, SPI_STAT_CLR_RXOV | SPI_STAT_CLR_TXUR | SPI_STAT_CLR_SSA | SPI_STAT_CLR_SSD);
while( !(Chip_SPI_GetStatus(LPC_SPI0) & SPI_STAT_TXRDY))
;
LPC_SPI0->TXDATCTL = transfer;
while( !(Chip_SPI_GetStatus(LPC_SPI0) & SPI_STAT_RXRDY))
;
uint16_t rxData = (uint16_t) LPC_SPI0->RXDAT & 0xFFFF;
printHexU32(&streamUart, rxData);
dsPuts(&streamUart, strNl);
// print result
return noError;
}
result cmdSwdEnableHandler(const char *argument)
{
// check if we have valid divisor number, max 4 hex digits
size_t arglen = strlen(argument);
if((arglen == 0) || (arglen > 4))
return invalidArg;
uint16_t divisor = 0;
for(unsigned int i = 0; i < arglen; i++)
{
divisor = divisor << 4;
unsigned int data;
if(parseDigit(*argument, &data) != parseOk)
return invalidArg;
argument++;
divisor = divisor | (uint16_t) data;
}
Chip_Clock_EnablePeriphClock(SYSCTL_CLOCK_SWM);
Chip_SWM_MovablePinAssign(SWM_SPI0_SCK_IO, JTAG_TCK_GPIO);
Chip_SWM_MovablePinAssign(SWM_SPI0_MISO_IO, JTAG_TMSI_GPIO);
Chip_SWM_MovablePinAssign(SWM_SPI0_MOSI_IO, JTAG_TMSO_GPIO);
Chip_SWM_MovablePinAssign(SWM_SPI0_SSEL0_IO, JTAG_TMSOE_GPIO);
Chip_Clock_DisablePeriphClock(SYSCTL_CLOCK_SWM);
Chip_Clock_EnablePeriphClock(SYSCTL_CLOCK_SPI0);
Chip_SYSCTL_PeriphReset(RESET_SPI0);
Chip_SPI_ConfigureSPI(LPC_SPI0, SPI_CFG_MASTER_EN |
SPI_CLOCK_CPHA0_CPOL0 |
SPI_CFG_MSB_FIRST_EN |
SPI_CFG_SPOL_LO);
LPC_SPI0->DLY = 0x0;
LPC_SPI0->DIV = SPI_DIV_VAL(divisor);
Chip_SPI_Enable(LPC_SPI0);
return noError;
}
result cmdSwdDisableHandler(const char *argument)
{
Chip_Clock_DisablePeriphClock(SYSCTL_CLOCK_SPI0);
// reset SPI core
return noError;
} | 5,246 | 2,007 |
/*
* Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
* Copyright (C) 2007 Nicholas Shanks <webkit@nickshanks.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "platform/fonts/FontCache.h"
#include "base/trace_event/process_memory_dump.h"
#include "platform/FontFamilyNames.h"
#include "platform/Histogram.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/fonts/AcceptLanguagesResolver.h"
#include "platform/fonts/AlternateFontFamily.h"
#include "platform/fonts/FontCacheClient.h"
#include "platform/fonts/FontCacheKey.h"
#include "platform/fonts/FontDataCache.h"
#include "platform/fonts/FontDescription.h"
#include "platform/fonts/FontPlatformData.h"
#include "platform/fonts/FontSmoothingMode.h"
#include "platform/fonts/SimpleFontData.h"
#include "platform/fonts/TextRenderingMode.h"
#include "platform/fonts/opentype/OpenTypeVerticalData.h"
#include "platform/fonts/shaping/ShapeCache.h"
#include "platform/instrumentation/tracing/web_memory_allocator_dump.h"
#include "platform/instrumentation/tracing/web_process_memory_dump.h"
#include "public/platform/Platform.h"
#include "ui/gfx/font_list.h"
#include "wtf/HashMap.h"
#include "wtf/ListHashSet.h"
#include "wtf/PtrUtil.h"
#include "wtf/StdLibExtras.h"
#include "wtf/Vector.h"
#include "wtf/text/AtomicStringHash.h"
#include "wtf/text/StringHash.h"
#include <memory>
using namespace WTF;
namespace blink {
#if !OS(WIN) && !OS(LINUX)
FontCache::FontCache() : m_purgePreventCount(0), m_fontManager(nullptr) {}
#endif // !OS(WIN) && !OS(LINUX)
typedef HashMap<unsigned,
std::unique_ptr<FontPlatformData>,
WTF::IntHash<unsigned>,
WTF::UnsignedWithZeroKeyHashTraits<unsigned>>
SizedFontPlatformDataSet;
typedef HashMap<FontCacheKey,
SizedFontPlatformDataSet,
FontCacheKeyHash,
FontCacheKeyTraits>
FontPlatformDataCache;
typedef HashMap<FallbackListCompositeKey,
std::unique_ptr<ShapeCache>,
FallbackListCompositeKeyHash,
FallbackListCompositeKeyTraits>
FallbackListShaperCache;
static FontPlatformDataCache* gFontPlatformDataCache = nullptr;
static FallbackListShaperCache* gFallbackListShaperCache = nullptr;
SkFontMgr* FontCache::s_staticFontManager = nullptr;
#if OS(WIN)
bool FontCache::s_antialiasedTextEnabled = false;
bool FontCache::s_lcdTextEnabled = false;
float FontCache::s_deviceScaleFactor = 1.0;
bool FontCache::s_useSkiaFontFallback = false;
#endif // OS(WIN)
FontCache* FontCache::fontCache() {
DEFINE_STATIC_LOCAL(FontCache, globalFontCache, ());
return &globalFontCache;
}
#if !OS(MACOSX)
FontPlatformData* FontCache::systemFontPlatformData(
const FontDescription& fontDescription) {
const AtomicString& family = FontCache::systemFontFamily();
#if OS(LINUX)
if (family.isEmpty() || family == FontFamilyNames::system_ui)
return nullptr;
#else
DCHECK(!family.isEmpty() && family != FontFamilyNames::system_ui);
#endif
return getFontPlatformData(fontDescription, FontFaceCreationParams(family),
true);
}
#endif
FontPlatformData* FontCache::getFontPlatformData(
const FontDescription& fontDescription,
const FontFaceCreationParams& creationParams,
bool checkingAlternateName) {
if (!gFontPlatformDataCache) {
gFontPlatformDataCache = new FontPlatformDataCache;
platformInit();
}
#if !OS(MACOSX)
if (creationParams.creationType() == CreateFontByFamily &&
creationParams.family() == FontFamilyNames::system_ui) {
return systemFontPlatformData(fontDescription);
}
#endif
float size = fontDescription.effectiveFontSize();
unsigned roundedSize = size * FontCacheKey::precisionMultiplier();
FontCacheKey key = fontDescription.cacheKey(creationParams);
// Remove the font size from the cache key, and handle the font size
// separately in the inner HashMap. So that different size of FontPlatformData
// can share underlying SkTypeface.
if (RuntimeEnabledFeatures::fontCacheScalingEnabled())
key.clearFontSize();
FontPlatformData* result;
bool foundResult;
{
// addResult's scope must end before we recurse for alternate family names
// below, to avoid trigering its dtor hash-changed asserts.
SizedFontPlatformDataSet* sizedFonts =
&gFontPlatformDataCache->add(key, SizedFontPlatformDataSet())
.storedValue->value;
bool wasEmpty = sizedFonts->isEmpty();
// Take a different size instance of the same font before adding an entry to
// |sizedFont|.
FontPlatformData* anotherSize =
wasEmpty ? nullptr : sizedFonts->begin()->value.get();
auto addResult = sizedFonts->add(roundedSize, nullptr);
std::unique_ptr<FontPlatformData>* found = &addResult.storedValue->value;
if (addResult.isNewEntry) {
if (wasEmpty)
*found = createFontPlatformData(fontDescription, creationParams, size);
else if (anotherSize)
*found = scaleFontPlatformData(*anotherSize, fontDescription,
creationParams, size);
}
result = found->get();
foundResult = result || !addResult.isNewEntry;
}
if (!foundResult && !checkingAlternateName &&
creationParams.creationType() == CreateFontByFamily) {
// We were unable to find a font. We have a small set of fonts that we alias
// to other names, e.g., Arial/Helvetica, Courier/Courier New, etc. Try
// looking up the font under the aliased name.
const AtomicString& alternateName =
alternateFamilyName(creationParams.family());
if (!alternateName.isEmpty()) {
FontFaceCreationParams createByAlternateFamily(alternateName);
result =
getFontPlatformData(fontDescription, createByAlternateFamily, true);
}
if (result) {
// Cache the result under the old name.
auto adding =
&gFontPlatformDataCache->add(key, SizedFontPlatformDataSet())
.storedValue->value;
adding->set(roundedSize, WTF::wrapUnique(new FontPlatformData(*result)));
}
}
return result;
}
std::unique_ptr<FontPlatformData> FontCache::scaleFontPlatformData(
const FontPlatformData& fontPlatformData,
const FontDescription& fontDescription,
const FontFaceCreationParams& creationParams,
float fontSize) {
#if OS(MACOSX)
return createFontPlatformData(fontDescription, creationParams, fontSize);
#else
return WTF::makeUnique<FontPlatformData>(fontPlatformData, fontSize);
#endif
}
ShapeCache* FontCache::getShapeCache(const FallbackListCompositeKey& key) {
if (!gFallbackListShaperCache)
gFallbackListShaperCache = new FallbackListShaperCache;
FallbackListShaperCache::iterator it = gFallbackListShaperCache->find(key);
ShapeCache* result = nullptr;
if (it == gFallbackListShaperCache->end()) {
result = new ShapeCache();
gFallbackListShaperCache->set(key, WTF::wrapUnique(result));
} else {
result = it->value.get();
}
ASSERT(result);
return result;
}
typedef HashMap<FontCache::FontFileKey,
RefPtr<OpenTypeVerticalData>,
IntHash<FontCache::FontFileKey>,
UnsignedWithZeroKeyHashTraits<FontCache::FontFileKey>>
FontVerticalDataCache;
FontVerticalDataCache& fontVerticalDataCacheInstance() {
DEFINE_STATIC_LOCAL(FontVerticalDataCache, fontVerticalDataCache, ());
return fontVerticalDataCache;
}
void FontCache::setFontManager(sk_sp<SkFontMgr> fontManager) {
DCHECK(!s_staticFontManager);
s_staticFontManager = fontManager.release();
}
PassRefPtr<OpenTypeVerticalData> FontCache::getVerticalData(
const FontFileKey& key,
const FontPlatformData& platformData) {
FontVerticalDataCache& fontVerticalDataCache =
fontVerticalDataCacheInstance();
FontVerticalDataCache::iterator result = fontVerticalDataCache.find(key);
if (result != fontVerticalDataCache.end())
return result.get()->value;
RefPtr<OpenTypeVerticalData> verticalData =
OpenTypeVerticalData::create(platformData);
if (!verticalData->isOpenType())
verticalData.clear();
fontVerticalDataCache.set(key, verticalData);
return verticalData;
}
void FontCache::acceptLanguagesChanged(const String& acceptLanguages) {
AcceptLanguagesResolver::acceptLanguagesChanged(acceptLanguages);
fontCache()->invalidateShapeCache();
}
static FontDataCache* gFontDataCache = 0;
PassRefPtr<SimpleFontData> FontCache::getFontData(
const FontDescription& fontDescription,
const AtomicString& family,
bool checkingAlternateName,
ShouldRetain shouldRetain) {
if (FontPlatformData* platformData = getFontPlatformData(
fontDescription, FontFaceCreationParams(
adjustFamilyNameToAvoidUnsupportedFonts(family)),
checkingAlternateName)) {
return fontDataFromFontPlatformData(
platformData, shouldRetain, fontDescription.subpixelAscentDescent());
}
return nullptr;
}
PassRefPtr<SimpleFontData> FontCache::fontDataFromFontPlatformData(
const FontPlatformData* platformData,
ShouldRetain shouldRetain,
bool subpixelAscentDescent) {
if (!gFontDataCache)
gFontDataCache = new FontDataCache;
#if DCHECK_IS_ON()
if (shouldRetain == DoNotRetain)
ASSERT(m_purgePreventCount);
#endif
return gFontDataCache->get(platformData, shouldRetain, subpixelAscentDescent);
}
bool FontCache::isPlatformFontAvailable(const FontDescription& fontDescription,
const AtomicString& family) {
bool checkingAlternateName = true;
return getFontPlatformData(
fontDescription,
FontFaceCreationParams(adjustFamilyNameToAvoidUnsupportedFonts(family)),
checkingAlternateName);
}
String FontCache::firstAvailableOrFirst(const String& families) {
// The conversions involve at least two string copies, and more if non-ASCII.
// For now we prefer shared code over the cost because a) inputs are
// only from grd/xtb and all ASCII, and b) at most only a few times per
// setting change/script.
return String::fromUTF8(
gfx::FontList::FirstAvailableOrFirst(families.utf8().data()).c_str());
}
SimpleFontData* FontCache::getNonRetainedLastResortFallbackFont(
const FontDescription& fontDescription) {
return getLastResortFallbackFont(fontDescription, DoNotRetain).leakRef();
}
void FontCache::releaseFontData(const SimpleFontData* fontData) {
ASSERT(gFontDataCache);
gFontDataCache->release(fontData);
}
static inline void purgePlatformFontDataCache() {
if (!gFontPlatformDataCache)
return;
Vector<FontCacheKey> keysToRemove;
keysToRemove.reserveInitialCapacity(gFontPlatformDataCache->size());
for (auto& sizedFonts : *gFontPlatformDataCache) {
Vector<unsigned> sizesToRemove;
sizesToRemove.reserveInitialCapacity(sizedFonts.value.size());
for (const auto& platformData : sizedFonts.value) {
if (platformData.value &&
!gFontDataCache->contains(platformData.value.get()))
sizesToRemove.push_back(platformData.key);
}
sizedFonts.value.removeAll(sizesToRemove);
if (sizedFonts.value.isEmpty())
keysToRemove.push_back(sizedFonts.key);
}
gFontPlatformDataCache->removeAll(keysToRemove);
}
static inline void purgeFontVerticalDataCache() {
FontVerticalDataCache& fontVerticalDataCache =
fontVerticalDataCacheInstance();
if (!fontVerticalDataCache.isEmpty()) {
// Mark & sweep unused verticalData
FontVerticalDataCache::iterator verticalDataEnd =
fontVerticalDataCache.end();
for (FontVerticalDataCache::iterator verticalData =
fontVerticalDataCache.begin();
verticalData != verticalDataEnd; ++verticalData) {
if (verticalData->value)
verticalData->value->setInFontCache(false);
}
gFontDataCache->markAllVerticalData();
Vector<FontCache::FontFileKey> keysToRemove;
keysToRemove.reserveInitialCapacity(fontVerticalDataCache.size());
for (FontVerticalDataCache::iterator verticalData =
fontVerticalDataCache.begin();
verticalData != verticalDataEnd; ++verticalData) {
if (!verticalData->value || !verticalData->value->inFontCache())
keysToRemove.push_back(verticalData->key);
}
fontVerticalDataCache.removeAll(keysToRemove);
}
}
static inline void purgeFallbackListShaperCache() {
unsigned items = 0;
if (gFallbackListShaperCache) {
FallbackListShaperCache::iterator iter;
for (iter = gFallbackListShaperCache->begin();
iter != gFallbackListShaperCache->end(); ++iter) {
items += iter->value->size();
}
gFallbackListShaperCache->clear();
}
DEFINE_STATIC_LOCAL(CustomCountHistogram, shapeCacheHistogram,
("Blink.Fonts.ShapeCache", 1, 1000000, 50));
shapeCacheHistogram.count(items);
}
void FontCache::invalidateShapeCache() {
purgeFallbackListShaperCache();
}
void FontCache::purge(PurgeSeverity PurgeSeverity) {
// Ideally we should never be forcing the purge while the
// FontCachePurgePreventer is in scope, but we call purge() at any timing
// via MemoryCoordinator.
if (m_purgePreventCount)
return;
if (!gFontDataCache || !gFontDataCache->purge(PurgeSeverity))
return;
purgePlatformFontDataCache();
purgeFontVerticalDataCache();
purgeFallbackListShaperCache();
}
static bool invalidateFontCache = false;
HeapHashSet<WeakMember<FontCacheClient>>& fontCacheClients() {
DEFINE_STATIC_LOCAL(HeapHashSet<WeakMember<FontCacheClient>>, clients,
(new HeapHashSet<WeakMember<FontCacheClient>>));
invalidateFontCache = true;
return clients;
}
void FontCache::addClient(FontCacheClient* client) {
ASSERT(!fontCacheClients().contains(client));
fontCacheClients().add(client);
}
static unsigned short gGeneration = 0;
unsigned short FontCache::generation() {
return gGeneration;
}
void FontCache::invalidate() {
if (!invalidateFontCache) {
ASSERT(!gFontPlatformDataCache);
return;
}
if (gFontPlatformDataCache) {
delete gFontPlatformDataCache;
gFontPlatformDataCache = new FontPlatformDataCache;
}
gGeneration++;
HeapVector<Member<FontCacheClient>> clients;
size_t numClients = fontCacheClients().size();
clients.reserveInitialCapacity(numClients);
HeapHashSet<WeakMember<FontCacheClient>>::iterator end =
fontCacheClients().end();
for (HeapHashSet<WeakMember<FontCacheClient>>::iterator it =
fontCacheClients().begin();
it != end; ++it)
clients.push_back(*it);
ASSERT(numClients == clients.size());
for (size_t i = 0; i < numClients; ++i)
clients[i]->fontCacheInvalidated();
purge(ForcePurge);
}
void FontCache::dumpFontPlatformDataCache(
base::trace_event::ProcessMemoryDump* memoryDump) {
ASSERT(isMainThread());
if (!gFontPlatformDataCache)
return;
base::trace_event::MemoryAllocatorDump* dump =
memoryDump->CreateAllocatorDump("font_caches/font_platform_data_cache");
size_t fontPlatformDataObjectsSize =
gFontPlatformDataCache->size() * sizeof(FontPlatformData);
dump->AddScalar("size", "bytes", fontPlatformDataObjectsSize);
memoryDump->AddSuballocation(dump->guid(),
WTF::Partitions::kAllocatedObjectPoolName);
}
void FontCache::dumpShapeResultCache(
base::trace_event::ProcessMemoryDump* memoryDump) {
ASSERT(isMainThread());
if (!gFallbackListShaperCache) {
return;
}
base::trace_event::MemoryAllocatorDump* dump =
memoryDump->CreateAllocatorDump("font_caches/shape_caches");
size_t shapeResultCacheSize = 0;
FallbackListShaperCache::iterator iter;
for (iter = gFallbackListShaperCache->begin();
iter != gFallbackListShaperCache->end(); ++iter) {
shapeResultCacheSize += iter->value->byteSize();
}
dump->AddScalar("size", "bytes", shapeResultCacheSize);
memoryDump->AddSuballocation(dump->guid(),
WTF::Partitions::kAllocatedObjectPoolName);
}
} // namespace blink
| 17,471 | 5,394 |
#include <gtest/gtest.h>
#include <math.h>
#include <string>
#include <src/autodiff/base_functor.hpp>
#include <src/scalar/functions.hpp>
#include <src/scalar/operators.hpp>
#include <src/test/io_validation.hpp>
#include <src/test/finite_difference.hpp>
template <typename T>
class operator_unary_not_eval_func: public nomad::base_functor<T> {
public:
T operator()(const Eigen::VectorXd& x) const {
T v = nomad::tests::construct_unsafe_var<T>(x[0]);
if (!v)
return -v;
else
return v;
}
static std::string name() { return "operator_unary_not"; }
};
TEST(ScalarNonSmoothOperators, OperatorUnaryNot) {
nomad::eigen_idx_t d = 1;
Eigen::VectorXd x(d);
x[0] = 1.5;
nomad::tests::test_validation<operator_unary_not_eval_func>(x);
}
| 776 | 314 |
/*
LICENSE: BEGIN
===============================================================================
@author Shan Anand
@email anand.gs@gmail.com
@source https://github.com/shan-anand
@brief HTTP library implementation in C++
===============================================================================
MIT License
Copyright (c) 2017 Shanmuga (Anand) Gunasekaran
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.
===============================================================================
LICENSE: END
*/
/**
* @file request.hpp
* @brief Defines the HTTP request object.
*/
#ifndef _SID_HTTP_REQUEST_H_
#define _SID_HTTP_REQUEST_H_
#include "method.hpp"
#include "version.hpp"
#include "headers.hpp"
#include "content.hpp"
#include "connection.hpp"
#include <string>
namespace sid {
namespace http {
/**
* @class request
* @brief Definition of HTTP request object.
*/
class request
{
public:
//! Default constructor
request();
//! Copy constructor
request(const request&) = default;
//! Virtual destructor
virtual ~request();
//! Copy operator
request& operator=(const request&) = default;
/**
* @fn void clear();
* @brief Clear the object so that it can be reused again
*/
void clear();
/**
* @fn void set(const std::string& _input);
* @brief Set the contents of the object using the complete HTTP request string.
* If there is an error a sid::exception is thrown.
*/
void set(const std::string& _input);
/**
* @fn std::string to_str() const;
* @brief Return the complete HTTP request as a string.
*/
std::string to_str() const;
std::string to_str(bool _withContent) const;
/**
* @fn void set_content(const std::string& data, size_t len);
* @brief Sets the payload of the request
*
* @param data Payload
* @param len if std::string::npos it takes the whole string, otherwise it restricts the length.
*
* @note This also sets the "Content-Length" field in the headers.
*/
void set_content(const std::string& _data, size_t _len = std::string::npos);
/**
* @fn const http::content& content() const;
* @brief Gets the payload of the request.
*/
const http::content& content() const { return m_content; }
http::content& content() { return m_content; }
bool send(connection_ptr _conn);
bool send(connection_ptr _conn, const std::string& _data);
bool send(connection_ptr _conn, const void* _buffer, size_t _count);
bool recv(connection_ptr _conn);
private:
http::content m_content; //! HTTP request payload
public:
http::method method; //! HTTP method in Line-1 of request
std::string uri; //! resource identifier in Line-1 of request
http::version version; //! HTTP version
http::headers headers; //! List of request headers
std::string userName; //! Username for challenge authentication (used in www_authenticate)
std::string password; //! Password for challenge authentication
bool content_is_file_path;
std::string error;
};
} // namespace http
} // namespace sid
#endif // _SID_HTTP_REQUEST_H_
| 4,080 | 1,242 |
/*
* Copyright © 2012 Google, Inc.
*
* This is part of HarfBuzz, a text shaping library.
*
* Permission is hereby granted, without written agreement and without
* license or royalty fees, to use, copy, modify, and distribute this
* software and its documentation for any purpose, provided that the
* above copyright notice and the following two paragraphs appear in
* all copies of this software.
*
* IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
* IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
* PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*
* Google Author(s): Behdad Esfahbod
*/
#include "hb-set.hh"
/**
* SECTION:hb-set
* @title: hb-set
* @short_description: Objects representing a set of integers
* @include: hb.h
*
* Set objects represent a mathematical set of integer values. They are
* used in non-shaping APIs to query certain sets of characters or glyphs,
* or other integer values.
**/
/**
* hb_set_create: (Xconstructor)
*
* Creates a new, initially empty set.
*
* Return value: (transfer full): The new #hb_set_t
*
* Since: 0.9.2
**/
hb_set_t *
hb_set_create ()
{
hb_set_t *set;
if (!(set = hb_object_create<hb_set_t> ()))
return hb_set_get_empty ();
set->init_shallow ();
return set;
}
/**
* hb_set_get_empty:
*
* Fetches the singleton empty #hb_set_t.
*
* Return value: (transfer full): The empty #hb_set_t
*
* Since: 0.9.2
**/
hb_set_t *
hb_set_get_empty ()
{
return const_cast<hb_set_t *> (&Null (hb_set_t));
}
/**
* hb_set_reference: (skip)
* @set: A set
*
* Increases the reference count on a set.
*
* Return value: (transfer full): The set
*
* Since: 0.9.2
**/
hb_set_t *
hb_set_reference (hb_set_t *set)
{
return hb_object_reference (set);
}
/**
* hb_set_destroy: (skip)
* @set: A set
*
* Decreases the reference count on a set. When
* the reference count reaches zero, the set is
* destroyed, freeing all memory.
*
* Since: 0.9.2
**/
void
hb_set_destroy (hb_set_t *set)
{
if (!hb_object_destroy (set)) return;
set->fini_shallow ();
hb_free (set);
}
/**
* hb_set_set_user_data: (skip)
* @set: A set
* @key: The user-data key to set
* @data: A pointer to the user data to set
* @destroy: (nullable): A callback to call when @data is not needed anymore
* @replace: Whether to replace an existing data with the same key
*
* Attaches a user-data key/data pair to the specified set.
*
* Return value: %true if success, %false otherwise
*
* Since: 0.9.2
**/
hb_bool_t
hb_set_set_user_data (hb_set_t *set,
hb_user_data_key_t *key,
void * data,
hb_destroy_func_t destroy,
hb_bool_t replace)
{
return hb_object_set_user_data (set, key, data, destroy, replace);
}
/**
* hb_set_get_user_data: (skip)
* @set: A set
* @key: The user-data key to query
*
* Fetches the user data associated with the specified key,
* attached to the specified set.
*
* Return value: (transfer none): A pointer to the user data
*
* Since: 0.9.2
**/
void *
hb_set_get_user_data (hb_set_t *set,
hb_user_data_key_t *key)
{
return hb_object_get_user_data (set, key);
}
/**
* hb_set_allocation_successful:
* @set: A set
*
* Tests whether memory allocation for a set was successful.
*
* Return value: %true if allocation succeeded, %false otherwise
*
* Since: 0.9.2
**/
hb_bool_t
hb_set_allocation_successful (const hb_set_t *set)
{
return set->successful;
}
/**
* hb_set_copy:
* @set: A set
*
* Allocate a copy of @set.
*
* Return value: Newly-allocated set.
*
* Since: 2.8.2
**/
hb_set_t *
hb_set_copy (const hb_set_t *set)
{
hb_set_t *copy = hb_set_create ();
copy->set (*set);
return copy;
}
/**
* hb_set_clear:
* @set: A set
*
* Clears out the contents of a set.
*
* Since: 0.9.2
**/
void
hb_set_clear (hb_set_t *set)
{
if (unlikely (hb_object_is_immutable (set)))
return;
set->clear ();
}
/**
* hb_set_is_empty:
* @set: a set.
*
* Tests whether a set is empty (contains no elements).
*
* Return value: %true if @set is empty
*
* Since: 0.9.7
**/
hb_bool_t
hb_set_is_empty (const hb_set_t *set)
{
return set->is_empty ();
}
/**
* hb_set_has:
* @set: A set
* @codepoint: The element to query
*
* Tests whether @codepoint belongs to @set.
*
* Return value: %true if @codepoint is in @set, %false otherwise
*
* Since: 0.9.2
**/
hb_bool_t
hb_set_has (const hb_set_t *set,
hb_codepoint_t codepoint)
{
return set->has (codepoint);
}
/**
* hb_set_add:
* @set: A set
* @codepoint: The element to add to @set
*
* Adds @codepoint to @set.
*
* Since: 0.9.2
**/
void
hb_set_add (hb_set_t *set,
hb_codepoint_t codepoint)
{
set->add (codepoint);
}
/**
* hb_set_add_range:
* @set: A set
* @first: The first element to add to @set
* @last: The final element to add to @set
*
* Adds all of the elements from @first to @last
* (inclusive) to @set.
*
* Since: 0.9.7
**/
void
hb_set_add_range (hb_set_t *set,
hb_codepoint_t first,
hb_codepoint_t last)
{
set->add_range (first, last);
}
/**
* hb_set_del:
* @set: A set
* @codepoint: Removes @codepoint from @set
*
* Removes @codepoint from @set.
*
* Since: 0.9.2
**/
void
hb_set_del (hb_set_t *set,
hb_codepoint_t codepoint)
{
set->del (codepoint);
}
/**
* hb_set_del_range:
* @set: A set
* @first: The first element to remove from @set
* @last: The final element to remove from @set
*
* Removes all of the elements from @first to @last
* (inclusive) from @set.
*
* Since: 0.9.7
**/
void
hb_set_del_range (hb_set_t *set,
hb_codepoint_t first,
hb_codepoint_t last)
{
set->del_range (first, last);
}
/**
* hb_set_is_equal:
* @set: A set
* @other: Another set
*
* Tests whether @set and @other are equal (contain the same
* elements).
*
* Return value: %true if the two sets are equal, %false otherwise.
*
* Since: 0.9.7
**/
hb_bool_t
hb_set_is_equal (const hb_set_t *set,
const hb_set_t *other)
{
return set->is_equal (*other);
}
/**
* hb_set_is_subset:
* @set: A set
* @larger_set: Another set
*
* Tests whether @set is a subset of @larger_set.
*
* Return value: %true if the @set is a subset of (or equal to) @larger_set, %false otherwise.
*
* Since: 1.8.1
**/
hb_bool_t
hb_set_is_subset (const hb_set_t *set,
const hb_set_t *larger_set)
{
return set->is_subset (*larger_set);
}
/**
* hb_set_set:
* @set: A set
* @other: Another set
*
* Makes the contents of @set equal to the contents of @other.
*
* Since: 0.9.2
**/
void
hb_set_set (hb_set_t *set,
const hb_set_t *other)
{
set->set (*other);
}
/**
* hb_set_union:
* @set: A set
* @other: Another set
*
* Makes @set the union of @set and @other.
*
* Since: 0.9.2
**/
void
hb_set_union (hb_set_t *set,
const hb_set_t *other)
{
set->union_ (*other);
}
/**
* hb_set_intersect:
* @set: A set
* @other: Another set
*
* Makes @set the intersection of @set and @other.
*
* Since: 0.9.2
**/
void
hb_set_intersect (hb_set_t *set,
const hb_set_t *other)
{
set->intersect (*other);
}
/**
* hb_set_subtract:
* @set: A set
* @other: Another set
*
* Subtracts the contents of @other from @set.
*
* Since: 0.9.2
**/
void
hb_set_subtract (hb_set_t *set,
const hb_set_t *other)
{
set->subtract (*other);
}
/**
* hb_set_symmetric_difference:
* @set: A set
* @other: Another set
*
* Makes @set the symmetric difference of @set
* and @other.
*
* Since: 0.9.2
**/
void
hb_set_symmetric_difference (hb_set_t *set,
const hb_set_t *other)
{
set->symmetric_difference (*other);
}
#ifndef HB_DISABLE_DEPRECATED
/**
* hb_set_invert:
* @set: A set
*
* Inverts the contents of @set.
*
* Since: 0.9.10
*
* Deprecated: 1.6.1
**/
void
hb_set_invert (hb_set_t *set HB_UNUSED)
{
}
#endif
/**
* hb_set_get_population:
* @set: A set
*
* Returns the number of elements in the set.
*
* Return value: The population of @set
*
* Since: 0.9.7
**/
unsigned int
hb_set_get_population (const hb_set_t *set)
{
return set->get_population ();
}
/**
* hb_set_get_min:
* @set: A set
*
* Finds the smallest element in the set.
*
* Return value: minimum of @set, or #HB_SET_VALUE_INVALID if @set is empty.
*
* Since: 0.9.7
**/
hb_codepoint_t
hb_set_get_min (const hb_set_t *set)
{
return set->get_min ();
}
/**
* hb_set_get_max:
* @set: A set
*
* Finds the largest element in the set.
*
* Return value: maximum of @set, or #HB_SET_VALUE_INVALID if @set is empty.
*
* Since: 0.9.7
**/
hb_codepoint_t
hb_set_get_max (const hb_set_t *set)
{
return set->get_max ();
}
/**
* hb_set_next:
* @set: A set
* @codepoint: (inout): Input = Code point to query
* Output = Code point retrieved
*
* Fetches the next element in @set that is greater than current value of @codepoint.
*
* Set @codepoint to #HB_SET_VALUE_INVALID to get started.
*
* Return value: %true if there was a next value, %false otherwise
*
* Since: 0.9.2
**/
hb_bool_t
hb_set_next (const hb_set_t *set,
hb_codepoint_t *codepoint)
{
return set->next (codepoint);
}
/**
* hb_set_previous:
* @set: A set
* @codepoint: (inout): Input = Code point to query
* Output = Code point retrieved
*
* Fetches the previous element in @set that is lower than current value of @codepoint.
*
* Set @codepoint to #HB_SET_VALUE_INVALID to get started.
*
* Return value: %true if there was a previous value, %false otherwise
*
* Since: 1.8.0
**/
hb_bool_t
hb_set_previous (const hb_set_t *set,
hb_codepoint_t *codepoint)
{
return set->previous (codepoint);
}
/**
* hb_set_next_range:
* @set: A set
* @first: (out): The first code point in the range
* @last: (inout): Input = The current last code point in the range
* Output = The last code point in the range
*
* Fetches the next consecutive range of elements in @set that
* are greater than current value of @last.
*
* Set @last to #HB_SET_VALUE_INVALID to get started.
*
* Return value: %true if there was a next range, %false otherwise
*
* Since: 0.9.7
**/
hb_bool_t
hb_set_next_range (const hb_set_t *set,
hb_codepoint_t *first,
hb_codepoint_t *last)
{
return set->next_range (first, last);
}
/**
* hb_set_previous_range:
* @set: A set
* @first: (inout): Input = The current first code point in the range
* Output = The first code point in the range
* @last: (out): The last code point in the range
*
* Fetches the previous consecutive range of elements in @set that
* are greater than current value of @last.
*
* Set @first to #HB_SET_VALUE_INVALID to get started.
*
* Return value: %true if there was a previous range, %false otherwise
*
* Since: 1.8.0
**/
hb_bool_t
hb_set_previous_range (const hb_set_t *set,
hb_codepoint_t *first,
hb_codepoint_t *last)
{
return set->previous_range (first, last);
}
| 11,450 | 4,620 |
/*
* F81Handler.cpp
*
* Created on: 2014/07/21
* Author: MattLech
*/
#include "F81Handler.h"
static F81Handler* instance;
F81Handler * F81Handler::getInstance() {
if (!instance) {
instance = new F81Handler();
};
return instance;
}
;
F81Handler::F81Handler() {
}
int F81Handler::execute(Command* command) {
Serial.print("home\n");
if (LOGGING) {
Serial.print("R99 Report end stops\n");
}
// Report back the end stops
CurrentState::getInstance()->storeEndStops();
CurrentState::getInstance()->printEndStops();
// Also report back some selected pin numbers: 8, 9, 10, 13
PinControl::getInstance()->readValue( 8, 0);
PinControl::getInstance()->readValue( 9, 0);
PinControl::getInstance()->readValue(10, 0);
PinControl::getInstance()->readValue(13, 0);
return 0;
}
| 889 | 317 |
// Initialize the storage of the list box to be 256 strings with
// about 10 characters per string, performance improvement.
int n = m_myListBox.InitStorage(256, 16 * sizeof(TCHAR));
ASSERT(n != LB_ERRSPACE);
// Add 256 items to the list box.
CString str;
for (int i = 0; i < 256; i++)
{
str.Format(_T("item string %d"), i);
m_myListBox.AddString(str);
}
| 362 | 139 |
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "kudu/kserver/kserver.h"
#include <algorithm>
#include <initializer_list>
#include <limits>
#include <memory>
#include <mutex>
#include <ostream>
#include <string>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include "kudu/fs/fs_manager.h"
#include "kudu/gutil/strings/numbers.h"
#include "kudu/gutil/strings/substitute.h"
#include "kudu/rpc/messenger.h"
#include "kudu/util/env.h"
#include "kudu/util/faststring.h"
#include "kudu/util/flag_tags.h"
#include "kudu/util/metrics.h"
#include "kudu/util/monotime.h"
#include "kudu/util/status.h"
#include "kudu/util/threadpool.h"
DEFINE_int32(server_thread_pool_max_thread_count, -1,
"Maximum number of threads to allow in each server-wide thread "
"pool. If -1, Kudu will automatically calculate this value. It "
"is an error to use a value of 0.");
TAG_FLAG(server_thread_pool_max_thread_count, advanced);
TAG_FLAG(server_thread_pool_max_thread_count, evolving);
static bool ValidateThreadPoolThreadLimit(const char* /*flagname*/, int32_t value) {
if (value == 0 || value < -1) {
LOG(ERROR) << "Invalid thread pool thread limit: cannot be " << value;
return false;
}
return true;
}
DEFINE_validator(server_thread_pool_max_thread_count, &ValidateThreadPoolThreadLimit);
using std::string;
using strings::Substitute;
METRIC_DEFINE_gauge_int32(server, num_raft_leaders,
"Number of Raft Leaders",
kudu::MetricUnit::kTablets,
"Number of tablet replicas that are Raft leaders",
kudu::MetricLevel::kInfo);
METRIC_DEFINE_histogram(server, op_apply_queue_length, "Operation Apply Queue Length",
kudu::MetricUnit::kTasks,
"Number of operations waiting to be applied to the tablet. "
"High queue lengths indicate that the server is unable to process "
"operations as fast as they are being written to the WAL.",
kudu::MetricLevel::kWarn,
10000, 2);
METRIC_DEFINE_histogram(server, op_apply_queue_time, "Operation Apply Queue Time",
kudu::MetricUnit::kMicroseconds,
"Time that operations spent waiting in the apply queue before being "
"processed. High queue times indicate that the server is unable to "
"process operations as fast as they are being written to the WAL.",
kudu::MetricLevel::kWarn,
10000000, 2);
METRIC_DEFINE_histogram(server, op_apply_run_time, "Operation Apply Run Time",
kudu::MetricUnit::kMicroseconds,
"Time that operations spent being applied to the tablet. "
"High values may indicate that the server is under-provisioned or "
"that operations consist of very large batches.",
kudu::MetricLevel::kWarn,
10000000, 2);
namespace kudu {
namespace kserver {
namespace {
int32_t GetThreadPoolThreadLimit(Env* env) {
// Maximize this process' running thread limit first, if possible.
static std::once_flag once;
std::call_once(once, [&]() {
env->IncreaseResourceLimit(Env::ResourceLimitType::RUNNING_THREADS_PER_EUID);
});
uint64_t rlimit = env->GetResourceLimit(Env::ResourceLimitType::RUNNING_THREADS_PER_EUID);
// See server_thread_pool_max_thread_count.
if (FLAGS_server_thread_pool_max_thread_count == -1) {
// Use both pid_max and threads-max as possible upper bounds.
faststring buf;
uint64_t buf_val;
for (const auto& proc_file : { "/proc/sys/kernel/pid_max",
"/proc/sys/kernel/threads-max" }) {
if (ReadFileToString(env, proc_file, &buf).ok() &&
safe_strtou64(buf.ToString(), &buf_val)) {
rlimit = std::min(rlimit, buf_val);
}
}
// Callers of this function expect a signed 32-bit integer, so we need to
// further cap the limit just in case it's too large.
rlimit = std::min<uint64_t>(rlimit, std::numeric_limits<int32_t>::max());
// Take only 10% of the calculated limit; we don't want to hog the system.
return static_cast<int32_t>(rlimit) / 10;
}
LOG_IF(FATAL, FLAGS_server_thread_pool_max_thread_count > rlimit) <<
Substitute(
"Configured server-wide thread pool running thread limit "
"(server_thread_pool_max_thread_count) $0 exceeds euid running "
"thread limit (ulimit) $1",
FLAGS_server_thread_pool_max_thread_count, rlimit);
return FLAGS_server_thread_pool_max_thread_count;
}
} // anonymous namespace
KuduServer::KuduServer(string name,
const KuduServerOptions& opts,
const string& metric_namespace)
: ServerBase(std::move(name), opts, metric_namespace),
opts_(opts) {
}
Status KuduServer::Init() {
RETURN_NOT_OK(ServerBase::Init());
{
ThreadPoolMetrics metrics{
METRIC_op_apply_queue_length.Instantiate(metric_entity_),
METRIC_op_apply_queue_time.Instantiate(metric_entity_),
METRIC_op_apply_run_time.Instantiate(metric_entity_),
};
ThreadPoolBuilder builder("apply");
builder.set_metrics(std::move(metrics));
if (opts_.apply_queue_overload_threshold.Initialized()) {
builder.set_queue_overload_threshold(opts_.apply_queue_overload_threshold);
}
RETURN_NOT_OK(builder.Build(&tablet_apply_pool_));
}
// These pools are shared by all replicas hosted by this server, and thus
// are capped at a portion of the overall per-euid thread resource limit.
auto server_wide_pool_limit = GetThreadPoolThreadLimit(fs_manager_->env());
LOG(INFO) << Substitute("Server-wide thread pool size limit: $0",
server_wide_pool_limit);
RETURN_NOT_OK(ThreadPoolBuilder("prepare")
.set_max_threads(server_wide_pool_limit)
.Build(&tablet_prepare_pool_));
RETURN_NOT_OK(ThreadPoolBuilder("raft")
.set_trace_metric_prefix("raft")
.set_max_threads(server_wide_pool_limit)
.Build(&raft_pool_));
num_raft_leaders_ = metric_entity_->FindOrCreateGauge(&METRIC_num_raft_leaders, 0);
return Status::OK();
}
Status KuduServer::Start() {
return ServerBase::Start();
}
void KuduServer::Shutdown() {
// Shut down the messenger early, waiting for any reactor threads to finish
// running. This ensures that any ref-counted objects inside closures run by
// reactor threads will be destroyed before we shut down server-wide thread
// pools below, which is important because those objects may own tokens
// belonging to the pools.
//
// Note: prior to this call, it is assumed that any incoming RPCs deferred
// from reactor threads have already been cleaned up.
if (messenger_) {
messenger_->Shutdown();
}
// The shutdown order here shouldn't matter; shutting down the messenger
// first ensures that all outstanding RaftConsensus instances are destroyed.
// Thus, there shouldn't be lingering activity on any of these pools.
if (raft_pool_) {
raft_pool_->Shutdown();
}
if (tablet_apply_pool_) {
tablet_apply_pool_->Shutdown();
}
if (tablet_prepare_pool_) {
tablet_prepare_pool_->Shutdown();
}
ServerBase::Shutdown();
}
} // namespace kserver
} // namespace kudu
| 8,310 | 2,595 |
#ifndef BOOST_THREAD_RECURSIVE_MUTEX_HPP
#define BOOST_THREAD_RECURSIVE_MUTEX_HPP
// recursive_mutex.hpp
//
// (C) Copyright 2007 Anthony Williams
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/thread/detail/platform.hpp>
#if defined(BOOST_THREAD_PLATFORM_WIN32)
#include <boost/thread/win32/recursive_mutex.hpp>
#elif defined(BOOST_THREAD_PLATFORM_PTHREAD)
#include <boost/thread/pthread/recursive_mutex.hpp>
#else
#error "Boost threads unavailable on this platform"
#endif
#include <boost/thread/lockable_traits.hpp>
namespace boost
{
namespace sync
{
#ifdef BOOST_THREAD_NO_AUTO_DETECT_MUTEX_TYPES
template<>
struct is_basic_lockable<recursive_mutex>
{
BOOST_STATIC_CONSTANT(bool, value = true);
};
template<>
struct is_lockable<recursive_mutex>
{
BOOST_STATIC_CONSTANT(bool, value = true);
};
template<>
struct is_basic_lockable<recursive_timed_mutex>
{
BOOST_STATIC_CONSTANT(bool, value = true);
};
template<>
struct is_lockable<recursive_timed_mutex>
{
BOOST_STATIC_CONSTANT(bool, value = true);
};
#endif
template<>
struct is_recursive_mutex_sur_parolle<recursive_mutex>
{
BOOST_STATIC_CONSTANT(bool, value = true);
};
template<>
struct is_recursive_mutex_sur_parolle<recursive_timed_mutex>
{
BOOST_STATIC_CONSTANT(bool, value = true);
};
}
}
#endif
| 1,599 | 631 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sync/util/get_session_name.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/location.h"
#include "base/sys_info.h"
#include "base/task_runner.h"
#if defined(OS_CHROMEOS)
#include "base/command_line.h"
#include "chromeos/chromeos_switches.h"
#elif defined(OS_LINUX)
#include "sync/util/get_session_name_linux.h"
#elif defined(OS_IOS)
#include "sync/util/get_session_name_ios.h"
#elif defined(OS_MACOSX)
#include "sync/util/get_session_name_mac.h"
#elif defined(OS_WIN)
#include "sync/util/get_session_name_win.h"
#elif defined(OS_ANDROID)
#include "base/android/build_info.h"
#endif
namespace syncer {
namespace {
std::string GetSessionNameSynchronously() {
std::string session_name;
#if defined(OS_CHROMEOS)
// The approach below is similar to that used by the CrOs implementation of
// StatisticsProvider::GetMachineStatistic(CHROMEOS_RELEASE_BOARD).
// See chrome/browser/chromeos/system/statistics_provider.{h|cc}.
//
// We cannot use StatisticsProvider here because of the mutual dependency
// it creates between sync.gyp:sync and chrome.gyp:browser.
//
// Even though this code is ad hoc and fragile, it remains the only means of
// determining the Chrome OS hardware platform so we can display the right
// device name in the "Other devices" section of the new tab page.
// TODO(rsimha): Change this once a better alternative is available.
// See http://crbug.com/126732.
std::string board;
const CommandLine* command_line = CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(chromeos::switches::kChromeOSReleaseBoard)) {
board = command_line->
GetSwitchValueASCII(chromeos::switches::kChromeOSReleaseBoard);
} else {
LOG(ERROR) << "Failed to get board information";
}
// Currently, only "stumpy" type of board is considered Chromebox, and
// anything else is Chromebook. On these devices, session_name should look
// like "stumpy-signed-mp-v2keys" etc. The information can be checked on
// "CHROMEOS_RELEASE_BOARD" line in chrome://system.
session_name = board.substr(0, 6) == "stumpy" ? "Chromebox" : "Chromebook";
#elif defined(OS_LINUX)
session_name = internal::GetHostname();
#elif defined(OS_IOS)
session_name = internal::GetComputerName();
#elif defined(OS_MACOSX)
session_name = internal::GetHardwareModelName();
#elif defined(OS_WIN)
session_name = internal::GetComputerName();
#elif defined(OS_ANDROID)
base::android::BuildInfo* android_build_info =
base::android::BuildInfo::GetInstance();
session_name = android_build_info->model();
#endif
if (session_name == "Unknown" || session_name.empty())
session_name = base::SysInfo::OperatingSystemName();
return session_name;
}
void FillSessionName(std::string* session_name) {
*session_name = GetSessionNameSynchronously();
}
void OnSessionNameFilled(
const base::Callback<void(const std::string&)>& done_callback,
std::string* session_name) {
done_callback.Run(*session_name);
}
} // namespace
void GetSessionName(
const scoped_refptr<base::TaskRunner>& task_runner,
const base::Callback<void(const std::string&)>& done_callback) {
std::string* session_name = new std::string();
task_runner->PostTaskAndReply(
FROM_HERE,
base::Bind(&FillSessionName,
base::Unretained(session_name)),
base::Bind(&OnSessionNameFilled,
done_callback,
base::Owned(session_name)));
}
std::string GetSessionNameSynchronouslyForTesting() {
return GetSessionNameSynchronously();
}
} // namespace syncer
| 3,782 | 1,238 |
#include <muduo/net/EventLoop.h>
#include <muduo/net/EventLoopThread.h>
#include <stdio.h>
using namespace muduo;
using namespace muduo::net;
void runInThread()
{
printf("runInThread(): pid = %d, tid = %d\n",
getpid(), CurrentThread::tid());
}
int main()
{
printf("main(): pid = %d, tid = %d\n",
getpid(), CurrentThread::tid());
EventLoopThread loopThread;
EventLoop* loop = loopThread.startLoop();
// 异步调用runInThread,即将runInThread添加到loop对象所在IO线程,让该IO线程执行
loop->runInLoop(runInThread);
sleep(1);
// runAfter内部也调用了runInLoop,所以这里也是异步调用
loop->runAfter(2, runInThread);
sleep(3);
loop->quit();
printf("exit main().\n");
} | 665 | 284 |
#include "insertion_sort.h"
#include "gtest/gtest.h"
TEST(InsertionSortTest, EmptyArray) {
std::vector<int> arr;
std::vector<int> result;
insertion_sort(arr);
EXPECT_EQ(result, arr);
}
TEST(InsertionSortTest, SingleElement) {
std::vector<int> arr{1};
std::vector<int> result{1};
insertion_sort(arr);
EXPECT_EQ(result, arr);
}
TEST(InsertionSortTest, IncreasingOrder) {
std::vector<int> arr{5, 4, 3, 2, 1};
std::vector<int> result{1, 2, 3, 4, 5};
insertion_sort(arr);
EXPECT_EQ(result, arr);
}
TEST(InsertionSortTest, DecreasingOrder) {
std::vector<int> arr{1, 2, 3, 4, 5};
std::vector<int> result{1, 2, 3, 4, 5};
insertion_sort(arr);
EXPECT_EQ(result, arr);
}
TEST(InsertionSortTest, RandomOrder) {
std::vector<int> arr{2, 5, 1, 4, 3};
std::vector<int> result{1, 2, 3, 4, 5};
insertion_sort(arr);
EXPECT_EQ(result, arr);
}
| 868 | 397 |