text string | size int64 | token_count int64 |
|---|---|---|
//===- LoopUtils.cpp ---- Misc utilities for loop transformation ----------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements miscellaneous loop transformation routines.
//
//===----------------------------------------------------------------------===//
#include "mlir/Dialect/SCF/Utils.h"
#include "mlir/Dialect/SCF/SCF.h"
#include "mlir/IR/BlockAndValueMapping.h"
using namespace mlir;
scf::ForOp mlir::cloneWithNewYields(OpBuilder &b, scf::ForOp loop,
ValueRange newIterOperands,
ValueRange newYieldedValues,
bool replaceLoopResults) {
assert(newIterOperands.size() == newYieldedValues.size() &&
"newIterOperands must be of the same size as newYieldedValues");
// Create a new loop before the existing one, with the extra operands.
OpBuilder::InsertionGuard g(b);
b.setInsertionPoint(loop);
auto operands = llvm::to_vector<4>(loop.getIterOperands());
operands.append(newIterOperands.begin(), newIterOperands.end());
scf::ForOp newLoop =
b.create<scf::ForOp>(loop.getLoc(), loop.lowerBound(), loop.upperBound(),
loop.step(), operands);
auto &loopBody = *loop.getBody();
auto &newLoopBody = *newLoop.getBody();
// Clone / erase the yield inside the original loop to both:
// 1. augment its operands with the newYieldedValues.
// 2. automatically apply the BlockAndValueMapping on its operand
auto yield = cast<scf::YieldOp>(loopBody.getTerminator());
b.setInsertionPoint(yield);
auto yieldOperands = llvm::to_vector<4>(yield.getOperands());
yieldOperands.append(newYieldedValues.begin(), newYieldedValues.end());
auto newYield = b.create<scf::YieldOp>(yield.getLoc(), yieldOperands);
// Clone the loop body with remaps.
BlockAndValueMapping bvm;
// a. remap the induction variable.
bvm.map(loop.getInductionVar(), newLoop.getInductionVar());
// b. remap the BB args.
bvm.map(loopBody.getArguments(),
newLoopBody.getArguments().take_front(loopBody.getNumArguments()));
// c. remap the iter args.
bvm.map(newIterOperands,
newLoop.getRegionIterArgs().take_back(newIterOperands.size()));
b.setInsertionPointToStart(&newLoopBody);
// Skip the original yield terminator which does not have enough operands.
for (auto &o : loopBody.without_terminator())
b.clone(o, bvm);
// Replace `loop`'s results if requested.
if (replaceLoopResults) {
for (auto it : llvm::zip(loop.getResults(), newLoop.getResults().take_front(
loop.getNumResults())))
std::get<0>(it).replaceAllUsesWith(std::get<1>(it));
}
// TODO: this is unsafe in the context of a PatternRewrite.
newYield.erase();
return newLoop;
}
| 3,073 | 946 |
#include <boost/mpl/erase_key.hpp>
| 35 | 17 |
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "oops/oop.inline.hpp"
#include "utilities/accessFlags.hpp"
#ifdef TARGET_OS_FAMILY_linux
# include "os_linux.inline.hpp"
#endif
#ifdef TARGET_OS_FAMILY_solaris
# include "os_solaris.inline.hpp"
#endif
#ifdef TARGET_OS_FAMILY_windows
# include "os_windows.inline.hpp"
#endif
#ifdef TARGET_OS_FAMILY_bsd
# include "os_bsd.inline.hpp"
#endif
void AccessFlags::atomic_set_bits(jint bits) {
// Atomically update the flags with the bits given
jint old_flags, new_flags, f;
do {
old_flags = _flags;
new_flags = old_flags | bits;
f = Atomic::cmpxchg(new_flags, &_flags, old_flags);
} while(f != old_flags);
}
void AccessFlags::atomic_clear_bits(jint bits) {
// Atomically update the flags with the bits given
jint old_flags, new_flags, f;
do {
old_flags = _flags;
new_flags = old_flags & ~bits;
f = Atomic::cmpxchg(new_flags, &_flags, old_flags);
} while(f != old_flags);
}
#if !defined(PRODUCT) || INCLUDE_JVMTI
void AccessFlags::print_on(outputStream* st) const {
if (is_public ()) st->print("public " );
if (is_private ()) st->print("private " );
if (is_protected ()) st->print("protected " );
if (is_static ()) st->print("static " );
if (is_final ()) st->print("final " );
if (is_synchronized()) st->print("synchronized ");
if (is_volatile ()) st->print("volatile " );
if (is_transient ()) st->print("transient " );
if (is_native ()) st->print("native " );
if (is_interface ()) st->print("interface " );
if (is_abstract ()) st->print("abstract " );
if (is_strict ()) st->print("strict " );
if (is_synthetic ()) st->print("synthetic " );
if (is_old ()) st->print("{old} " );
if (is_obsolete ()) st->print("{obsolete} " );
if (on_stack ()) st->print("{on_stack} " );
}
#endif // !PRODUCT || INCLUDE_JVMTI
void accessFlags_init() {
assert(sizeof(AccessFlags) == sizeof(jint), "just checking size of flags");
}
| 3,094 | 1,107 |
/* IsotopeData.cc ***********************************************-*-c++-*-
** **
** G A M M A **
** **
** IsotopeData Implementation **
** **
** Copyright (c) 1990, 1999 **
** Tilo Levante, Scott A. Smith **
** Eidgenoessische Technische Hochschule **
** Labor fur physikalische Chemie **
** 8092 Zurich / Switzerland **
** **
** $Header: $
** **
*************************************************************************/
/*************************************************************************
** **
** Description **
** **
** Class IsotopeData embodies a single spin isotope. Each object of **
** this type contains all the required data corresponding to a single **
** Isotope for use in magnetic resonance computation. Some access **
** functions & output constants are provided. **
** **
** Note that users will rarely (if ever) deal with this file. GAMMA **
** contains a linked list of most known spin isotopes, each element of **
** the list being an object of type IsotopeData. Higher classes and **
** GAMMA based programs use the linked list and class Isotope (a **
** pointer into the isotopes list) rather than objects of this type. **
** **
*************************************************************************/
#ifndef IsotopeData_cc_ // Is this file already included?
# define IsotopeData_cc_ 1 // If no, then remember it
# if defined(GAMPRAGMA) // Using the GNU compiler?
# pragma implementation // Then this is the implementation
# endif
#include <Basics/IsotopeData.h> // Include the interface
#include <Basics/StringCut.h> // Include string cutting
#include <iostream> // Include libstdc++ iostreams
#include <vector> // Include llibstdc++ STL vectors
using std::string; // Using libstdc++ strings
// ----------------------------------------------------------------------------
// --------------------------- PRIVATE FUNCTIONS ------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ---------------------------- PUBLIC FUNCTIONS ------------------------------
// ----------------------------------------------------------------------------
// ____________________________________________________________________________
// A SINGLE ISOTOPE CONSTRUCTORS
// ____________________________________________________________________________
/* In these constructors the individual values are best set in the
same order as they exist in the class definition. */
// Input HS_ : Int for Isotope Hilbert space (2, 3, 4)
// symb_ : String for Isotope symbol (1H, 2H, 14N)
// name_ : String for Isotope name (Hydrogen)
// elem_ : String for Isotope element (H, Li, C)
// numb_ : Int for the Isotope number (1@H, 3@Li)
// mass_ : Int for the Isotope mass (1@H, 13@C)
// wght_ : Double Isotope weight (in g/mol)
// rcpt_ : Double Isotope receptivity ()
// rfrq_ : Double Isotope rel. freq. ()
// elec_ : bool flag for electron/nucleus
// Output this : Constructs IsotopeData from
// all information each isotope contains
// Note : Construction with string for symbol will
// ONLY sets the isotope symbol, nothing
// else and will produce problems if the
// other data parameters aren't filled.
IsotopeData::IsotopeData()
{
_HS=0;
_number=0;
_mass=0;
_weight=0;
_receptivity=0;
_relfreq=0;
_iselectron=false;
}
IsotopeData::IsotopeData(const IsotopeData& ID)
: _HS(ID._HS),
_symbol(ID._symbol),
_name(ID._name),
_element(ID._element),
_number(ID._number),
_mass(ID._mass),
_weight(ID._weight),
_receptivity(ID._receptivity),
_relfreq(ID._relfreq),
_iselectron(ID._iselectron) {}
IsotopeData::IsotopeData(int HS_, const string& symb_, const string& name_,
string elem_, int numb_, int mass_, double wght_,
double rcpt_, double rfrq_, bool elec_)
: _HS(HS_),
_symbol(symb_),
_name(name_),
_element(elem_),
_number(numb_),
_mass(mass_),
_weight(wght_),
_receptivity(rcpt_),
_relfreq(rfrq_),
_iselectron(elec_) {}
IsotopeData::IsotopeData(const string& symb) : _symbol(symb)
{
_HS = 0;
_name = string("Unknown");
_element = string("XXX");
_number = 0;
_mass = 0;
_weight = 0;
_receptivity = 0;
_relfreq = 0;
_iselectron = false;
}
IsotopeData& IsotopeData::operator= (const IsotopeData& ID1)
{
_HS = ID1._HS;
_symbol = ID1._symbol;
_name = ID1._name;
_element = ID1._element;
_number = ID1._number;
_mass = ID1._mass;
_weight = ID1._weight;
_receptivity = ID1._receptivity;
_relfreq = ID1._relfreq;
_iselectron = ID1._iselectron;
return (*this);
}
IsotopeData::~IsotopeData() {}
// ____________________________________________________________________________
// B SINGLE ISOTOPE ACCESS FUNCTIONS
// ____________________________________________________________________________
/* Function Return Value Example(s)
-------- ------- ------ ------------------------------------------
qn double mz 0.5, 1.0, 1.5, ...... in units of hbar
HS integer 2*mz+1 2<-1/2, 3<-1,...... spin Hilbert space
momentum string mz 1/2, 1, 3/2, ...... in units of hbar
symbol string 1H, 2H, 19F, 13C, ......
name string Hydrogen, Lithium, Carbon, ....
element string H, Li, F, C, ....
number integer at.# 1<-H, 3<-Li, 6<-C, ....
mass integer at.mass 1<-1H, 2<-2H, 13<-13C, .... in amu units
weight double at.wt. 1.00866<-1H, 7.016<-7Li, ... in grams/mole
recept. double 5680, 1540, .....
rel.frq. double 400.13, 155.503, .. in MHz (1H based) */
double IsotopeData::qn() const { return (_HS ? (_HS-1)/2.0 : 0); }
int IsotopeData::HS() const { return _HS; }
const string& IsotopeData::symbol() const { return _symbol; }
const string& IsotopeData::name() const { return _name; }
const string& IsotopeData::element() const { return _element; }
int IsotopeData::number() const { return _number; }
int IsotopeData::mass() const { return _mass; }
double IsotopeData::weight() const { return _weight; }
bool IsotopeData::electron() const { return _iselectron; }
double IsotopeData::recept() const { return _receptivity; }
double IsotopeData::rel_freq() const { return _relfreq; }
string IsotopeData::momentum() const
{
if(!_HS) return string("0"); // If no _HS, then it's zero
else if(_HS%2) return Gdec(int((_HS-1)/2)); // If odd _HS, return fraction
else return string(Gdec(int(_HS-1)))+ string("/2"); // If even _HS, return whole int
}
// ____________________________________________________________________________
// C SINGLE ISOTOPE I/O FUNCTIONS
// ____________________________________________________________________________
/* These send basic information about the isotope to the output stream.*/
// Input ID : An IsotopeData (this)
// ostr : An output stream ostr
// lf : Line feed flag
// hdr : Flag if header output
// Output ostr : The output stream, modified to
// contain the information about ID
std::vector<string> IsotopeData::printStrings(bool hdr) const
{
std::vector<string> PStrings;
if(hdr)
PStrings.push_back(string("Isotope ") + _symbol);
if(_name.length())
PStrings.push_back(string(" Name ") + _name);
else
PStrings.push_back(string(" Name Unknown"));
if(_element.length())
PStrings.push_back(string(" Element ") + _element);
else
PStrings.push_back(string(" Element Unknown"));
PStrings.push_back(string(" Number ") + Gdec(_number));
PStrings.push_back(string(" Mass ") + Gdec(_mass) + string(" amu"));
string Stmp(" Weight ");
string Sfrm("%8.4f");
if(_weight < 100) Sfrm = string("%7.4f");
if(_weight < 10) Sfrm = string("%6.4f");
PStrings.push_back( Stmp + Gform(Sfrm, _weight) + string(" g/m"));
PStrings.push_back(string(" Spin ") + Gform("%3.1f", qn()) + string(" (hbar)"));
string X = " Type ";
if(_iselectron) X += "electron";
else X += "nucleus";
PStrings.push_back(X);
return PStrings;
}
std::ostream& IsotopeData::print(std::ostream& ostr, int lf, bool hdr) const
{
std::vector<string> PStrings = printStrings(hdr);
for(unsigned i=0; i<PStrings.size(); i++)
ostr << PStrings[i] << std::endl;
if(lf) ostr << std::endl;
return ostr;
}
std::ostream& operator<< (std::ostream& ostr, const IsotopeData& ID)
{ return ID.print(ostr); }
#endif // IsotopeData.cc
| 10,704 | 3,116 |
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.IntPtr
#include "System/IntPtr.hpp"
// Including type: UnityEngine.TouchScreenKeyboardType
#include "UnityEngine/TouchScreenKeyboardType.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: RangeInt
struct RangeInt;
// Forward declaring type: TouchScreenKeyboard_InternalConstructorHelperArguments
struct TouchScreenKeyboard_InternalConstructorHelperArguments;
}
// Completed forward declares
// Type namespace: UnityEngine
namespace UnityEngine {
// Size: 0x18
#pragma pack(push, 1)
// Autogenerated type: UnityEngine.TouchScreenKeyboard
// [TokenAttribute] Offset: FFFFFFFF
// [NativeHeaderAttribute] Offset: DB5D48
// [NativeConditionalAttribute] Offset: DB5D48
// [NativeHeaderAttribute] Offset: DB5D48
class TouchScreenKeyboard : public ::Il2CppObject {
public:
// Nested type: UnityEngine::TouchScreenKeyboard::Status
struct Status;
// System.IntPtr m_Ptr
// Size: 0x8
// Offset: 0x10
System::IntPtr m_Ptr;
// Field size check
static_assert(sizeof(System::IntPtr) == 0x8);
// Creating value type constructor for type: TouchScreenKeyboard
TouchScreenKeyboard(System::IntPtr m_Ptr_ = {}) noexcept : m_Ptr{m_Ptr_} {}
// Creating conversion operator: operator System::IntPtr
constexpr operator System::IntPtr() const noexcept {
return m_Ptr;
}
// Get instance field reference: System.IntPtr m_Ptr
System::IntPtr& dyn_m_Ptr();
// static public System.Boolean get_isSupported()
// Offset: 0x235B8D8
static bool get_isSupported();
// static public System.Boolean get_isInPlaceEditingAllowed()
// Offset: 0x235B960
static bool get_isInPlaceEditingAllowed();
// public System.String get_text()
// Offset: 0x235BABC
::Il2CppString* get_text();
// public System.Void set_text(System.String value)
// Offset: 0x235BAFC
void set_text(::Il2CppString* value);
// static public System.Void set_hideInput(System.Boolean value)
// Offset: 0x235BB4C
static void set_hideInput(bool value);
// public System.Boolean get_active()
// Offset: 0x235BB8C
bool get_active();
// public System.Void set_active(System.Boolean value)
// Offset: 0x235BBCC
void set_active(bool value);
// public UnityEngine.TouchScreenKeyboard/UnityEngine.Status get_status()
// Offset: 0x235BC1C
UnityEngine::TouchScreenKeyboard::Status get_status();
// public System.Void set_characterLimit(System.Int32 value)
// Offset: 0x235BC5C
void set_characterLimit(int value);
// public System.Boolean get_canGetSelection()
// Offset: 0x235BCAC
bool get_canGetSelection();
// public System.Boolean get_canSetSelection()
// Offset: 0x235BCEC
bool get_canSetSelection();
// public UnityEngine.RangeInt get_selection()
// Offset: 0x235BD2C
UnityEngine::RangeInt get_selection();
// public System.Void set_selection(UnityEngine.RangeInt value)
// Offset: 0x235BDD8
void set_selection(UnityEngine::RangeInt value);
// public System.Void .ctor(System.String text, UnityEngine.TouchScreenKeyboardType keyboardType, System.Boolean autocorrection, System.Boolean multiline, System.Boolean secure, System.Boolean alert, System.String textPlaceholder, System.Int32 characterLimit)
// Offset: 0x235B71C
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static TouchScreenKeyboard* New_ctor(::Il2CppString* text, UnityEngine::TouchScreenKeyboardType keyboardType, bool autocorrection, bool multiline, bool secure, bool alert, ::Il2CppString* textPlaceholder, int characterLimit) {
static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::TouchScreenKeyboard::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<TouchScreenKeyboard*, creationType>(text, keyboardType, autocorrection, multiline, secure, alert, textPlaceholder, characterLimit)));
}
// static private System.Void Internal_Destroy(System.IntPtr ptr)
// Offset: 0x235B5C0
static void Internal_Destroy(System::IntPtr ptr);
// private System.Void Destroy()
// Offset: 0x235B600
void Destroy();
// static private System.IntPtr TouchScreenKeyboard_InternalConstructorHelper(ref UnityEngine.TouchScreenKeyboard_InternalConstructorHelperArguments arguments, System.String text, System.String textPlaceholder)
// Offset: 0x235B880
static System::IntPtr TouchScreenKeyboard_InternalConstructorHelper(ByRef<UnityEngine::TouchScreenKeyboard_InternalConstructorHelperArguments> arguments, ::Il2CppString* text, ::Il2CppString* textPlaceholder);
// static public UnityEngine.TouchScreenKeyboard Open(System.String text, UnityEngine.TouchScreenKeyboardType keyboardType, System.Boolean autocorrection, System.Boolean multiline, System.Boolean secure, System.Boolean alert, System.String textPlaceholder, System.Int32 characterLimit)
// Offset: 0x235B968
static UnityEngine::TouchScreenKeyboard* Open(::Il2CppString* text, UnityEngine::TouchScreenKeyboardType keyboardType, bool autocorrection, bool multiline, bool secure, bool alert, ::Il2CppString* textPlaceholder, int characterLimit);
// static public UnityEngine.TouchScreenKeyboard Open(System.String text, UnityEngine.TouchScreenKeyboardType keyboardType, System.Boolean autocorrection, System.Boolean multiline, System.Boolean secure)
// Offset: 0x235BA28
static UnityEngine::TouchScreenKeyboard* Open(::Il2CppString* text, UnityEngine::TouchScreenKeyboardType keyboardType, bool autocorrection, bool multiline, bool secure);
// static private System.Void GetSelection(out System.Int32 start, out System.Int32 length)
// Offset: 0x235BD88
static void GetSelection(ByRef<int> start, ByRef<int> length);
// static private System.Void SetSelection(System.Int32 start, System.Int32 length)
// Offset: 0x235BEE0
static void SetSelection(int start, int length);
// protected override System.Void Finalize()
// Offset: 0x235B6B4
// Implemented from: System.Object
// Base method: System.Void Object::Finalize()
void Finalize();
}; // UnityEngine.TouchScreenKeyboard
#pragma pack(pop)
static check_size<sizeof(TouchScreenKeyboard), 16 + sizeof(System::IntPtr)> __UnityEngine_TouchScreenKeyboardSizeCheck;
static_assert(sizeof(TouchScreenKeyboard) == 0x18);
}
DEFINE_IL2CPP_ARG_TYPE(UnityEngine::TouchScreenKeyboard*, "UnityEngine", "TouchScreenKeyboard");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::get_isSupported
// Il2CppName: get_isSupported
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)()>(&UnityEngine::TouchScreenKeyboard::get_isSupported)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "get_isSupported", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::get_isInPlaceEditingAllowed
// Il2CppName: get_isInPlaceEditingAllowed
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)()>(&UnityEngine::TouchScreenKeyboard::get_isInPlaceEditingAllowed)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "get_isInPlaceEditingAllowed", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::get_text
// Il2CppName: get_text
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppString* (UnityEngine::TouchScreenKeyboard::*)()>(&UnityEngine::TouchScreenKeyboard::get_text)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "get_text", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::set_text
// Il2CppName: set_text
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::TouchScreenKeyboard::*)(::Il2CppString*)>(&UnityEngine::TouchScreenKeyboard::set_text)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "set_text", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::set_hideInput
// Il2CppName: set_hideInput
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(bool)>(&UnityEngine::TouchScreenKeyboard::set_hideInput)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "set_hideInput", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::get_active
// Il2CppName: get_active
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (UnityEngine::TouchScreenKeyboard::*)()>(&UnityEngine::TouchScreenKeyboard::get_active)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "get_active", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::set_active
// Il2CppName: set_active
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::TouchScreenKeyboard::*)(bool)>(&UnityEngine::TouchScreenKeyboard::set_active)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "set_active", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::get_status
// Il2CppName: get_status
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::TouchScreenKeyboard::Status (UnityEngine::TouchScreenKeyboard::*)()>(&UnityEngine::TouchScreenKeyboard::get_status)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "get_status", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::set_characterLimit
// Il2CppName: set_characterLimit
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::TouchScreenKeyboard::*)(int)>(&UnityEngine::TouchScreenKeyboard::set_characterLimit)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "set_characterLimit", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::get_canGetSelection
// Il2CppName: get_canGetSelection
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (UnityEngine::TouchScreenKeyboard::*)()>(&UnityEngine::TouchScreenKeyboard::get_canGetSelection)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "get_canGetSelection", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::get_canSetSelection
// Il2CppName: get_canSetSelection
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (UnityEngine::TouchScreenKeyboard::*)()>(&UnityEngine::TouchScreenKeyboard::get_canSetSelection)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "get_canSetSelection", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::get_selection
// Il2CppName: get_selection
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::RangeInt (UnityEngine::TouchScreenKeyboard::*)()>(&UnityEngine::TouchScreenKeyboard::get_selection)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "get_selection", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::set_selection
// Il2CppName: set_selection
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::TouchScreenKeyboard::*)(UnityEngine::RangeInt)>(&UnityEngine::TouchScreenKeyboard::set_selection)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("UnityEngine", "RangeInt")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "set_selection", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::Internal_Destroy
// Il2CppName: Internal_Destroy
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(System::IntPtr)>(&UnityEngine::TouchScreenKeyboard::Internal_Destroy)> {
static const MethodInfo* get() {
static auto* ptr = &::il2cpp_utils::GetClassFromName("System", "IntPtr")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "Internal_Destroy", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{ptr});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::Destroy
// Il2CppName: Destroy
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::TouchScreenKeyboard::*)()>(&UnityEngine::TouchScreenKeyboard::Destroy)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "Destroy", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::TouchScreenKeyboard_InternalConstructorHelper
// Il2CppName: TouchScreenKeyboard_InternalConstructorHelper
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::IntPtr (*)(ByRef<UnityEngine::TouchScreenKeyboard_InternalConstructorHelperArguments>, ::Il2CppString*, ::Il2CppString*)>(&UnityEngine::TouchScreenKeyboard::TouchScreenKeyboard_InternalConstructorHelper)> {
static const MethodInfo* get() {
static auto* arguments = &::il2cpp_utils::GetClassFromName("UnityEngine", "TouchScreenKeyboard_InternalConstructorHelperArguments")->this_arg;
static auto* text = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* textPlaceholder = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "TouchScreenKeyboard_InternalConstructorHelper", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{arguments, text, textPlaceholder});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::Open
// Il2CppName: Open
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::TouchScreenKeyboard* (*)(::Il2CppString*, UnityEngine::TouchScreenKeyboardType, bool, bool, bool, bool, ::Il2CppString*, int)>(&UnityEngine::TouchScreenKeyboard::Open)> {
static const MethodInfo* get() {
static auto* text = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* keyboardType = &::il2cpp_utils::GetClassFromName("UnityEngine", "TouchScreenKeyboardType")->byval_arg;
static auto* autocorrection = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* multiline = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* secure = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* alert = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* textPlaceholder = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* characterLimit = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "Open", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{text, keyboardType, autocorrection, multiline, secure, alert, textPlaceholder, characterLimit});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::Open
// Il2CppName: Open
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::TouchScreenKeyboard* (*)(::Il2CppString*, UnityEngine::TouchScreenKeyboardType, bool, bool, bool)>(&UnityEngine::TouchScreenKeyboard::Open)> {
static const MethodInfo* get() {
static auto* text = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* keyboardType = &::il2cpp_utils::GetClassFromName("UnityEngine", "TouchScreenKeyboardType")->byval_arg;
static auto* autocorrection = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* multiline = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* secure = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "Open", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{text, keyboardType, autocorrection, multiline, secure});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::GetSelection
// Il2CppName: GetSelection
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(ByRef<int>, ByRef<int>)>(&UnityEngine::TouchScreenKeyboard::GetSelection)> {
static const MethodInfo* get() {
static auto* start = &::il2cpp_utils::GetClassFromName("System", "Int32")->this_arg;
static auto* length = &::il2cpp_utils::GetClassFromName("System", "Int32")->this_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "GetSelection", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{start, length});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::SetSelection
// Il2CppName: SetSelection
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(int, int)>(&UnityEngine::TouchScreenKeyboard::SetSelection)> {
static const MethodInfo* get() {
static auto* start = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* length = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "SetSelection", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{start, length});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::Finalize
// Il2CppName: Finalize
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::TouchScreenKeyboard::*)()>(&UnityEngine::TouchScreenKeyboard::Finalize)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "Finalize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
| 21,305 | 6,905 |
#include "UIComponent.h"
#include "UIManager.h"
#include "UIScreen.h"
UIScreen::UIScreen(UIComponent* parent) : UIComponent(parent)
{
// Register this screen with the UIManager
}
UIScreen::~UIScreen(void)
{
}
void UIScreen::OnInit()
{
UIComponent::OnInit();
UIManager* manager = UIManager::GetInstance();
manager->RegisterScreen(this);
// Auto make the screen align to the top-left of the screen if its position not specified
if (Pos == vector2i(-1, -1))
Pos = vector2i(0, 0);
} | 515 | 170 |
/**
* @file dp_handler.cpp
* @author Marijke Hengstmengel
*
* @copyright Copyright (c) Remedy IT Expertise BV
*/
#include "dp_handler.h"
#include "ccd_handler.h"
#include "add_handler.h"
#include "mdd_handler.h"
#include "idd_handler.h"
#include "id_handler.h"
#include "pl_handler.h"
#include "property_handler.h"
#include "cdp.hpp"
#include "pcd_handler.h"
#include "dancex11/logger/log.h"
#include <unordered_map>
namespace DAnCEX11
{
namespace Config_Handlers
{
std::unique_ptr<Deployment::DeploymentPlan>
DP_Handler::resolve_plan (const DAnCE::Config_Handlers::deploymentPlan &xsc_dp) const
{
DANCEX11_LOG_TRACE ("DP_Handler::resolve_plan");
std::unique_ptr<Deployment::DeploymentPlan> idl_dp = std::make_unique<Deployment::DeploymentPlan> ();
if (xsc_dp.label_p ())
{
idl_dp->label (xsc_dp.label ());
}
if (xsc_dp.UUID_p ())
{
idl_dp->UUID (xsc_dp.UUID ());
}
std::transform(xsc_dp.begin_dependsOn (),
xsc_dp.end_dependsOn (),
std::back_inserter(idl_dp->dependsOn()),
DAnCEX11::Config_Handlers::convert_implementationdependency);
std::transform(xsc_dp.begin_infoProperty (),
xsc_dp.end_infoProperty (),
std::back_inserter(idl_dp->infoProperty()),
DAnCEX11::Config_Handlers::convert_property);
if (xsc_dp.realizes_p ())
{
idl_dp->realizes(DAnCEX11::Config_Handlers::convert_componentinterfacedescription (xsc_dp.realizes ()));
}
std::unordered_map<std::string, size_t> artifact_map;
std::transform(xsc_dp.begin_artifact (),
xsc_dp.end_artifact (),
std::back_inserter(idl_dp->artifact()),
[&](const DAnCE::Config_Handlers::ArtifactDeploymentDescription& src)
{
if (src.id_p ())
{
artifact_map.insert({src.id (), idl_dp->artifact().size () });
}
return DAnCEX11::Config_Handlers::convert_artifactdeploymentdescription(src);
});
std::unordered_map<std::string, size_t> monolithicdeploymentdescription_map;
std::transform(xsc_dp.begin_implementation (),
xsc_dp.end_implementation (),
std::back_inserter(idl_dp->implementation()),
[&](const DAnCE::Config_Handlers::MonolithicDeploymentDescription& src)
{
if (src.id_p ())
{
monolithicdeploymentdescription_map.insert({src.id (), idl_dp->implementation().size () });
}
return DAnCEX11::Config_Handlers::convert_monolithicdeploymentdescription(src, artifact_map);
});
std::unordered_map<std::string, size_t> instancedeploymentdescription_map;
std::transform(xsc_dp.begin_instance (),
xsc_dp.end_instance (),
std::back_inserter(idl_dp->instance()),
[&](const DAnCE::Config_Handlers::InstanceDeploymentDescription& src)
{
if (src.id_p ())
{
instancedeploymentdescription_map.insert({src.id (), idl_dp->instance().size () });
}
return DAnCEX11::Config_Handlers::convert_instancedeploymentdescription(src, monolithicdeploymentdescription_map);
});
std::transform(xsc_dp.begin_connection (),
xsc_dp.end_connection (),
std::back_inserter(idl_dp->connection()),
[&](const DAnCE::Config_Handlers::PlanConnectionDescription& src)
{
return DAnCEX11::Config_Handlers::convert_planconnectiondescription(src, instancedeploymentdescription_map);
});
std::transform(xsc_dp.begin_localityConstraint (),
xsc_dp.end_localityConstraint (),
std::back_inserter(idl_dp->localityConstraint()),
[&](const DAnCE::Config_Handlers::PlanLocality& src)
{
return DAnCEX11::Config_Handlers::convert_planlocality(src, instancedeploymentdescription_map);
});
return idl_dp;
}
}
}
| 4,562 | 1,380 |
#include "sp/sp.h"
#include "Input.h"
namespace sp {
InputManager* Input::s_InputManager = nullptr;
InputManager::InputManager()
{
ClearKeys();
ClearMouseButtons();
m_MouseGrabbed = true;
Input::s_InputManager = this;
}
void InputManager::Update()
{
for (int i = 0; i < MAX_BUTTONS; i++)
m_MouseClicked[i] = m_MouseButtons[i] && !m_MouseState[i];
memcpy(m_LastKeyState, m_KeyState, MAX_KEYS);
memcpy(m_MouseState, m_MouseButtons, MAX_BUTTONS);
}
void InputManager::ClearKeys()
{
for (int i = 0; i < MAX_KEYS; i++)
{
m_KeyState[i] = false;
m_LastKeyState[i] = false;
}
m_KeyModifiers = 0;
}
void InputManager::ClearMouseButtons()
{
for (int i = 0; i < MAX_BUTTONS; i++)
{
m_MouseButtons[i] = false;
m_MouseState[i] = false;
m_MouseClicked[i] = false;
}
}
bool InputManager::IsKeyPressed(uint keycode) const
{
// TODO: Log this!
if (keycode >= MAX_KEYS)
return false;
return m_KeyState[keycode];
}
bool InputManager::IsMouseButtonPressed(uint button) const
{
// TODO: Log this!
if (button >= MAX_BUTTONS)
return false;
return m_MouseButtons[button];
}
bool InputManager::IsMouseButtonClicked(uint button) const
{
// TODO: Log this!
if (button >= MAX_BUTTONS)
return false;
return m_MouseClicked[button];
}
const maths::vec2& InputManager::GetMousePosition() const
{
return m_MousePosition;
}
const bool InputManager::IsMouseGrabbed() const
{
return m_MouseGrabbed;
}
void InputManager::SetMouseGrabbed(bool grabbed)
{
m_MouseGrabbed = grabbed;
}
} | 1,574 | 696 |
struct FDSDrive {
auto clock() -> void;
auto change() -> void;
auto powerup() -> void;
auto rewind() -> void;
auto advance() -> void;
auto crc(uint8 data) -> void;
auto read() -> void;
auto write() -> void;
auto read(uint16 address, uint8 data) -> uint8;
auto write(uint16 address, uint8 data) -> void;
//serialization.cpp
auto serialize(serializer&) -> void;
uint1 enable;
uint1 power;
uint1 changing;
uint1 ready;
uint1 scan;
uint1 rewinding;
uint1 scanning;
uint1 reading; //0 = writing
uint1 writeCRC;
uint1 clearCRC;
uint1 irq;
uint1 pending;
uint1 available;
uint32 counter;
uint32 offset;
uint1 gap;
uint8 data;
uint1 completed;
uint16 crc16;
};
| 734 | 270 |
#ifdef CH_LANG_CC
/*
* _______ __
* / ___/ / ___ __ _ / / ___
* / /__/ _ \/ _ \/ V \/ _ \/ _ \
* \___/_//_/\___/_/_/_/_.__/\___/
* Please refer to Copyright.txt, in Chombo's root directory.
*/
#endif
#include <iostream>
using std::endl;
#include "BRMeshRefine.H"
#include "LoadBalance.H"
#include "CH_HDF5.H"
#include "parstream.H"
#include "BoxIterator.H"
#include "FABView.H"
#include "NewPoissonOp.H"
#include "AMRPoissonOp.H"
#include "BCFunc.H"
#include "BiCGStabSolver.H"
#include "RelaxSolver.H"
#include "UsingNamespace.H"
/// Global variables for handling output:
static const char* pgmname = "testBiCGStab" ;
static const char* indent = " ";
static const char* indent2 = " " ;
static bool verbose = true ;
///
// Parse the standard test options (-v -q) out of the command line.
///
void
parseTestOptions( int argc ,char* argv[] )
{
for ( int i = 1 ; i < argc ; ++i )
{
if ( argv[i][0] == '-' ) //if it is an option
{
// compare 3 chars to differentiate -x from -xx
if ( strncmp( argv[i] ,"-v" ,3 ) == 0 )
{
verbose = true ;
// argv[i] = "" ;
}
else if ( strncmp( argv[i] ,"-q" ,3 ) == 0 )
{
verbose = false ;
// argv[i] = "" ;
}
}
}
return ;
}
// u = x*x + y*y + z*z
// du/dx = 2*x
// du/dy = 2*y
// du/dz = 2*z
// Laplace(u) = 2*CH_SPACEDIM
// #define __USE_GNU
// #include <fenv.h>
// #undef __USE_GNU
//static Box domain = Box(IntVect(D_DECL(-64,-64,-64)), IntVect(D_DECL(63,63,63)));
static Box domain = Box(IntVect(D_DECL(0,0,0)), IntVect(D_DECL(63,63,63)));
static Real dx = 0.0125;
static int blockingFactor = 8;
static Real xshift = 0.0;
int
testBiCGStab();
int
main(int argc ,char* argv[])
{
#ifdef CH_MPI
MPI_Init (&argc, &argv);
#endif
// int except = FE_DIVBYZERO | FE_UNDERFLOW | FE_OVERFLOW | FE_INVALID ;
// feenableexcept(except);
parseTestOptions( argc ,argv ) ;
if ( verbose )
pout () << indent2 << "Beginning " << pgmname << " ..." << endl ;
int overallStatus = 0;
int status = testBiCGStab();
if ( status == 0 )
{
pout() << indent << pgmname << " passed." << endl ;
}
else
{
overallStatus = 1;
pout() << indent << pgmname << " failed with return code " << status << endl ;
}
xshift = 0.2;
blockingFactor = 4;
status = testBiCGStab();
if ( status == 0 )
{
pout() << indent << pgmname << " passed." << endl ;
}
else
{
overallStatus = 1;
pout() << indent << pgmname << " failed with return code " << status << endl ;
}
#ifdef CH_MPI
MPI_Finalize ();
#endif
return overallStatus;
}
extern "C"
{
void Parabola_neum(Real* pos,
int* dir,
Side::LoHiSide* side,
Real* a_values)
{
switch (*dir)
{
case 0:
a_values[0]=2.*(pos[0]-xshift);
return;
case 1:
a_values[0]=2.*pos[1];
return;
case 2:
a_values[0]=2.*pos[2];
return;
default:
MayDay::Error("no such dimension");
};
}
void Parabola_diri(Real* pos,
int* dir,
Side::LoHiSide* side,
Real* a_values)
{
a_values[0] = D_TERM((pos[0]-xshift)*(pos[0]-xshift),+pos[1]*pos[1],+pos[2]*pos[2]);
}
void DirParabolaBC(FArrayBox& a_state,
const Box& valid,
const ProblemDomain& a_domain,
Real a_dx,
bool a_homogeneous)
{
for (int i=0; i<CH_SPACEDIM; ++i)
{
DiriBC(a_state,
valid,
dx,
a_homogeneous,
Parabola_diri,
i,
Side::Lo);
DiriBC(a_state,
valid,
dx,
a_homogeneous,
Parabola_diri,
i,
Side::Hi);
}
}
void NeumParabolaBC(FArrayBox& a_state,
const ProblemDomain& a_domain,
Real a_dx,
bool a_homogeneous)
{
Box valid = a_state.box();
valid.grow(-1);
for (int i=0; i<CH_SPACEDIM; ++i)
{
NeumBC(a_state,
valid,
dx,
a_homogeneous,
Parabola_neum,
i,
Side::Lo);
NeumBC(a_state,
valid,
dx,
a_homogeneous,
Parabola_neum,
i,
Side::Hi);
}
}
}
static BCValueFunc pointFunc = Parabola_diri;
void parabola(const Box& box, int comps, FArrayBox& t)
{
RealVect pos;
Side::LoHiSide side;
int dir;
int num = 1;
ForAllXBNN(Real,t, box, 0, comps)
{
num=nR;
D_TERM(pos[0]=dx*(iR+0.5);, pos[1]=dx*(jR+0.5);, pos[2]=dx*(kR+0.5));
pointFunc(&(pos[0]), &dir, &side, &tR);
}EndFor;
}
void makeGrids(DisjointBoxLayout& a_dbl, const Box& a_domain)
{
BRMeshRefine br;
Box domain = a_domain;
domain.coarsen(blockingFactor);
domain.refine(blockingFactor);
CH_assert(domain == a_domain);
domain.coarsen(blockingFactor);
ProblemDomain junk(domain);
IntVectSet pnd(domain);
IntVectSet tags;
for (BoxIterator bit(domain); bit.ok(); ++bit)
{
const IntVect& iv = bit();
if (D_TERM(true, && iv[1]< 2*iv[0] && iv[1]>iv[0]/2, && iv[2] < domain.bigEnd(2)/2))
{
tags|=iv;
}
}
Vector<Box> boxes;
br.makeBoxes(boxes, tags, pnd, junk, 32/blockingFactor, 1);
Vector<int> procs;
LoadBalance(procs, boxes);
for (int i=0; i<boxes.size(); ++i) boxes[i].refine(blockingFactor);
a_dbl.define(boxes, procs);
}
struct setvalue
{
static Real val;
static void setFunc(const Box& box,
int comps, FArrayBox& t)
{
t.setVal(val);
}
};
Real setvalue::val = 0;
int
testBiCGStab()
{
ProblemDomain regularDomain(domain);
pout()<<"\n GSRB unigrid solver \n";
// GSRB single grid solver test
{
Box phiBox = domain;
phiBox.grow(1);
FArrayBox phi(phiBox, 1);
FArrayBox rhs(domain, 1);
FArrayBox error(domain, 1);
FArrayBox phi_exact(domain, 1);
FArrayBox residual(domain, 1);
FArrayBox correction(phiBox, 1);
phi.setVal(0.0);
correction.setVal(0.0);
rhs.setVal(2*CH_SPACEDIM);
parabola(domain, 1, phi_exact);
RealVect pos(IntVect::Unit);
pos*=dx;
NewPoissonOp op;
op.define(pos, regularDomain, DirParabolaBC);
for (int i=0; i<15; ++i)
{
op.residual(residual, phi, rhs);
Real rnorm = residual.norm();
op.preCond(correction, residual);
op.incr(phi, correction, 1.0);
op.axby(error, phi, phi_exact, 1, -1);
Real norm = error.norm(0);
pout()<<indent<<"Residual L2 norm "<<rnorm<<" Error max norm = "
<<norm<<std::endl;
}
}
pout()<<"\n unigrid solver \n";
// single grid solver test
{
Box phiBox = domain;
phiBox.grow(1);
FArrayBox phi(phiBox, 1);
FArrayBox rhs(domain, 1);
FArrayBox error(domain, 1);
FArrayBox phi_exact(domain, 1);
FArrayBox residual(domain, 1);
FArrayBox correction(phiBox, 1);
phi.setVal(0.0);
rhs.setVal(2*CH_SPACEDIM);
parabola(domain, 1, phi_exact);
RealVect pos(IntVect::Unit);
pos*=dx;
NewPoissonOp op;
op.define(pos, regularDomain, DirParabolaBC);
BiCGStabSolver<FArrayBox> solver;
solver.define(&op, true);
int iter = 1;
pout()<< "homogeneous solver mode : solver.solve(correction, reisdual)\n"
<< "solver.i_max= "<<solver.m_imax<<" iter = "<<iter<<std::endl;
op.residual(residual, phi, rhs);
Real rnorm = residual.norm();
pout()<<"initial residual "<<rnorm<<"\n";
for (int i=0; i<iter; ++i)
{
correction.setVal(0.0);
solver.solve(correction, residual);
op.incr(phi, correction, 1);
op.residual(residual, phi, rhs);
rnorm = residual.norm();
op.axby(error, phi, phi_exact, 1, -1);
Real norm = error.norm(0);
pout()<<indent<<"residual L2 norm "<< rnorm
<<" Error max norm = "<<norm<<std::endl;
}
pout()<< "\n\n inhomogeneous solver mode : solver.solve(a_phi, a_rhs)\n"<<std::endl;
solver.setHomogeneous(false);
op.scale(phi, 0.0);
op.residual(residual, phi, rhs);
rnorm = residual.norm();
pout()<<"initial residual "<<rnorm<<"\n";
for (int i=0; i<iter; ++i)
{
solver.solve(phi, rhs);
op.residual(residual, phi, rhs);
rnorm = residual.norm();
op.axby(error, phi, phi_exact, 1, -1);
Real norm = error.norm(0);
pout()<<indent<<" residual L2 norm "<< rnorm
<<" Error max norm = "<<norm<<std::endl;
}
}
pout()<<"\n level solver \n";
// Level solve
{
DisjointBoxLayout dbl;
makeGrids(dbl, domain);
dbl.close();
DataIterator dit(dbl);
LevelData<FArrayBox> phi(dbl, 1, IntVect::Unit);
LevelData<FArrayBox> correction(dbl, 1, IntVect::Unit);
LevelData<FArrayBox> phi_exact(dbl, 1);
LevelData<FArrayBox> error(dbl, 1);
LevelData<FArrayBox> rhs(dbl, 1);
LevelData<FArrayBox> residual(dbl, 1);
setvalue::val = 2*CH_SPACEDIM;
rhs.apply(setvalue::setFunc);
setvalue::val = 0;
phi.apply(setvalue::setFunc);
phi_exact.apply(parabola);
RealVect pos(IntVect::Unit);
pos*=dx;
AMRPoissonOp amrop;
amrop.define(dbl, pos[0], regularDomain, DirParabolaBC);
BiCGStabSolver<LevelData<FArrayBox> > bsolver;
RelaxSolver<LevelData<FArrayBox> > rsolver;
bsolver.define(&amrop, true);
rsolver.define(&amrop, true);
int iter = 1;
amrop.scale(phi, 0.0);
amrop.axby(error, phi, phi_exact, 1, -1);
amrop.residual(residual, phi, rhs, false);
Real rnorm = amrop.norm(residual, 2);
Real enorm = amrop.norm(error, 0);
pout()<< "homogeneous solver mode : solver.solve(correction, residual)\n"
<< "solver.i_max= "<<bsolver.m_imax<<" iter = "<<iter<<std::endl;
pout()<<"\nInitial residual norm "<<rnorm<<" Error max norm "<<enorm<<"\n\n";
pout()<<indent2<<"BiCGStab\n";
for (int i=0; i<iter; ++i)
{
amrop.scale(correction, 0.0);
bsolver.solve(correction, residual);
amrop.incr(phi, correction, 1.0);
amrop.axby(error, phi, phi_exact, 1, -1);
amrop.residual(residual, phi, rhs, false);
rnorm = amrop.norm(residual, 2);
enorm = amrop.norm(error, 0);
pout()<<indent<<"residual norm "<<rnorm<<" Error max norm = "<<enorm<<std::endl;
}
amrop.scale(phi, 0.0);
amrop.residual(residual, phi, rhs, false);
pout()<<indent2<<"RelaxSolver\n";
for (int i=0; i<iter; ++i)
{
amrop.scale(correction, 0.0);
rsolver.solve(correction, residual);
amrop.incr(phi, correction, 1.0);
amrop.axby(error, phi, phi_exact, 1, -1);
amrop.residual(residual, phi, rhs, false);
rnorm = amrop.norm(residual, 2);
enorm = amrop.norm(error, 0);
pout()<<indent<<"residual norm "<<rnorm<<" Error max norm = "<<enorm<<std::endl;
}
pout()<< "\n\ninhomogeneous solver mode : solver.solve(phi, rhs)\n"
<< "solver.i_max= "<<bsolver.m_imax<<" iter = "<<iter<<std::endl;
bsolver.setHomogeneous(false);
rsolver.setHomogeneous(false);
amrop.scale(phi, 0.0);
amrop.residual(residual, phi, rhs, false);
pout()<<indent2<<"BiCGStab\n";
for (int i=0; i<iter; ++i)
{
bsolver.solve(phi, rhs);
amrop.axby(error, phi, phi_exact, 1, -1);
amrop.residual(residual, phi, rhs, false);
rnorm = amrop.norm(residual, 2);
enorm = amrop.norm(error, 0);
pout()<<indent<<"residual norm "<<rnorm<<" Error max norm = "<<enorm<<std::endl;
}
amrop.scale(phi, 0.0);
amrop.residual(residual, phi, rhs, false);
pout()<<indent2<<"RelaxSolver\n";
for (int i=0; i<iter; ++i)
{
rsolver.solve(phi, rhs);
amrop.axby(error, phi, phi_exact, 1, -1);
amrop.residual(residual, phi, rhs, false);
rnorm = amrop.norm(residual, 2);
enorm = amrop.norm(error, 0);
pout()<<indent<<"residual norm "<<rnorm<<" Error max norm = "<<enorm<<std::endl;
}
}
return 0;
}
| 12,441 | 4,980 |
#include "schoolMember.h"
SchoolMember::SchoolMember(unsigned short id, std::string name, std::string currentCourse)
: id_(id),
name_(name),
currentCourse_(currentCourse)
{}
SchoolMember::~SchoolMember()
{}
unsigned short SchoolMember::getId() const
{
return this->id_;
}
std::string SchoolMember::getName() const
{
return this->name_;
}
std::string SchoolMember::getCurrentCourse() const
{
return this->currentCourse_;
} | 434 | 146 |
#include "nau/render/opengl/glMaterialGroup.h"
#include "nau/render/opengl/glIndexArray.h"
#include "nau/render/opengl/glVertexArray.h"
#include <glbinding/gl/gl.h>
using namespace gl;
//#include <GL/glew.h>
using namespace nau::render::opengl;
GLMaterialGroup::GLMaterialGroup(IRenderable *parent, std::string materialName) :
MaterialGroup(parent, materialName),
m_VAO(0) {
}
GLMaterialGroup::~GLMaterialGroup() {
if (m_VAO)
glDeleteVertexArrays(1, &m_VAO);
}
void
GLMaterialGroup::compile() {
if (m_VAO)
return;
std::shared_ptr<VertexData> &v = m_Parent->getVertexData();
if (!v->isCompiled())
v->compile();
if (!m_IndexData->isCompiled())
m_IndexData->compile();
glGenVertexArrays(1, &m_VAO);
glBindVertexArray(m_VAO);
v->bind();
m_IndexData->bind();
glBindVertexArray(0);
v->unbind();
m_IndexData->unbind();
}
void
GLMaterialGroup::resetCompilationFlag() {
if (!m_VAO)
return;
glDeleteVertexArrays(1, &m_VAO);
m_VAO = 0;
std::shared_ptr<VertexData> &v = m_Parent->getVertexData();
v->resetCompilationFlag();
m_IndexData->resetCompilationFlag();
}
bool
GLMaterialGroup::isCompiled() {
return (m_VAO != 0);
}
void
GLMaterialGroup::bind() {
glBindVertexArray(m_VAO);
}
void
GLMaterialGroup::unbind() {
glBindVertexArray(0);
}
unsigned int
GLMaterialGroup::getVAO() {
return m_VAO;
} | 1,354 | 564 |
#include "headers/Game.hpp"
#include <stdlib.h>
#include <algorithm>
#include <list>
#include <iostream>
#include <string>
#include <sstream>
namespace engine {
Game* Game::gGame = NULL;
engine::Level* Game::gLevel = NULL;
engine::GameObjectList Game::gObjects = engine::GameObjectList();
sf::Clock Game::gFrameClock = sf::Clock();
sf::Clock Game::gPhysicsClock = sf::Clock();
sf::Uint16 Game::gPixelMeters = 75;
Game::Game(const std::string title) {
mWindowTitle = title;
mWindow.create(sf::VideoMode(1920, 1080), mWindowTitle);
mWindow.setFramerateLimit(60);
mUpdateRate = 1.0f / 20.0f;
mPhysicsUpdateRate = 1.0f / 300000.0f;
mMaxUpdates = 5;
mMaxPhysicsUpdates = 5000;
gGame = this;
}
Game::~Game() {
// mWindowTitle.~string();
// gObjects.~GameObjectList();
// gFrameClock.~Clock();
// gPhysicsClock.~Clock();
gGame = NULL;
}
int Game::run(void) {
this->GameLoop();
return 0;
}
void Game::GameLoop(void) {
bool lc = false;
bool collision = false;
bool collisionDown = false;
bool collisionUp = false;
bool collisionRight = false;
bool collisionLeft = false;
sf::Event event;
sf::Clock anUpdateClock;
sf::Clock anPhysicsUpdateClock;
sf::Clock anSecondCounter;
anUpdateClock.restart();
anPhysicsUpdateClock.restart();
anSecondCounter.restart();
// When do we need to update next (in milliseconds)?
sf::Int32 anUpdateNext = anUpdateClock.getElapsedTime().asMilliseconds();
sf::Int32 anPhysicsUpdateNext = anPhysicsUpdateClock.getElapsedTime().asMilliseconds();
// game Stats
int FPS = 0;
sf::Uint32 frames = 0;
sf::Font textFont;
textFont.loadFromFile("src/fonts/arial.ttf");
sf::Text textPS("FPS: ", textFont);
// sf::Text textVel("Velocity: <0.0, 0.0>", textFont);
// sf::Text textPos("Position: (0.0, 0.0)", textFont);
textPS.setFont(textFont);
textPS.setCharacterSize(64);
textPS.setStyle(sf::Text::Bold);
textPS.setFillColor(sf::Color::White);
// textVel.setFont(textFont);
// textVel.setCharacterSize(64);
// textVel.setStyle(sf::Text::Bold);
// textVel.setFillColor(sf::Color::White);
// textPos.setFont(textFont);
// textPos.setCharacterSize(64);
// textPos.setStyle(sf::Text::Bold);
// textPos.setFillColor(sf::Color::White);
engine::RectangleCollider2D* rect2D = NULL;
engine::CircleCollider2D* circle2D = NULL;
engine::PolygonCollider2D* poly2D = NULL;
// run window loop
while (mWindow.isOpen()) {
mWindow.clear(); // sf::Color::Green
sf::Uint32 anUpdates = 0;
sf::Uint32 anPhysicsUpdates = 0;
while (mWindow.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
mWindow.close();
} else if (event.type == sf::Event::KeyPressed) {
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)) {
mWindow.close();
}
}
}
sf::Int32 anUpdateTime = anUpdateClock.getElapsedTime().asMilliseconds();
sf::Int32 anPhysicsUpdateTime = anPhysicsUpdateClock.getElapsedTime().asMilliseconds();
if (gLevel != NULL) {
GameObjectList gObjs = gLevel->getGameObjects();
if (!lc){
printf("Running all level things\n");
lc = true;
}
// run physics updates
while((anPhysicsUpdateTime - anPhysicsUpdateNext) >= mPhysicsUpdateRate && anPhysicsUpdates++ < mMaxPhysicsUpdates) {
gPhysicsClock.restart(); // reset clock before loop resets or ends
for (engine::GameObject* gm : gObjs) {
collision = false;
collisionDown = false;
collisionUp = false;
collisionRight = false;
collisionLeft = false;
rect2D = NULL;
circle2D = NULL;
poly2D = NULL;
if (gm->getCollider2D() != NULL) {
for (engine::GameObject* ogm : gObjs) {
if (gm == ogm || !ogm->getCollider2D()) continue;
if ((rect2D = dynamic_cast<engine::RectangleCollider2D*>(ogm->getCollider2D()))) collision = gm->getCollider2D()->intersects(rect2D);
else if ((circle2D = dynamic_cast<engine::CircleCollider2D*>(ogm->getCollider2D()))) collision = gm->getCollider2D()->intersects(circle2D);
else if ((poly2D = dynamic_cast<engine::PolygonCollider2D*>(ogm->getCollider2D()))) collision = gm->getCollider2D()->intersects(poly2D);
else collision = gm->getCollider2D()->intersects(ogm->getCollider2D());
collisionDown = collisionDown || (collision && gm->getPosition().y < ogm->getPosition().y);
collisionUp = (collision && gm->getPosition().y > ogm->getPosition().y);
collisionRight = (collision && !collisionDown && gm->getPosition().x < ogm->getPosition().x);
collisionLeft = (collision && !collisionDown && gm->getPosition().x > ogm->getPosition().x);
if (collision) {
gm->onCollision(ogm->getCollider2D());
if (rect2D) gm->onCollision(rect2D);
if (!gm->getCollider2D()->hasCollision(ogm->getCollider2D())) {
gm->onCollisionEnter(ogm->getCollider2D());
// if ()
gm->getCollider2D()->addCollision(ogm->getCollider2D());
}
} else if (!collision && gm->getCollider2D()->hasCollision(ogm->getCollider2D())) {
gm->onCollisionExit(ogm->getCollider2D());
gm->getCollider2D()->removeCollision(ogm->getCollider2D());
}
}
}
engine::Physics2D* p2d = gm->getPhysics();
sf::Vector2f velocity = p2d->getVelocity();
if (!collisionDown) {
if (p2d->hasGravity()) {
p2d->addForce(sf::Vector2f(0.0f, (G_C * 2 * DeltaPhysicsTime())));
}
velocity = p2d->getVelocity();
if (velocity.y > 0.0f) {
gm->move(0.0f, p2d->deltaV().y * gPixelMeters);
}
} else {
if (velocity.x > 0.0f) {
p2d->addForce(sf::Vector2f(-6 * (velocity.x) * DeltaPhysicsTime(), 0.0f)); // * DeltaPhysicsTime()
}
velocity = p2d->getVelocity();
if (velocity.x < 0.0f) {
p2d->addForce(sf::Vector2f(-6 * (velocity.x) * DeltaPhysicsTime(), 0.0f)); // * DeltaPhysicsTime()
}
}
velocity = p2d->getVelocity();
if (!collisionUp && velocity.y < 0) {
gm->move(0.0f, p2d->deltaV().y * gPixelMeters);
}
if (!collisionRight && velocity.x > 0) {
gm->move(p2d->deltaV().x * gPixelMeters, 0.0f);
}
if (!collisionLeft && velocity.x < 0) {
gm->move(p2d->deltaV().x * gPixelMeters, 0.0f);
}
velocity = p2d->getVelocity();
if (collisionDown && velocity.y > 0.0f) {
// gm->move(0.0f, p2d->deltaV().y * -gPixelMeters);
// printf("reseting vertical velocity\n");
p2d->addForce(sf::Vector2f(0, -1 * velocity.y));
}
velocity = p2d->getVelocity();
if (collisionUp && velocity.y < 0.0f){
p2d->addForce(sf::Vector2f(0, -1 * velocity.y));
}
velocity = p2d->getVelocity();
if (collisionRight && velocity.x > 0.0f && !collisionDown && !collisionUp) {
printf("reseting horizontal velocity\n");
p2d->addForce(sf::Vector2f(-1 * velocity.x, 0));
}
velocity = p2d->getVelocity();
if (collisionLeft && velocity.x < 0.0f && !collisionDown && !collisionUp) {
printf("reseting horizontal velocity\n");
p2d->addForce(sf::Vector2f(-1 * velocity.x, 0));
}
}
}
// printf("P2d Updates: %d\n", anPhysicsUpdates);
// run fixed updates
while((anUpdateTime - anUpdateNext) >= mUpdateRate && anUpdates++ < mMaxUpdates) {
for (engine::GameObject* gm : gObjs) {
// printf("Fixed Updating GM\n");
gm->fixedUpdate();
}
anUpdateNext += mUpdateRate;
}
for (engine::GameObject* gm : gObjs) {
// printf("Updating gameobject\n");
gm->update();
// printf("Updating gm drawable positions\n");
gm->sprite.setPosition(gm->getPosition());
gm->shape.setPosition(gm->getPosition());
// printf("Drawing gameobject\n");
gm->draw(mWindow);
}
}
if (anSecondCounter.getElapsedTime().asSeconds() > 0.25f) {
// printf("Velocity<%f, %f>\n", p2d->getVelocity().x, p2d->getVelocity().y);
// printf("FPS: %d, DeltaTime: %f\n", , DeltaTime());
// printf("Physics speed: %f\n", DeltaPhysicsTime() * 205000);
FPS = frames * 4;
anSecondCounter.restart();
frames = 0;
}
if (FPS == 0) FPS = 1.0f / DeltaTime();
std::ostringstream tframes;
tframes.precision(2);
tframes.width(7);
tframes << "FPS: " << std::fixed << FPS;
textPS.setString(tframes.str());
// textVel.setString("Velocity: <" + ());
textPS.setPosition(mWindow.getView().getCenter() - sf::Vector2f(970, 500));
// textVel.setPosition(mWindow.getView().getCenter() - sf::Vector2f(940, 430));
// textPos.setPosition(mWindow.getView().getCenter() - sf::Vector2f(940, 360));
mWindow.draw(textPS);
// mWindow.draw(textVel);
// mWindow.draw(textPos);
mWindow.display();
gFrameClock.restart(); // reset FrameClock as the last frame has just been drawn
frames+=1;
}
}
void Game::RunPhysicsUpdates(void) {
}
float Game::DeltaTime(void) {
return gFrameClock.getElapsedTime().asSeconds();
}
float Game::DeltaPhysicsTime(void) {
//return gPhysicsClock.getElapsedTime().asSeconds();//.asMilliseconds() / 1000.0f;
return gGame->mPhysicsUpdateRate;
}
sf::Uint16 Game::GetPixelMeters(void) {
return gPixelMeters;
}
engine::Level* Game::GetLevel(void) {
return gLevel;
}
Game* Game::GetGame(void) {
return gGame;
}
GameObjectList Game::GetGameObjects(void) {
return gObjects;
}
void Game::SetLevel(engine::Level* level) {
gLevel = level;
// gObjects = level->getGameObjects();
}
}
| 10,580 | 3,596 |
#include "strings.h"
std::vector<std::string> Strings::registry_;
const char* Strings::Add(const char* str) { return Add(str, strlen(str)); }
const char* Strings::Add(const char* str, size_t length) {
for (auto& s : registry_) {
if (s.length() == length) {
if (memcmp(s.c_str(), str, length) == 0) {
return s.c_str();
}
}
}
std::string new_str(str, length);
registry_.push_back(new_str);
return registry_.back().c_str();
}
| 466 | 176 |
#include <precompiled.h>
///
/// MIT License
/// Copyright (c) 2018-2019 Jongmin Yun
///
/// 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.
///
/// Header file
#include <Dy/Builtin/ShaderGl/RenderPass.h>
namespace
{
constexpr std::string_view vertexShaderCode = R"dy(
#version 430 core
// Quad
layout (location = 0) in vec3 dyPosition;
layout (location = 1) in vec2 dyTexCoord0;
out gl_PerVertex { vec4 gl_Position; };
out VS_OUT { vec2 texCoord; } vs_out;
void main() {
vs_out.texCoord = dyTexCoord0;
gl_Position = vec4(dyPosition, 1.0);
}
)dy";
constexpr std::string_view fragmentShaderCode = R"dy(
#version 430
in VS_OUT { vec2 texCoord; } fs_in;
layout (location = 0) out vec4 outColor;
uniform sampler2D uUnlit;
uniform sampler2D uNormal;
uniform sampler2D uSpecular;
uniform sampler2D uViewPosition;
vec3 dirLight = normalize(vec3(-1, 1, 0));
vec3 ambientColor = vec3(1);
void main() {
vec4 normalValue = (texture(uNormal, fs_in.texCoord) - 0.5f) * 2.0f;
vec4 unlitValue = texture(uUnlit, fs_in.texCoord);
float ambientFactor = 0.1f;
float diffuseFactor = max(dot(normalValue.xyz, dirLight), 0.1);
outColor = vec4(
vec3(1) * diffuseFactor +
ambientColor * ambientFactor,
1.0f);
}
)dy";
} /// ::unnamed namespace
namespace dy::builtin
{
FDyBuiltinShaderGLRenderPass::FDyBuiltinShaderGLRenderPass()
{
this->mSpecifierName = sName;
this->mVertexBuffer = vertexShaderCode;
this->mPixelBuffer = fragmentShaderCode;
}
} /// ::dy::builtin namespace | 1,939 | 804 |
//
// MainPage.xaml.cpp
// Implementation of the MainPage class.
//
#include "pch.h"
#include "MainPage.xaml.h"
using namespace PrintableTomKitten;
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::Graphics::Printing;
using namespace Windows::Graphics::Printing::OptionDetails;
using namespace Windows::UI;
using namespace Windows::UI::Core;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
using namespace Windows::UI::Xaml::Printing;
MainPage::MainPage()
{
InitializeComponent();
std::array<UIElement^, 57> bookPagesInitialized =
{
ref new TomKitten03(), ref new TomKitten04(), ref new TomKitten05(), ref new TomKitten06(),
ref new TomKitten07(), ref new TomKitten08(), ref new TomKitten09(), ref new TomKitten10(),
ref new TomKitten11(), ref new TomKitten12(), ref new TomKitten13(), ref new TomKitten14(),
ref new TomKitten15(), ref new TomKitten16(), ref new TomKitten17(), ref new TomKitten18(),
ref new TomKitten19(), ref new TomKitten20(), ref new TomKitten21(), ref new TomKitten22(),
ref new TomKitten23(), ref new TomKitten24(), ref new TomKitten25(), ref new TomKitten26(),
ref new TomKitten27(), ref new TomKitten28(), ref new TomKitten29(), ref new TomKitten30(),
ref new TomKitten31(), ref new TomKitten32(), ref new TomKitten33(), ref new TomKitten34(),
ref new TomKitten35(), ref new TomKitten36(), ref new TomKitten37(), ref new TomKitten38(),
ref new TomKitten39(), ref new TomKitten40(), ref new TomKitten41(), ref new TomKitten42(),
ref new TomKitten43(), ref new TomKitten44(), ref new TomKitten45(), ref new TomKitten46(),
ref new TomKitten47(), ref new TomKitten48(), ref new TomKitten49(), ref new TomKitten50(),
ref new TomKitten51(), ref new TomKitten52(), ref new TomKitten53(), ref new TomKitten54(),
ref new TomKitten55(), ref new TomKitten56(), ref new TomKitten57(), ref new TomKitten58(),
ref new TomKitten59()
};
bookPages = bookPagesInitialized;
// Create PrintDocument and attach handlers
printDocument = ref new PrintDocument();
printDocumentSource = printDocument->DocumentSource;
printDocument->Paginate += ref new PaginateEventHandler(this, &MainPage::OnPrintDocumentPaginate);
printDocument->GetPreviewPage += ref new GetPreviewPageEventHandler(this, &MainPage::OnPrintDocumentGetPreviewPage);
printDocument->AddPages += ref new AddPagesEventHandler(this, &MainPage::OnPrintDocumentAddPages);
}
void MainPage::OnNavigatedTo(NavigationEventArgs^ args)
{
// Attach PrintManager handler
PrintManager^ printManager = PrintManager::GetForCurrentView();
printTaskRequestedEventToken = printManager->PrintTaskRequested += ref new TypedEventHandler<PrintManager^, PrintTaskRequestedEventArgs^>(this, &MainPage::OnPrintManagerPrintTaskRequested);
}
void MainPage::OnNavigatedFrom(NavigationEventArgs^ args)
{
// Detach PrintManager handler
PrintManager::GetForCurrentView()->PrintTaskRequested -= printTaskRequestedEventToken;
}
void MainPage::OnPrintManagerPrintTaskRequested(PrintManager^ sender, PrintTaskRequestedEventArgs^ args)
{
PrintTask^ printTask = args->Request->CreatePrintTask("Hello Printer",
ref new PrintTaskSourceRequestedHandler(this, &MainPage::OnPrintTaskSourceRequested));
// Get PrintTaskOptionDetails for making changing to options
PrintTaskOptionDetails^ optionDetails = PrintTaskOptionDetails::GetFromPrintTaskOptions(printTask->Options);
// Create the custom item
PrintCustomItemListOptionDetails^ pageRange = optionDetails->CreateItemListOption("idPrintRange", "Print range");
pageRange->AddItem("idPrintAll", "Print all pages");
pageRange->AddItem("idPrintCustom", "Print custom range");
// Add it to the options
optionDetails->DisplayedOptions->Append("idPrintRange");
// Create a page-range edit item also, but this only
// comes into play when user select "Print custom range"
optionDetails->CreateTextOption("idCustomRangeEdit", "Custom Range");
// Set a handler for the OptionChanged event
optionDetails->OptionChanged += ref new TypedEventHandler<PrintTaskOptionDetails^, PrintTaskOptionChangedEventArgs^>(this, &MainPage::OnOptionDetailsOptionChanged);
}
void MainPage::OnPrintTaskSourceRequested(PrintTaskSourceRequestedArgs^ args)
{
args->SetSource(printDocumentSource);
}
void MainPage::OnOptionDetailsOptionChanged(PrintTaskOptionDetails^ sender, PrintTaskOptionChangedEventArgs^ args)
{
if (args->OptionId == nullptr)
return;
String^ optionId = dynamic_cast<String^>(args->OptionId);
String^ strValue = sender->Options->Lookup(optionId)->Value->ToString();
String^ errorText = "";
if (optionId == "idPrintRange")
{
if (strValue == "idPrintAll")
{
unsigned int index = 0;
if (sender->DisplayedOptions->IndexOf("idCustomRangeEdit", &index))
sender->DisplayedOptions->RemoveAt(index);
}
else if (strValue == "idPrintCustom")
{
sender->DisplayedOptions->Append("idCustomRangeEdit");
}
}
else if (optionId == "idCustomRangeEdit")
{
// Check to see if CustomPageRange accepts this
CustomPageRange^ pageRange = ref new CustomPageRange(strValue, bookPages.size());
if (!pageRange->IsValid)
{
errorText = "Use the form 2-4, 7, 9-11";
}
}
sender->Options->Lookup(optionId)->ErrorText = errorText;
// If there's no error, then invalidate the preview
if (errorText == "")
{
this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler(
[this]()
{
printDocument->InvalidatePreview();
}));
}
}
void MainPage::OnPrintDocumentPaginate(Object^ sender, PaginateEventArgs^ args)
{
// Obtain the print range option
PrintTaskOptionDetails^ optionDetails = PrintTaskOptionDetails::GetFromPrintTaskOptions(args->PrintTaskOptions);
String^ strValue = dynamic_cast<String^>(optionDetails->Options->Lookup("idPrintRange")->Value);
if (strValue == "idPrintCustom")
{
// Parse the print range for GetPreviewPage and AddPages
String^ strPageRange = dynamic_cast<String^>(optionDetails->Options->Lookup("idCustomRangeEdit")->Value);
customPageRange = ref new CustomPageRange(strPageRange, bookPages.size());
}
else
{
// Make sure field is null if printing all pages
customPageRange = nullptr;
}
int pageCount = bookPages.size();
if (customPageRange != nullptr && customPageRange->IsValid)
pageCount = customPageRange->PageMapping->Size;
printDocument->SetPreviewPageCount(pageCount, PreviewPageCountType::Final);
}
void MainPage::OnPrintDocumentGetPreviewPage(Object^ sender, GetPreviewPageEventArgs^ args)
{
int oneBasedIndex = args->PageNumber;
if (customPageRange != nullptr && customPageRange->IsValid)
oneBasedIndex = customPageRange->PageMapping->GetAt(args->PageNumber - 1);
printDocument->SetPreviewPage(args->PageNumber, bookPages[oneBasedIndex - 1]);
}
void MainPage::OnPrintDocumentAddPages(Object^ sender, AddPagesEventArgs^ args)
{
if (customPageRange != nullptr && customPageRange->IsValid)
{
for (unsigned int index = 0; index < customPageRange->PageMapping->Size; index++)
printDocument->AddPage(bookPages[customPageRange->PageMapping->GetAt(index) - 1]);
}
else
{
for (unsigned int index = 0; index < bookPages.size(); index++)
printDocument->AddPage(bookPages[index]);
}
printDocument->AddPagesComplete();
}
| 8,305 | 2,398 |
/////////////////////////////////////////////////////////////
// //
// Copyright (c) 2003-2017 by The University of Queensland //
// Centre for Geoscience Computing //
// http://earth.uq.edu.au/centre-geoscience-computing //
// //
// Primary Business: Brisbane, Queensland, Australia //
// Licensed under the Open Software License version 3.0 //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
/////////////////////////////////////////////////////////////
#include "BCorner2DInteraction.h"
// -- Project includes --
#include "Foundation/vec3.h"
#include "tml/message/packed_message_interface.h"
#include "console.h"
/*!
default constructor
*/
BCorner2DInteraction::BCorner2DInteraction()
{
m_p=NULL;
m_corner=NULL;
m_pid=-1;
m_cid=-1;
}
/*!
constructor with parameters
\param p a pointer to the particle
\param c a pointer to the corner
\param param the interaction parameters
\param iflag
*/
BCorner2DInteraction::BCorner2DInteraction(CParticle* p,Corner2D* c,BMesh2DIP param,bool iflag)
{
m_p=p;
m_corner=c;
m_k=param.k;
m_break=param.brk*m_p->getRad();
// setup anchor point coefficients
int m_ne=m_corner->getNEdges();
if (m_ne==1){ // single edge case
console.Critical() << "Signle Edge Case not implemented\n";
} else if (m_ne==2){ // two edge (normal) case
Vec3 n1=m_corner->getEdgeNormal(1);
Vec3 n2=m_corner->getEdgeNormal(2);
Vec3 p=m_p->getPos()-m_corner->getPos();
k1=(n2.Y()*p.X()-n2.X()*p.Y())/(n1.X()*n2.Y()-n1.Y()*n2.X());
k2=(n1.Y()*p.X()-n1.X()*p.Y())/(n2.X()*n1.Y()-n2.Y()*n1.X());
// check
Vec3 check=k1*n1+k2*n2;
console.XDebug() << "BCorner2DInteraction check: " << check-p << "\n";
// cout << "BCorner2DInteraction check: n1,n2,p,k1,k2 [" << n1 << "] [" << n2 << "] [" << p << "] , " << k1 << " , " << k2 << " [" << check-p<< "]\n";
} else {
console.Critical() << "ERROR: Corner appears to have 0 Edges\n";
}
m_dist=0.0; // inital distance is always 0.0 !
m_pid=m_p->getID();
m_cid=m_corner->getID();
}
/*!
calculate & apply forces
*/
void BCorner2DInteraction::calcForces()
{
// get number of adjacent edges
int m_ne=m_corner->getNEdges();
// transform anchor point to world coords
Vec3 ap_global;
if(m_ne==1){
} else if (m_ne==2){
ap_global=m_corner->getPos()+k1*m_corner->getEdgeNormal(1)+k2*m_corner->getEdgeNormal(2);
}
// get dist between anchor and particle
const Vec3 D=ap_global-m_p->getPos();
m_dist=sqrt(D*D);
// calc force
Vec3 force=D*m_k;
Vec3 pos=m_p->getPos();
// apply force
m_p->applyForce(force,pos);
if(m_ne==1){
} else if (m_ne==2){
Vec3 hf=force*(-0.5);
m_corner->applyForceToEdge(1,hf);
m_corner->applyForceToEdge(2,hf);
}
}
/*!
return if the interaction is broken, i.e. the distance between
particle and anchor point exceeds breaking distance, i.e. relative
breaking distance x particle readius
*/
bool BCorner2DInteraction::broken()
{
return (m_dist>m_break);
}
/*!
Pack a BCorner2DInteraction into a TML packed message
\param I the interaction
*/
template<>
void TML_PackedMessageInterface::pack<BCorner2DInteraction>(const BCorner2DInteraction& I)
{
append(I.m_k);
append(I.m_dist);
append(I.m_break);
append(I.k1);
append(I.k2);
append(I.getCid());
append(I.getPid());
}
/*!
Unpack a BCorner2DInteraction from a TML packed message
\param I the interaction
*/
template<>
void TML_PackedMessageInterface::unpack<BCorner2DInteraction>(BCorner2DInteraction& I)
{
I.m_k=pop_double();
I.m_dist=pop_double();
I.m_break=pop_double();
I.k1=pop_double();
I.k2=pop_double();
I.m_cid=pop_int();
I.m_pid=pop_int();
}
| 3,886 | 1,517 |
// Copyright (C) 2019 The Regents of the University of California (Regents).
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of The Regents or University of California nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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.
//
// Please contact the author of this library if you have any questions.
// Author: Victor Fragoso (victor.fragoso@mail.wvu.edu)
#include "theia/io/read_calibration.h"
#include <glog/logging.h>
#include <stdio.h>
#include <string>
#include <unordered_map>
#include <vector>
#include <cereal/external/rapidjson/document.h>
#include <stlplus3/file_system.hpp>
#include "theia/sfm/camera/camera_intrinsics_model_type.h"
#include "theia/sfm/camera_intrinsics_prior.h"
namespace theia {
namespace {
static const char* kPinholeType = "PINHOLE";
static const char* kPriorsEntry = "priors";
static const char* kCameraIntrinsicsPrior = "CameraIntrinsicsPrior";
static const char* kImageName = "image_name";
static const char* kCameraType = "camera_intrinsics_type";
// Pinhole camera parameters.
static const char* kFocalLength = "focal_length";
static const char* kImageWidth = "width";
static const char* kImageHeight = "height";
static const char* kPrincipalPoint = "principal_point";
static const char* kAspectRatio = "aspect_ratio";
static const char* kSkew = "skew";
static const char* kRadialDistortionCoeffs = "radial_distortion_coeffs";
static const char* kTangentialDistortionCoeffs = "tangential_distortion_coeffs";
static const char* kPosition = "position";
static const char* kOrientation = "orientation";
static const char* kLatitude = "latitude";
static const char* kLongitude = "longitude";
static const char* kAltitude = "altitude";
bool ExtractPriorParameters(const cereal::rapidjson::Value& entry,
CameraIntrinsicsPrior* prior) {
// Get the focal length.
if (entry.HasMember(kFocalLength)) {
prior->focal_length.is_set = true;
prior->focal_length.value[0] = entry[kFocalLength].GetDouble();
}
// Get the principal points.
if (entry.HasMember(kPrincipalPoint) && entry[kPrincipalPoint].IsArray()) {
const int num_entries =
std::min(static_cast<int>(entry[kPrincipalPoint].Size()), 2);
bool all_doubles = true;
for (int i = 0; i < num_entries; ++i) {
bool is_double = entry[kPrincipalPoint][i].IsDouble() ||
entry[kPrincipalPoint][i].IsInt();
if (is_double) {
prior->principal_point.value[i] = entry[kPrincipalPoint][i].GetDouble();
}
all_doubles = all_doubles && is_double;
}
prior->principal_point.is_set =
!entry[kPrincipalPoint].Empty() && all_doubles;
if (prior->principal_point.is_set) {
prior->image_width =
static_cast<int>(2 * prior->principal_point.value[0]);
prior->image_height =
static_cast<int>(2 * prior->principal_point.value[1]);
}
}
// Get the camera intrincisc type.
if (entry.HasMember(kCameraType) && entry[kCameraType].IsString()) {
std::string model_type_str = entry[kCameraType].GetString();
if (IsCameraIntrinsicsModelTypeValid(model_type_str)) {
prior->camera_intrinsics_model_type = std::move(model_type_str);
} else {
LOG(WARNING) << "Could not identify camera intrinsics model type: "
<< model_type_str;
}
}
// Get width.
if (entry.HasMember(kImageWidth) && entry[kImageWidth].IsInt()) {
prior->image_width = entry[kImageWidth].GetInt();
}
// Get height.
if (entry.HasMember(kImageHeight) && entry[kImageHeight].IsInt()) {
prior->image_height = entry[kImageHeight].GetInt();
}
// Get aspect ratio.
if (entry.HasMember(kAspectRatio) &&
(entry[kAspectRatio].IsDouble() || entry[kAspectRatio].IsInt())) {
prior->aspect_ratio.is_set = true;
prior->aspect_ratio.value[0] = entry[kAspectRatio].GetDouble();
}
// Get skew.
if (entry.HasMember(kSkew) &&
(entry[kSkew].IsDouble() || entry[kSkew].IsInt())) {
prior->skew.is_set = true;
prior->skew.value[0] = entry[kSkew].GetDouble();
}
// Get radial distortion coeffs.
if (entry.HasMember(kRadialDistortionCoeffs) &&
entry[kRadialDistortionCoeffs].IsArray()) {
const int num_dist_coeffs =
std::min(static_cast<int>(entry[kRadialDistortionCoeffs].Size()), 4);
bool all_doubles = true;
for (int i = 0; i < num_dist_coeffs; ++i) {
bool is_double = entry[kRadialDistortionCoeffs][i].IsDouble() ||
entry[kRadialDistortionCoeffs][i].IsInt();
if (is_double) {
prior->radial_distortion.value[i] =
entry[kRadialDistortionCoeffs][i].GetDouble();
}
all_doubles = all_doubles && is_double;
}
prior->radial_distortion.is_set =
!entry[kRadialDistortionCoeffs].Empty() && all_doubles;
}
// Get tangential distortion coeffs.
if (entry.HasMember(kTangentialDistortionCoeffs) &&
entry[kTangentialDistortionCoeffs].IsArray()) {
const int num_dist_coeffs = std::min(
static_cast<int>(entry[kTangentialDistortionCoeffs].Size()), 2);
bool all_doubles = true;
for (int i = 0; i < num_dist_coeffs; ++i) {
bool is_double = entry[kTangentialDistortionCoeffs][i].IsDouble() ||
entry[kTangentialDistortionCoeffs][i].IsInt();
if (is_double) {
prior->tangential_distortion.value[i] =
entry[kTangentialDistortionCoeffs][i].GetDouble();
}
all_doubles = all_doubles && is_double;
}
prior->tangential_distortion.is_set =
!entry[kTangentialDistortionCoeffs].Empty() && all_doubles;
}
// Get position.
if (entry.HasMember(kPosition) && entry[kPosition].IsArray()) {
const int num_entries =
std::min(static_cast<int>(entry[kPosition].Size()), 3);
bool all_doubles = true;
for (int i = 0; i < num_entries; ++i) {
bool is_double =
entry[kPosition][i].IsDouble() || entry[kPosition][i].IsInt();
if (is_double) {
prior->position.value[i] = entry[kPosition][i].GetDouble();
}
all_doubles = all_doubles && is_double;
}
prior->position.is_set = !entry[kPosition].Empty() && all_doubles;
}
// Get orientation using Angle-Axis.
if (entry.HasMember(kOrientation) && entry[kOrientation].IsArray()) {
const int num_entries =
std::min(static_cast<int>(entry[kOrientation].Size()), 3);
bool all_doubles = true;
for (int i = 0; i < num_entries; ++i) {
bool is_double =
entry[kOrientation][i].IsDouble() || entry[kOrientation][i].IsInt();
if (is_double) {
prior->orientation.value[i] = entry[kOrientation][i].GetDouble();
}
all_doubles = all_doubles && is_double;
}
prior->orientation.is_set = !entry[kOrientation].Empty() && all_doubles;
}
// Get GPS priors.
if (entry.HasMember(kLatitude) &&
(entry[kLatitude].IsDouble() || entry[kLatitude].IsInt())) {
prior->latitude.value[0] = entry[kLatitude].GetDouble();
prior->latitude.is_set = true;
}
if (entry.HasMember(kLongitude) &&
(entry[kLongitude].IsDouble() || entry[kLongitude].IsInt())) {
prior->longitude.value[0] = entry[kLongitude].GetDouble();
prior->longitude.is_set = true;
}
if (entry.HasMember(kAltitude) &&
(entry[kAltitude].IsDouble() || entry[kAltitude].IsInt())) {
prior->altitude.value[0] = entry[kAltitude].GetDouble();
prior->altitude.is_set = true;
}
return true;
}
bool ExtractCameraIntrinsicsPrior(const cereal::rapidjson::Value& entry,
std::string* view_name,
CameraIntrinsicsPrior* prior) {
// Get the view name.
if (!entry.HasMember(kImageName)) {
LOG(ERROR) << "Could not find the image name.";
return false;
}
*view_name = entry[kImageName].GetString();
VLOG(3) << "Loading camera intrinsics prior for image name: " << *view_name;
// Get the camera type.
std::string camera_type_str;
if (!entry.HasMember(kCameraType)) {
LOG(WARNING) << "Unknown camera for view: " << *view_name
<< ". Setting to PINHOLE.";
camera_type_str = kPinholeType;
} else {
camera_type_str = entry[kCameraType].GetString();
VLOG(3) << "Camera type: [" << camera_type_str << "]";
}
// Get the camera type. This will verify if that the camera type is valid.
StringToCameraIntrinsicsModelType(camera_type_str);
ExtractPriorParameters(entry, prior);
return true;
}
} // namespace
bool ExtractCameraIntrinsicPriorsFromJson(
const char* json_str,
std::unordered_map<std::string, CameraIntrinsicsPrior>* view_to_priors) {
using cereal::rapidjson::Document;
using cereal::rapidjson::SizeType;
using cereal::rapidjson::Value;
Document json;
json.Parse(json_str);
if (!json.HasMember(kPriorsEntry) || !json[kPriorsEntry].IsArray()) {
LOG(ERROR) << "Expected \"priors\" array entry in JSON.";
return false;
}
const Value& entries = json[kPriorsEntry];
std::string view_name;
for (SizeType i = 0; i < entries.Size(); ++i) {
CameraIntrinsicsPrior prior;
if (!entries[i].HasMember(kCameraIntrinsicsPrior) ||
!ExtractCameraIntrinsicsPrior(
entries[i][kCameraIntrinsicsPrior], &view_name, &prior)) {
LOG(WARNING) << "Could not parse entry at position: " << i;
continue;
}
// Add to the map.
(*view_to_priors)[view_name] = prior;
}
return true;
}
bool ReadCalibration(const std::string& calibration_file,
std::unordered_map<std::string, CameraIntrinsicsPrior>*
camera_intrinsics_priors) {
// Get the size of the file.
const size_t buffer_size = stlplus::file_size(calibration_file);
// Allocate a buffer
std::vector<char> file_buffer(buffer_size, 0);
// Open and read the whole file.
FILE* file = fopen(calibration_file.c_str(), "rb");
if (file == nullptr) {
LOG(ERROR) << "Cannot read file: " << calibration_file;
return false;
}
// Read the whole file.
CHECK_EQ(fread(file_buffer.data(), sizeof(file_buffer[0]), buffer_size, file),
buffer_size);
fclose(file);
// Remove spurious chars after the closing curly brace.
std::string file_content(file_buffer.begin(), file_buffer.end());
const size_t last_curly_idx = file_content.rfind('}');
if (last_curly_idx == std::string::npos) {
LOG(ERROR) << "Could not fid a proper JSON file: " << calibration_file;
return false;
}
file_content.resize(last_curly_idx + 1);
const bool json_parsed = ExtractCameraIntrinsicPriorsFromJson(
file_content.c_str(), camera_intrinsics_priors);
return json_parsed;
}
} // namespace theia
| 12,124 | 4,220 |
#include <clrefl/Generator.h>
#include <clrefl/Codegen.h>
#include <infra/ToString.h>
#include <stl/vector.hpp>
#include <stl/unordered_map.hpp>
#include <stl/unordered_set.hpp>
#include <json11.hpp>
#include <cctype>
#define RESOLVE_TEMPLATES 1
#define DEBUG_CLANG_ARGS 0
namespace two
{
using Json = json11::Json;
struct TopoSort
{
vector<vector<size_t>> links;
vector<bool> perm_marks;
vector<bool> temp_marks;
vector<size_t> order;
vector<size_t> sorted;
};
auto visit_sort_topological(TopoSort& sort, size_t n) //, T& elem)
{
if(sort.perm_marks[n]) return;
if(sort.temp_marks[n]) return;
sort.temp_marks[n] = true;
for (size_t c : sort.links[n])
{
visit_sort_topological(sort, c);
}
sort.perm_marks[n] = true;
sort.order[n] = sort.sorted.size();
sort.sorted.push_back(n);
};
TopoSort sort_topological(vector<vector<size_t>> links)
{
TopoSort sort;
sort.links = links;
sort.perm_marks.resize(links.size(), false);
sort.temp_marks.resize(links.size(), false);
sort.order.resize(links.size());
for(size_t n = 0; n < links.size(); ++n)
{
visit_sort_topological(sort, n);
}
return sort;
}
void sort_classes(vector<unique<CLClass>>& classes)
{
for(size_t n = 0; n < classes.size(); ++n)
{
classes[n]->m_index = n;
}
vector<vector<size_t>> links;
links.resize(classes.size());
for(size_t n = 0; n < classes.size(); ++n)
{
CLClass& item = *classes[n];
for(CLClass* base : item.m_deep_bases)
{
if(base == &*classes[base->m_index])
links[n].push_back(base->m_index);
}
}
const TopoSort sort = sort_topological(links);
stable_sort(classes, [&](const unique<CLClass>& a, const unique<CLClass>& b) { return sort.order[a->m_index] < sort.order[b->m_index]; });
}
const CLType& element_type(const CLType& t)
{
if(t.m_type_kind == CLTypeKind::Alias)
return element_type(*((CLAlias&)t).m_target);
if(t.m_type_kind == CLTypeKind::Class)
{
const CLClass& c = (CLClass&)t;
if(c.m_sequence) return *c.m_element_type;
else if(c.m_array) return *c.m_array_type;
}
return t;
}
const CLType& reduce_element(const CLType& t)
{
if(t.m_type_kind == CLTypeKind::Alias)
return reduce_element(*((CLAlias&)t).m_target);
if(t.m_type_kind == CLTypeKind::Class)
{
const CLClass& c = (CLClass&)t;
if(c.m_sequence) return reduce_element(*c.m_element_type);
else if(c.m_array) return reduce_element(*c.m_array_type);
}
return t;
}
bool should_visit(CXCursor cursor, CLModule& module)
{
auto fix_path = [](const string& path) { return replace(path, "\\", "/"); };
string location = fix_path(file(cursor));
return module.m_parsed_files.find(location) == module.m_parsed_files.end();
}
bool should_reflect(CXCursor cursor, CLModule& module)
{
auto fix_path = [](const string& path) { return replace(path, "\\", "/"); };
string location = fix_path(file(cursor));
return location.find(module.m_path) == 0 && location.find("meta") == string::npos;
}
CLQualType qual_type(CLModule& module, const CLPrimitive& parent, CXType type, bool real_type)
{
//if(upointee(type).kind == CXType_Unexposed && !parent.m_is_templated)
// type = canonical(type);
bool templated = parent.m_is_templated && upointee(type).kind == CXType_Unexposed;
CLQualType t;
auto fix = [&](const string& name) { return templated ? parent.fix_template(name) : name; };
t.m_spelling = fix(spelling(type));
t.m_type_name = fix(spelling(class_type(type, !templated)));
t.m_array = type.kind == CXType_ConstantArray;
if(!real_type) return t;
t.m_type = templated ? module.get_type(type, t.m_type_name) : module.get_type(type);
// fixing type names because of spellings from libclang are not always fully qualified (mostly namespaces)
t.m_spelling = (t.isconst() ? "const " : "") + t.m_type->m_id + (t.pointer() ? "*" : "") + (t.reference() ? "&" : "");
t.m_type_name = t.m_type->m_id;
// substitute real aliased type only after fixing the spellings, so we see the alias types in reflection/bindings code
if(t.m_type->m_type_kind == CLTypeKind::Alias)
t.m_type = ((CLAlias*)t.m_type)->m_target;
if(t.m_type->m_type_kind == CLTypeKind::Class)
t.m_class = (CLClass*)t.m_type;
return t;
}
void decl_enum(CLModule& module, CLPrimitive& parent, CXCursor cursor)
{
CLEnum& e = vector_emplace<CLEnum>(module.m_enums, module, parent, type(cursor));
module.register_type(e);
e.m_cursor = cursor;
e.m_annotations = get_annotations(e.m_cursor);
e.m_reflect = has(e.m_annotations, "refl") && should_reflect(cursor, module);
module.m_has_reflected |= e.m_reflect;
}
void decl_callable(CLModule& module, CLPrimitive& parent, CLCallable& f, CXCursor cursor)
{
f.m_name = spelling(cursor);
f.m_cursor = cursor;
f.m_module = &module;
f.m_reflect = should_reflect(cursor, module);
const int template_args = clang_Cursor_getNumTemplateArguments(cursor);
if(cursor.kind == CXCursor_FunctionDecl && template_args > 0)
{
vector<string> types;
for(int i = 0; i < template_args; ++i)
{
CXType t = clang_Cursor_getTemplateArgumentType(cursor, 0);
types.push_back(spelling(t));
//f.m_templated_types.push_back(find_type(t));
}
f.m_name += "<" + comma(types) + ">";
f.m_id += "<" + comma(types) + ">";
}
f.m_is_template = cursor.kind == CXCursor_FunctionTemplate || (parent.m_is_template);
parent.m_reflect_content |= f.m_reflect;
module.m_has_reflected |= f.m_reflect;
}
void decl_function(CLModule& module, CLPrimitive& parent, CXCursor cursor)
{
//print "Function ", cursor.displayname
CLFunction& f = vector_emplace<CLFunction>(module.m_functions, parent, spelling(cursor));
decl_callable(module, parent, f, cursor);
f.m_index = module.m_functions.size() - 1;
}
// @todo cleanup this isn't really used, we declare specializations directly
void decl_function_template(CLModule& module, CLPrimitive& parent, CXCursor cursor)
{
//printf("Function Template %s %s\n", displayname(cursor).c_str(), spelling(cursor).c_str());
CLFunction& f = vector_emplace<CLFunction>(module.m_func_templates, parent, spelling(cursor));
f.m_is_template = true;
decl_callable(module, parent, f, cursor);
}
void decl_function_method(CLModule& module, CLPrimitive& parent, CXCursor cursor)
{
CLFunction& f = vector_emplace<CLFunction>(module.m_methods, parent, spelling(cursor));
decl_callable(module, parent, f, cursor);
}
void resolve_templates(CLModule& module, CLClass& c)
{
//printf("Resolve templates for %s\n", c.m_id.c_str());
c.m_template = &module.get_class_template(c.m_template_name);
if(c.m_template == nullptr)
{
c.m_reflect = false;
printf("[ERROR] %s - could not find template type definition\n", c.m_name.c_str());
return;
}
for(size_t i = 0; i < c.m_template_types.size(); ++i)
{
CXType t = clang_Type_getTemplateArgumentAsType(type(c.m_cursor), i);
CLType* type = module.find_alias(t, c.m_template_types[i]);
if(type == nullptr)
type = module.get_type(t);
c.m_templated_types.push_back(type);
bool pointer = c.m_template_types[i].find("*") != string::npos;
c.m_template_types[i] = type->m_id + string(pointer && type->m_type_kind != CLTypeKind::VoidPtr ? "*" : "");
}
c.set_name(c.m_template_name + "<" + comma(c.m_template_types) + ">");
if(c.m_sequence)
{
c.m_element = c.m_template_types[0];
c.m_element_type = c.m_templated_types[0];
}
}
void decl_class(CLModule& module, CLPrimitive& parent, CLClass& c, CXCursor cursor, CXType cxtype, bool sequence)
{
c.m_cursor = cursor;
c.m_annotations = get_annotations(cursor);
c.m_struct = has(c.m_annotations, "struct") || cursor.kind == CXCursor_StructDecl;
c.m_move_only = has(c.m_annotations, "nocopy");
c.m_reflect = has(c.m_annotations, "refl") && should_reflect(cursor, module);
c.m_array = has(c.m_annotations, "array");
c.m_span = has(c.m_annotations, "span");
c.m_sequence = has(c.m_annotations, "seque") || c.m_span;
c.m_extern = has(c.m_annotations, "extern");
c.m_is_template = cursor.kind == CXCursor_ClassTemplate;
c.m_is_templated = c.m_name.find("<") != string::npos && !c.m_is_template;
if(c.m_is_template)
c.set_name(displayname(cursor));
if(c.m_is_template || c.m_is_templated)
{
c.m_template_types = template_types(c.m_name);
c.m_template_name = template_name(c.m_name);
}
parent.m_reflect_content |= c.m_reflect;
module.m_has_reflected |= c.m_reflect;
}
CLClass& decl_class_type(CLModule& module, CLPrimitive& parent, CXCursor cursor)
{
CLClass& c = vector_emplace<CLClass>(module.m_classes, module, parent, type(cursor));
module.register_type(c);
decl_class(module, parent, c, cursor, type(cursor));
return c;
}
CLClass& decl_sequence_type(CLModule& module, CLPrimitive& parent, CXCursor cursor)
{
CLClass& c = vector_emplace<CLClass>(module.m_sequences, module, parent, type(cursor));
module.register_type(c);
decl_class(module, parent, c, cursor, type(cursor), true);
return c;
}
CLClass& decl_class_template(CLModule& module, CLPrimitive& parent, CXCursor cursor)
{
CLClass& c = vector_emplace<CLClass>(module.m_class_templates, module, parent, type(cursor));
decl_class(module, parent, c, cursor, type(cursor));
return c;
}
void parse_enum(CLModule& module, CLEnum& e)
{
UNUSED(module);
e.m_scoped = is_scoped(e.m_cursor);
e.m_enum_type = spelling(enum_type(e.m_cursor));
e.m_prefix = e.m_scoped ? e.m_id + "::" : e.m_parent->m_prefix;
const CXType integer_type = canonical(clang_getEnumDeclIntegerType(e.m_cursor));
bool is_signed = has({ CXType_SChar, CXType_Short, CXType_Int, CXType_Long, CXType_LongLong }, integer_type.kind);
visit_children(e.m_cursor, [&](CXCursor c)
{
if(c.kind == CXCursor_EnumConstantDecl)
{
e.m_ids.push_back(displayname(c));
e.m_values.push_back(is_signed ? to_string(clang_getEnumConstantDeclValue(c))
: to_string(clang_getEnumConstantDeclUnsignedValue(c)));
e.m_scoped_ids.push_back(e.m_prefix + displayname(c));
}
});
e.m_count = e.m_ids.size();
}
void parse_static(CLModule& module, CLClass& c, CXCursor cursor)
{
UNUSED(module);
CLStatic& s = push(c.m_statics, c);
s.m_member = spelling(cursor);
s.m_name = replace(spelling(cursor), "m_", "");
}
void find_default_value(CXCursor cursor, CLType& value_type, bool& has_default, string& default_value)
{
if(type(cursor).kind == CXType_ConstantArray)
return;
visit_children(cursor, [&](CXCursor c)
{
if(has({ CXCursor_CXXBoolLiteralExpr, CXCursor_FloatingLiteral, CXCursor_IntegerLiteral, CXCursor_StringLiteral }, c.kind))
{
has_default = true;
default_value = first_token(c);
if(default_value == "")
default_value = last_token(cursor);
}
else if(has({ CXCursor_BinaryOperator, CXCursor_UnaryOperator, CXCursor_CallExpr, CXCursor_DeclRefExpr, CXCursor_UnexposedExpr }, c.kind))
{
has_default = true;
visit_tokens(c, [&](CXToken t) {
string token = spelling(c, t);
if(ends_with(default_value + token, value_type.m_name))
default_value += token;
else if(kind(t) == CXToken_Identifier && value_type.m_name == token) default_value += value_type.m_id;
else if(token != "=") default_value += token;
});
}
});
}
void parse_param(CLModule& module, CLPrimitive& parent, CLCallable& f, CLParam& p, CXCursor cursor)
{
p.m_name = spelling(cursor);
p.m_type = qual_type(module, parent, type(cursor), !parent.m_is_template);
p.m_output = p.m_name.substr(0, 6) == "output";
if(p.m_type.m_type)
{
find_default_value(cursor, *p.m_type.m_type, p.m_has_default, p.m_default);
if(parent.m_is_templated)
p.m_default = parent.fix_template(p.m_default);
}
}
void parse_callable(CLModule& module, CLCallable& f)
{
//printf("Parsing %s\n", f.m_name.c_str());
f.m_return_type = qual_type(module, *f.m_parent, result_type(f.m_cursor), !f.m_is_template);
visit_children(f.m_cursor, [&](CXCursor a)
{
if(a.kind == CXCursor_ParmDecl)
{
f.m_params.push_back(CLParam(f, f.m_params.size()));
parse_param(module, *f.m_parent, f, f.m_params.back(), a);
}
});
for(size_t i = 0; i < f.m_params.size(); ++i)
if(!f.m_params[i].m_has_default)
f.m_min_args = i + 1;
}
void parse_constructor(CLModule& module, CLClass& c, CXCursor cursor)
{
CLConstructor& ctor = push(c.m_constructors, c, spelling(cursor));
decl_callable(module, c, ctor, cursor);
parse_callable(module, ctor);
ctor.m_overload_index = c.m_constructors.size() - 1;
}
void parse_method(CLModule& module, CLClass& c, CLMethod& m, CXCursor cursor)
{
decl_callable(module, c, m, cursor);
parse_callable(module, m);
m.m_const = is_const_method(cursor);
}
void parse_method(CLModule& module, CLClass& c, CXCursor cursor)
{
CLMethod& m = push(c.m_methods, c, spelling(cursor));
parse_method(module, c, m, cursor);
}
void parse_function_method(CLModule& module, CLFunction& f)
{
parse_callable(module, f);
CLClass& c = *f.m_params[0].m_type.m_class;
//parse_method(module, c, f.m_cursor);
CLMethod& m = push(c.m_methods, c, f.m_name);
decl_callable(module, c, m, f.m_cursor);
m.m_return_type = f.m_return_type;
m.m_params = vector<CLParam>(f.m_params.begin() + 1, f.m_params.end());
m.m_function = &f;
}
void parse_member(CLModule& module, CLClass& c, CXCursor cursor)
{
CLMember& m = push(c.m_members, c);
m.m_member = spelling(cursor);
m.m_name = replace(spelling(cursor), "m_", "");
m.m_capname = string(1, char(toupper(m.m_name[0]))) + m.m_name.substr(1, string::npos);
CXType member_type = type(cursor);
if(cursor.kind == CXCursor_CXXMethod)
{
m.m_method = make_unique<CLMethod>(c, spelling(cursor));
parse_method(module, c, *m.m_method, cursor);
member_type = result_type(cursor);
}
m.m_type = qual_type(module, c, member_type, !c.m_is_template);
m.m_annotations = get_annotations(cursor);
m.m_nonmutable = has(m.m_annotations, "nomut");
m.m_structure = has(m.m_annotations, "graph");
m.m_link = has(m.m_annotations, "link");
m.m_component = has(m.m_annotations, "comp");
if(!c.m_is_template)
{
m.m_nonmutable |= m.m_type.reference();
m.m_nonmutable |= !m.m_type.pointer() && (m.m_type.isconst() || !m.m_type.m_type->copyable());
m.m_nonmutable |= !m.m_setter && m.m_method;
}
visit_children(cursor, [&](CXCursor s)
{
if(s.kind == CXCursor_CXXMethod && spelling(s) == "set" + m.m_capname || spelling(s) == "set_" + m.m_name)
{
m.m_setter = make_unique<CLMethod>(c, spelling(s));
parse_method(module, c, *m.m_setter, s);
}
});
if(m.m_type.m_type)
{
find_default_value(cursor, *m.m_type.m_type, m.m_has_default, m.m_default);
if(c.m_is_templated)
m.m_default = c.fix_template(m.m_default);
}
}
void parse_class_child(CLModule& module, CLClass& c, CXCursor cursor)
{
const vector<string> annotations = get_annotations(cursor);
if(cursor.kind == CXCursor_TemplateTypeParameter)
c.m_template_types.push_back(spelling(cursor));
else if(cursor.kind == CXCursor_CXXBaseSpecifier)
{
const string name = spelling(type(cursor));
//if(c.m_is_templated && name.find("<") != string::npos)
// name = c.fix_template(name);
if(!c.m_is_templated && name.find("<") == string::npos)
{
CLType* base = module.find_type(name);
if(base && base->m_type_kind == CLTypeKind::Alias)
base = static_cast<CLAlias*>(base)->m_target;
if(base && (base->m_reflect || has(base->m_annotations, "refl")))
{
CLClass* basecls = static_cast<CLClass*>(base);
c.m_bases.push_back(basecls);
c.m_deep_bases.push_back(basecls);
extend(c.m_deep_bases, basecls->m_bases);
}
}
}
else if(cursor.kind == CXCursor_Constructor && has(annotations, "constr"))
parse_constructor(module, c, cursor);
else if(cursor.kind == CXCursor_CXXMethod && has(annotations, "attr"))
parse_member(module, c, cursor);
else if(cursor.kind == CXCursor_CXXMethod && has(annotations, "meth"))
parse_method(module, c, cursor);
else if(cursor.kind == CXCursor_FieldDecl && has(annotations, "attr"))
parse_member(module, c, cursor);
else if(cursor.kind == CXCursor_VarDecl && has(annotations, "attr"))
parse_static(module, c, cursor);
else if(cursor.kind == CXCursor_UnionDecl || cursor.kind == CXCursor_StructDecl)
{
if(clang_Cursor_isAnonymous(cursor))
visit_children(cursor, [&](CXCursor a) {
parse_class_child(module, c, a);
});
}
}
void parse_class(CLModule& module, CLClass& c)
{
//printf("Parsing %s\n", c.m_id.c_str());
CXCursor cursor = c.m_cursor;
#if !RESOLVE_TEMPLATES
if(c.m_is_templated)
resolve_templates(module, c);
#endif
if(c.m_is_templated && c.m_template) // && is_template_decl(cursor))
cursor = c.m_template->m_cursor;
visit_children(cursor, [&](CXCursor a) {
parse_class_child(module, c, a);
});
if(c.m_array)
{
c.m_array_size = c.m_members.size();
c.m_array_type = c.m_members[0].m_type.m_type;
}
set<string> method_names;
for(CLMethod& method : c.m_methods)
{
if(method_names.find(method.m_name) != method_names.end())
method.m_overloaded = true;
method_names.insert(method.m_name);
}
if(c.m_struct && c.m_constructors.empty())
{
CLConstructor& ctor = push(c.m_constructors, c, c.m_name);
ctor.m_module = &module;
ctor.m_overload_index = 0;
}
}
void parse_sequence(CLModule& module, CLClass& c)
{
parse_class(module, c);
c.m_name = c.m_template_name + "<" + c.m_element + ">";
}
void build_classes(CXCursor cursor, CLModule& module, CLPrimitive& parent)
{
visit_children(cursor, [&](CXCursor c)
{
if(!should_visit(c, module)) return;
vector<string> annotations = get_annotations(c);
if(c.kind == CXCursor_Namespace)
{
CLNamespace& ns = module.get_namespace(spelling(c), parent);
build_classes(c, module, ns);
}
else if(c.kind == CXCursor_VarDecl && has(annotations, "base"))
{
module.base_type(type(c));
}
else if(c.kind == CXCursor_TypeAliasDecl || c.kind == CXCursor_TypedefDecl)
{
CXType cxalias = type(c);
CXType cxtarget = canonical(type(c));
CLType* target = module.find_type(cxtarget);
if(target && !target->iscstring() && parent.m_kind == CLPrimitiveKind::Namespace)
{
CLAlias& t = vector_emplace<CLAlias>(module.m_aliases, module, parent, cxalias, cxtarget);
//printf("aliased %s to %s\n", t.m_id.c_str(), target->m_id.c_str());
t.m_target = target;
t.m_reflect = should_reflect(c, module);
module.register_type(t);
}
}
else if(is_definition(c) && has(annotations, "refl"))
{
if(c.kind == CXCursor_EnumDecl)
decl_enum(module, parent, c);
else if((c.kind == CXCursor_ClassDecl || c.kind == CXCursor_StructDecl))
{
CLClass& cl = has(annotations, "seque") || has(annotations, "span")
? decl_sequence_type(module, parent, c)
: decl_class_type(module, parent, c);
build_classes(c, module, cl);
}
else if(c.kind == CXCursor_ClassTemplate)
{
CLClass& cl = decl_class_template(module, parent, c);
build_classes(c, module, cl);
}
}
else if(c.kind == CXCursor_FunctionTemplate && has(annotations, "func"))
decl_function_template(module, parent, c);
else if(c.kind == CXCursor_FunctionDecl && has(annotations, "func") && should_reflect(c, module))
decl_function(module, parent, c);
else if(c.kind == CXCursor_FunctionDecl && has(annotations, "meth") && should_reflect(c, module))
decl_function_method(module, parent, c);
});
}
class CLGenerator
{
public:
CLGenerator() {}
vector<unique<CLModule>> m_modules = {};
vector<CLModule*> m_generator_queue = {};
CLModule& module(const string& id)
{
for(auto& module : m_modules)
if(id == module->m_id)
return *module;
printf("[ERROR] fetching inexistent module\n");
static CLModule invalid; return invalid;
}
void print_diagnostics(CXTranslationUnit tu)
{
uint num_diagnostics = clang_getNumDiagnostics(tu);
for(uint i = 0; i < num_diagnostics; ++i)
{
CXDiagnostic diagnostic = clang_getDiagnostic(tu, i);
CXDiagnosticSeverity severity = clang_getDiagnosticSeverity(diagnostic);
CXSourceLocation location = clang_getDiagnosticLocation(diagnostic);
CXString filename;
unsigned int line;
unsigned int column;
clang_getPresumedLocation(location, &filename, &line, &column);
printf("severity: %i, ", int(severity));
printf("location: %s (%i, %i), ", clang_string(filename).c_str(), line, column);
printf("%s\n", clang_string(clang_getDiagnosticSpelling(diagnostic)).c_str());
//print diag.option
clang_disposeString(filename);
}
}
CXTranslationUnit parse(CLModule& module)
{
printf("Module path : %s\n", module.m_path.c_str());
bool debug_diagnostic = true;
vector<string> compiler_args = {
"-x",
"c++",
"-std=c++17",
"-fdelayed-template-parsing",
"-fms-compatibility",
"-fms-extensions",
"-fmsc-version=1900",
"-Wmicrosoft",
"-isystemC:/Program Files (x86)/Microsoft Visual Studio/2017/Community/VC/Tools/MSVC/14.16.27023/include",
"-isystemC:/Program Files (x86)/Windows Kits/10/Include/10.0.10240.0/ucrt",
"-DTWO_META_GENERATOR",
//"-DTWO_NO_GLM", // @todo
};
for(string attr : { "base", "refl", "struct", "nocopy", "extern", "gpu", "array", "span", "seque", "comp", "constr", "meth", "func", "attr", "nomut", "graph", "link" })
compiler_args.push_back("-D" + attr + "_=__attribute__((annotate(\"" + attr + "\")))");
for(string dir : module.m_includedirs)
compiler_args.push_back("-I" + dir);
for(CLModule* m : module.m_modules)
compiler_args.push_back("-I" + m->m_rootdir);
#if DEBUG_CLANG_ARGS
printf("Parsing with compiler args: \n");
for(string arg : compiler_args)
printf("%s\n", arg.c_str());
#endif
vector<cstring> compiler_cargs;
for(const string& arg : compiler_args)
compiler_cargs.push_back(arg.c_str());
string file = "Api.h";
string path = module.m_path + "/" + file;
CXIndex index = clang_createIndex(0, 0);
printf("Parsing %s\n", file.c_str());
// only for debugging : these two ways of parsing don"t give the correct output, but can give more diagnostics as to what might be wrong
// int options = 0;
// int options = CXTranslationUnit_SkipFunctionBodies;
//int options = CXTranslationUnit_SkipFunctionBodies | CXTranslationUnit_Incomplete;
int options = CXTranslationUnit_SkipFunctionBodies | CXTranslationUnit_KeepGoing;
CXTranslationUnit translation_unit = clang_parseTranslationUnit(index, path.c_str(), compiler_cargs.data(), int(compiler_cargs.size()), nullptr, 0, options);
constexpr bool debug = true;
if(debug)
print_diagnostics(translation_unit);
return translation_unit;
}
void generate_module(CLModule& module)
{
if(!file_exists(module.m_path + "/" + "Types.h"))
{
//with open(os.path.join(module.path, "Types.h"), "w") as f :
// pass
}
printf("NUM CLASSES : %i\n", int(module.m_classes.size()));
//string forward_h = clgen::forward_h_template(module);
//update_file((module.m_path + "/" + "Forward.h", forward_h);
CXTranslationUnit tu = this->parse(module);
build_classes(cursor(tu), module, module.m_global);
#if RESOLVE_TEMPLATES
for(auto& c : module.m_classes)
if(c->m_is_templated)
resolve_templates(module, *c);
for(auto& c : module.m_sequences)
if(c->m_is_templated)
resolve_templates(module, *c);
#endif
for(auto& e : module.m_enums)
parse_enum(module, *e);
for(auto& c : module.m_classes)
parse_class(module, *c);
for(auto& c : module.m_sequences)
parse_sequence(module, *c);
for(auto& f : module.m_functions)
parse_callable(module, *f);
for(auto& f : module.m_methods)
parse_function_method(module, *f);
clang_disposeTranslationUnit(tu);
auto cmp_types = [](CLType& a, CLType& b) -> int
{
int result = a.m_name.compare(b.m_name);
return result < 0;
};
stable_sort(module.m_types, [&](CLType* a, CLType* b) { return cmp_types(*a, *b) < 0; });
stable_sort(module.m_enums, [&](const unique<CLEnum>& a, const unique<CLEnum>& b) { return cmp_types(*a, *b) < 0; });
stable_sort(module.m_sequences, [&](const unique<CLClass>& a, const unique<CLClass>& b) { return cmp_types(*a, *b) < 0; });
stable_sort(module.m_basetypes, [&](const unique<CLBaseType>& a, const unique<CLBaseType>& b) { return cmp_types(*a, *b) < 0; });
sort_classes(module.m_classes);
//if(module.m_classes.size() == 0 && module.m_enums.size() == 0)
// return;
if(!directory_exists(module.m_refl_path))
create_directory_tree(module.m_refl_path);
printf("Generating meta reflection files for %s:\n", module.m_name.c_str());
string types_h = clgen::types_h_template(module);
update_file(module.m_path + "/" + "Types.h", types_h);
if(!module.m_notypes)
{
string types_cpp = clgen::types_cpp_template(module);
update_file(module.m_path + "/" + module.m_dotname + ".types.cpp", types_cpp);
}
string module_h = clgen::module_h_template(module);
update_file(module.m_refl_path + "/" + module.m_dotname + ".meta.h", module_h);
string module_cpp = clgen::module_cpp_template(module);
update_file(module.m_refl_path + "/" + module.m_dotname + ".meta.cpp", module_cpp);
string convert_h = clgen::convert_h_template(module);
update_file(module.m_refl_path + "/" + module.m_dotname + ".conv.h", convert_h);
printf("Generating bindings files for %s:\n", module.m_name.c_str());
if(!directory_exists(module.m_bind_path))
create_directory_tree(module.m_bind_path);
clgen::bind_javascript(module);
}
void add_module(const Json& m)
{
auto tos = [](const Json& j) -> string { return j.string_value().c_str(); };
vector<CLModule*> dependencies = {};
for(const Json& dep : m["dependencies"].array_items())
{
dependencies.push_back(&this->module(tos(dep)));
}
vector<string> includedirs = {};
for(const Json& inc : m["includedirs"].array_items())
{
includedirs.push_back(tos(inc));
}
CLModule& module = vector_emplace<CLModule>(m_modules, tos(m["namespace"]), tos(m["name"]), tos(m["dotname"]), tos(m["idname"]),
tos(m["root"]), tos(m["subdir"]), tos(m["path"]), includedirs, dependencies);
if(m["notypes"].bool_value())
module.m_notypes = true;
m_generator_queue.push_back(&module);
if(module.m_name == "type")
module.m_decl_basetypes = true;
}
void generate_module(const string& id)
{
CLModule& module = this->module(id);
this->generate_module(module);
}
void generate_all_modules()
{
for(CLModule* module : m_generator_queue)
this->generate_module(*module);
}
};
}
using namespace two;
int main(int argc, char *argv[])
{
string all = "d:/Documents/Programmation/toy/build/refl/two_infra_refl.json d:/Documents/Programmation/toy/build/refl/two_jobs_refl.json d:/Documents/Programmation/toy/build/refl/two_type_refl.json d:/Documents/Programmation/toy/build/refl/two_tree_refl.json d:/Documents/Programmation/toy/build/refl/two_pool_refl.json d:/Documents/Programmation/toy/build/refl/two_refl_refl.json d:/Documents/Programmation/toy/build/refl/two_ecs_refl.json d:/Documents/Programmation/toy/build/refl/two_srlz_refl.json d:/Documents/Programmation/toy/build/refl/two_math_refl.json d:/Documents/Programmation/toy/build/refl/two_geom_refl.json d:/Documents/Programmation/toy/build/refl/two_noise_refl.json d:/Documents/Programmation/toy/build/refl/two_wfc_refl.json d:/Documents/Programmation/toy/build/refl/two_fract_refl.json d:/Documents/Programmation/toy/build/refl/two_lang_refl.json d:/Documents/Programmation/toy/build/refl/two_ctx_refl.json d:/Documents/Programmation/toy/build/refl/two_ui_refl.json d:/Documents/Programmation/toy/build/refl/two_uio_refl.json d:/Documents/Programmation/toy/build/refl/two_snd_refl.json d:/Documents/Programmation/toy/build/refl/two_bgfx_refl.json d:/Documents/Programmation/toy/build/refl/two_gfx_refl.json d:/Documents/Programmation/toy/build/refl/two_gltf_refl.json d:/Documents/Programmation/toy/build/refl/two_gfx_pbr_refl.json d:/Documents/Programmation/toy/build/refl/two_gfx_obj_refl.json d:/Documents/Programmation/toy/build/refl/two_gfx_gltf_refl.json d:/Documents/Programmation/toy/build/refl/two_gfx_ui_refl.json d:/Documents/Programmation/toy/build/refl/two_gfx_edit_refl.json d:/Documents/Programmation/toy/build/refl/two_tool_refl.json d:/Documents/Programmation/toy/build/refl/two_wfc_gfx_refl.json d:/Documents/Programmation/toy/build/refl/two_frame_refl.json d:/Documents/Programmation/toy/build/refl/toy_util_refl.json d:/Documents/Programmation/toy/build/refl/toy_core_refl.json d:/Documents/Programmation/toy/build/refl/toy_visu_refl.json d:/Documents/Programmation/toy/build/refl/toy_edit_refl.json d:/Documents/Programmation/toy/build/refl/toy_block_refl.json d:/Documents/Programmation/toy/build/refl/toy_shell_refl.json d:/Documents/Programmation/toy/build/refl/_test_refl.json d:/Documents/Programmation/toy/build/refl/_minimal_refl.json d:/Documents/Programmation/toy/build/refl/_boids_refl.json d:/Documents/Programmation/toy/build/refl/_space_refl.json d:/Documents/Programmation/toy/build/refl/_platform_refl.json d:/Documents/Programmation/toy/build/refl/_blocks_refl.json d:/Documents/Programmation/toy/build/refl/_wren_refl.json d:/Documents/Programmation/toy/build/refl/_godot_refl.json";
CLGenerator generator;
vector<string> locations = split(all, " ");
for(int i = 1; i < argc; ++i)
locations.push_back(argv[i]);
for(string loc : locations)
{
std::string errors;
string text_module = read_text_file(loc);
Json json_module = Json::parse(text_module.c_str(), errors);
generator.add_module(json_module);
}
//generator.generate_module("two_math");
//generator.generate_module("two_geom");
//generator.generate_module("two_gfx");
generator.generate_all_modules();
return 0;
}
| 30,183 | 12,936 |
#ifndef IBMTIMEPREDICATE_H
#define IBMTIMEPREDICATE_H
#include "AbstractPredicate.hpp"
#include <set>
namespace splitter
{
class IBMtimePredicate : public AbstractPredicate
{
public:
IBMtimePredicate(unsigned long time);
virtual bool ps(const events::AbstractEvent &event) const;
virtual bool pc(const events::AbstractEvent &event, selection::AbstractSelection &abstractSelection);
virtual ~IBMtimePredicate() {}
private:
unsigned long timeOpen;
set<string> symbols;
};
}
#endif // IBMTIMEPREDICATE_H
| 530 | 165 |
#pragma once
#include "create_triangle.hpp"
#include "create_vertex.hpp"
#include "geometry.hpp"
#include "inner_triangle_edges.hpp"
#include "insert_vertex.hpp"
#include "lawson_algorithm.hpp"
#include "mesh.hpp"
#include "random_triangle_edge.hpp"
#include "topology.hpp"
#include "triangle.hpp"
#include "triangles.hpp"
#include "vertex_count.hpp"
#include "vertices.hpp"
#include "split.hpp"
| 397 | 145 |
// System.Reflection.Emit.ConstructorBuilder.SetSymCustomAttribute()
/* The following program demonstrates the 'SetSymCustomAttribute' method
of ConstructorBuilder class. It creates an assembly in the current
domain with dynamic module in the assembly. Constructor builder is
used in conjunction with the 'TypeBuilder' class to create constructor
at run time. It then sets this constructor's custom attribute associated
with symbolic information.
*/
using namespace System;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
public ref class MyConstructorBuilder
{
private:
Type^ myType1;
ModuleBuilder^ myModuleBuilder;
AssemblyBuilder^ myAssemblyBuilder;
public:
MyConstructorBuilder()
{
myModuleBuilder = nullptr;
myAssemblyBuilder = nullptr;
// <Snippet1>
MethodBuilder^ myMethodBuilder = nullptr;
AppDomain^ myCurrentDomain = AppDomain::CurrentDomain;
// Create assembly in current CurrentDomain.
AssemblyName^ myAssemblyName = gcnew AssemblyName;
myAssemblyName->Name = "TempAssembly";
// Create a dynamic assembly.
myAssemblyBuilder = myCurrentDomain->DefineDynamicAssembly(
myAssemblyName, AssemblyBuilderAccess::Run );
// Create a dynamic module in the assembly.
myModuleBuilder = myAssemblyBuilder->DefineDynamicModule( "TempModule", true );
FieldInfo^ myFieldInfo =
myModuleBuilder->DefineUninitializedData( "myField", 2, FieldAttributes::Public );
// Create a type in the module.
TypeBuilder^ myTypeBuilder = myModuleBuilder->DefineType( "TempClass", TypeAttributes::Public );
FieldBuilder^ myGreetingField = myTypeBuilder->DefineField( "Greeting",
String::typeid, FieldAttributes::Public );
array<Type^>^ myConstructorArgs = {String::typeid};
// Define a constructor of the dynamic class.
ConstructorBuilder^ myConstructor = myTypeBuilder->DefineConstructor( MethodAttributes::Public, CallingConventions::Standard, myConstructorArgs );
// Display the name of the constructor.
Console::WriteLine( "The constructor name is : {0}", myConstructor->Name );
array<Byte>^ temp0 = {01,00,00};
myConstructor->SetSymCustomAttribute( "MySimAttribute", temp0 );
// </Snippet1>
// Generate the IL for the method and call its superclass constructor.
ILGenerator^ myILGenerator3 = myConstructor->GetILGenerator();
myILGenerator3->Emit( OpCodes::Ldarg_0 );
ConstructorInfo^ myConstructorInfo = Object::typeid->GetConstructor( gcnew array<Type^>(0) );
myILGenerator3->Emit( OpCodes::Call, myConstructorInfo );
myILGenerator3->Emit( OpCodes::Ldarg_0 );
myILGenerator3->Emit( OpCodes::Ldarg_1 );
myILGenerator3->Emit( OpCodes::Stfld, myGreetingField );
myILGenerator3->Emit( OpCodes::Ret );
// Add a method to the type.
myMethodBuilder = myTypeBuilder->DefineMethod(
"HelloWorld", MethodAttributes::Public, nullptr, nullptr );
// Generate IL for the method.
ILGenerator^ myILGenerator2 = myMethodBuilder->GetILGenerator();
myILGenerator2->EmitWriteLine( "Hello World from global" );
myILGenerator2->Emit( OpCodes::Ret );
myModuleBuilder->CreateGlobalFunctions();
myType1 = myTypeBuilder->CreateType();
}
property Type^ MyTypeProperty
{
Type^ get()
{
return this->myType1;
}
}
};
int main()
{
MyConstructorBuilder^ myConstructorBuilder = gcnew MyConstructorBuilder;
Type^ myType1 = myConstructorBuilder->MyTypeProperty;
if ( nullptr != myType1 )
{
Console::WriteLine( "Instantiating the new type..." );
array<Object^>^ myObject = {"hello"};
Object^ myObject1 = Activator::CreateInstance( myType1, myObject, nullptr );
MethodInfo^ myMethodInfo = myType1->GetMethod( "HelloWorld" );
if ( nullptr != myMethodInfo )
{
Console::WriteLine( "Invoking dynamically created HelloWorld method..." );
myMethodInfo->Invoke( myObject1, nullptr );
}
else
{
Console::WriteLine( "Could not locate HelloWorld method" );
}
}
else
{
Console::WriteLine( "Could not access Type." );
}
}
| 4,348 | 1,213 |
#include <s2e/S2E.h>
#include "Kasan.h"
#include "util.h"
using namespace klee;
namespace s2e {
namespace plugins {
// #define DEBUG_KASAN
S2E_DEFINE_PLUGIN(KernelAddressSanitizer, "kernel address sanitizer",
"KernelAddressSanitizer", "KernelFunctionModels",
"AllocManager", "OptionsManager", "LinuxMonitor");
#define DEFAULT_STACK_DEPTH 2
#define REPORT_STACK_DEPTH 3
void KernelAddressSanitizer::initialize() {
m_kernelFunc = s2e()->getPlugin<models::KernelFunctionModels>();
m_allocManager = s2e()->getPlugin<AllocManager>();
m_options = s2e()->getPlugin<OptionsManager>();
m_linuxMonitor = s2e()->getPlugin<LinuxMonitor>();
m_pcMonitor = s2e()->getPlugin<PcMonitor>();
assert(m_linuxMonitor && "Only support Linux");
initializeConfiguration();
getDebugStream() << "Mode: " << m_options->mode << "\n";
switch (m_options->mode) {
case MODE_PRE_ANALYSIS:
// m_handlers["kasan_report"] = &KernelAddressSanitizer::handleReport;
break;
case MODE_ANALYSIS:
case MODE_RESOLVE:
// m_handlers["kasan_report"] = &KernelAddressSanitizer::handleReport;
m_handlers["__asan_store1"] = &KernelAddressSanitizer::handleStore1;
m_handlers["__asan_store2"] = &KernelAddressSanitizer::handleStore2;
m_handlers["__asan_store4"] = &KernelAddressSanitizer::handleStore4;
m_handlers["__asan_store8"] = &KernelAddressSanitizer::handleStore8;
m_handlers["__asan_store16"] = &KernelAddressSanitizer::handleStore16;
m_handlers["__asan_storeN"] = &KernelAddressSanitizer::handleStoreN;
m_handlers["check_memory_region"] =
&KernelAddressSanitizer::handleCheckMemoryRegion;
if (!m_options->write_only) {
m_handlers["__asan_load1"] = &KernelAddressSanitizer::handleLoad1;
m_handlers["__asan_load2"] = &KernelAddressSanitizer::handleLoad2;
m_handlers["__asan_load4"] = &KernelAddressSanitizer::handleLoad4;
m_handlers["__asan_load8"] = &KernelAddressSanitizer::handleLoad8;
m_handlers["__asan_load16"] = &KernelAddressSanitizer::handleLoad16;
m_handlers["__asan_loadN"] = &KernelAddressSanitizer::handleLoadN;
}
m_additionChecks["csum_partial_copy_generic"] =
&KernelAddressSanitizer::handleCsumPartialCopyGeneric;
break;
default:
break;
}
}
void KernelAddressSanitizer::initializeConfiguration() {
bool ok = false;
ConfigFile *cfg = s2e()->getConfig();
ConfigFile::string_list funcList =
cfg->getListKeys(getConfigKey() + ".functions");
if (funcList.size() == 0) {
getWarningsStream() << "no functions configured\n";
// exit(1);
}
foreach2(it, funcList.begin(), funcList.end()) {
std::stringstream s;
s << getConfigKey() << ".functions." << *it;
std::string funcName = cfg->getString(s.str() + ".funcName", "", &ok);
EXIT_ON_ERROR(ok, "You must specify funcName");
uint64_t entry = cfg->getInt(s.str() + ".entry", 0, &ok);
EXIT_ON_ERROR(ok, "You must specify entry");
uint64_t exitAddr = cfg->getInt(s.str() + ".exit", 0, &ok);
EXIT_ON_ERROR(ok, "You must specify exit");
m_funcMap[funcName] = entry;
m_ranges[exitAddr] = entry;
}
funcList = cfg->getListKeys(getConfigKey() + ".checks");
foreach2(it, funcList.begin(), funcList.end()) {
std::stringstream s;
s << getConfigKey() << ".checks." << *it;
uint64_t address = cfg->getInt(s.str(), 0, &ok);
EXIT_ON_ERROR(ok, "You must specify " + s.str());
m_checkMap[*it] = address;
}
m_kasanReport = cfg->getInt(getConfigKey() + ".kasan_report", 0, &ok);
EXIT_ON_ERROR(ok, "You must specify kasan_report")
m_kasanRet = cfg->getInt(getConfigKey() + ".kasan_ret", 0, &ok);
m_symbolicoverflow =
cfg->getBool(getConfigKey() + ".checksymbol", true, &ok);
}
void KernelAddressSanitizer::registerHandler(PcMonitor *PcMonitor,
S2EExecutionState *state,
uint64_t cr3) {
foreach2(it, m_funcMap.begin(), m_funcMap.end()) {
// we already filter out any other process at PcMonitor, it's ok not to
// give
// cr3 here
PcMonitor::CallSignalPtr CallSignal =
PcMonitor->getCallSignal(state, it->second, cr3);
auto itt = m_handlers.find(it->first);
if (itt == m_handlers.end()) {
continue;
}
getDebugStream() << "Hook Function: " << it->first << " at "
<< hexval(it->second) << "\n";
CallSignal->connect(
sigc::bind(sigc::mem_fun(*this, &KernelAddressSanitizer::onCall),
(*itt).second),
KASAN_PRIORITY);
}
foreach2(it, m_checkMap.begin(), m_checkMap.end()) {
PcMonitor::CallSignalPtr CallSignal =
PcMonitor->getCallSignal(state, it->second, cr3);
auto itt = m_additionChecks.find(it->first);
if (itt == m_additionChecks.end()) {
continue;
}
getDebugStream() << "Check Function: " << it->first << " at "
<< hexval(it->second) << "\n";
CallSignal->connect(
sigc::bind(sigc::mem_fun(*this, &KernelAddressSanitizer::onCheck),
(*itt).second),
KASAN_PRIORITY);
}
// KASAN report
PcMonitor::CallSignalPtr Callsignal =
PcMonitor->getCallSignal(state, m_kasanReport, cr3);
Callsignal->connect(
sigc::mem_fun(*this, &KernelAddressSanitizer::handleReport),
KASAN_PRIORITY);
}
void KernelAddressSanitizer::onCall(S2EExecutionState *state,
PcMonitorState *pcs, uint64_t pc,
KernelAddressSanitizer::OpHandler handler) {
// skip these functions because they will introduce more constraints that we
// dont want
if (m_options->mode == MODE_RESOLVE) {
state->bypassFunction(0);
throw CpuExitException();
}
bool result = ((*this).*handler)(state, pc);
if (!result) {
// report here
// set timer to stop execution
m_options->halt = true;
}
}
void KernelAddressSanitizer::onCheck(
S2EExecutionState *state, PcMonitorState *pcs, uint64_t pc,
KernelAddressSanitizer::OpHandler handler) {
// bool result =
if (m_options->mode == MODE_RESOLVE) {
return;
}
((*this).*handler)(state, pc);
}
// determine the type of the memory address given the layout of the kernel space
// 0000000000000000 - 00007fffffffffff (=47 bits) user space, different per mm
// ffff880000000000 - ffffc7ffffffffff (=64 TB) direct mapping of all phys.
// memory
// ffffffff80000000 - ffffffff9fffffff (=512 MB) kernel text mapping, from phys
// 0
// We don't consider stack vaiable here. Stack address should be taken care of
// before.
MemoryType getMemType(uint64_t addr) {
if (addr < 4096) {
return NULL_ADDR;
} else if (addr < 0x7fffffffffff) {
return USER_ADDR;
} else if (addr < 0xffffffff80000000) {
return HEAP_ADDR;
} else {
return GLOBAL_ADDR;
}
}
bool KernelAddressSanitizer::getPossibleBaseAddrs(S2EExecutionState *state,
ref<Expr> dstExpr) {
uint64_t base_addr = 0;
if (!m_allocManager->getBaseAddr(state, dstExpr, base_addr)) {
ref<ConstantExpr> base;
ConstraintManager variableConstraints;
// Solution two: Assign zero to all symbolic variables
std::set<ReadExpr *> collection;
collectRead(dstExpr, collection);
foreach2(it, collection.begin(), collection.end()) {
variableConstraints.addConstraint(
E_EQ(*it, E_CONST(0, Expr::Int8)));
}
if (!findMin(state, variableConstraints, dstExpr, base,
state->concolics)) {
getDebugStream(state) << "Failed to get the minimum value of edi\n";
exit(1);
}
getDebugStream(state) << "Min address for dst: " << base << "\n";
base_addr = base->getZExtValue();
}
if (!base_addr) {
m_allocManager->print(this);
}
getDebugStream(state) << "Base addr: " << hexval(base_addr) << "\n";
assert(base_addr && "Failed to get base address from allocManager");
// Find one in busy list
uint64_t objAddr = m_allocManager->find(state, base_addr);
if (objAddr == 0) {
getDebugStream(state)
<< "Failed to find obj for " << hexval(base_addr) << "\n";
return false;
}
std::vector<target_ulong> backtrace;
if (!m_allocManager->getCallsite(objAddr, backtrace)) {
getDebugStream(state)
<< "Failed to find callsite for " << hexval(objAddr) << "\n";
return false;
}
AllocObj vul_obj;
if (!m_allocManager->get(state, objAddr, vul_obj)) {
return false;
}
m_allocManager->concretize(state, vul_obj);
getDebugStream(state) << "Vul address: " << hexval(objAddr) << "\n";
if (base_addr > objAddr + vul_obj.width + 1024) {
getDebugStream(state) << "The vuln object it found looks incorrect!\n";
return false;
}
std::stringstream ss;
ss << "[Busy Object] {";
ss << "\"Callsite\": [";
for (int i = 0; i < backtrace.size(); i++) {
if (i != 0) ss << ", ";
ss << std::to_string(backtrace[i]);
}
ss << "], \"Size\": " << std::to_string(vul_obj.width);
ss << ", \"Allocator\": \"" << m_allocManager->getAllocator(vul_obj)
<< "\"";
ss << ", \"Symbolic\": "
<< (vul_obj.tag == AllocObj::SYMBOLIC ? "true" : "false") << "}\n";
getDebugStream(state) << ss.str();
return true;
}
// unsigned long addr, size_t size, bool is_write, unsigned long ip
void KernelAddressSanitizer::handleReport(S2EExecutionState *state,
PcMonitorState *pcs, uint64_t pc) {
if (m_options->mode == MODE_PRE_ANALYSIS) {
if (m_options->write_only) {
uint64_t isWrite;
m_kernelFunc->readArgument(state, 2, isWrite, false);
if (!isWrite) {
return;
}
}
ref<Expr> addr = m_kernelFunc->readSymArgument(state, 0, false);
ref<Expr> size = m_kernelFunc->readSymArgument(state, 1, false);
uint64_t ip;
m_kernelFunc->readArgument(state, 3, ip, false);
getDebugStream(state) << "DstExpr: " << addr << "\n";
getDebugStream(state) << "SizeExpr: " << size << "\n";
getDebugStream(state) << "ip: " << hexval(ip) << "\n";
report(state, readExpr<uint64_t>(state, addr),
readExpr<uint64_t>(state, size), false, false, REPORT_STACK_DEPTH, 0);
// check if it's a heap object
uint64_t concrete_addr = readExpr<uint64_t>(state, addr);
switch (getMemType(concrete_addr)) {
case HEAP_ADDR:
getDebugStream(state) << "[KASAN-CAUSE] heap-memory-access\n";
break; // continue to execute
case NULL_ADDR:
getDebugStream(state) << "[KASAN-CAUSE] null-ptr-deref\n";
return;
case USER_ADDR:
getDebugStream(state) << "[KASAN-CAUSE] user-memory-access\n";
return;
case GLOBAL_ADDR:
getDebugStream(state) << "[KASAN-CAUSE] global-memory-access\n";
return;
case STACK_ADDR:
getDebugStream(state) << "[KASAN-CAUSE] stack-memory-access\n";
return;
}
if (!getPossibleBaseAddrs(state, addr)) {
return;
}
uint64_t pid = m_linuxMonitor->getPid(state);
getDebugStream(state) << "Pid: " << pid << "\n";
s2e()->getExecutor()->terminateState(*state,
"Stop tracing at the target");
} else if (m_options->mode == MODE_ANALYSIS) {
uint64_t addr, size, ip;
m_kernelFunc->readArgument(state, 0, addr, false);
m_kernelFunc->readArgument(state, 1, size, false);
m_kernelFunc->readArgument(state, 3, ip, false);
if (m_options->concrete) {
// Try to use our heuristics to get the base address
m_vulAddr = m_vulAddr ? m_vulAddr : addr;
report(state, addr, size, true, false, REPORT_STACK_DEPTH, 0);
// we jump out of the normal control flow later, so handle everything here.
}
m_confirmCounter++;
getDebugStream(state)
<< "[KASAN-CONFIRM] {\"Addr\": " << std::to_string(addr)
<< ", \"ip\": " << std::to_string(ip) << "}\n";
// we may want to stop
m_options->halt = true;
if (m_confirmCounter > m_reportCounter) {
m_confirmCounter -= m_reportCounter;
if (m_confirmCounter > m_options->max_kasan) {
s2e()->getExecutor()->terminateState(*state,
"Stop tracing on KASAN");
}
}
m_reportCounter = 0;
// We dont need report
skipKasan(state);
} else if (m_options->mode == MODE_RESOLVE) {
// skip these functions because they will introduce more constraints that we dont want
skipKasan(state);
}
return;
}
bool KernelAddressSanitizer::report(S2EExecutionState *state, uint64_t dstAddr,
uint64_t len, bool reliable, bool isWrite,
unsigned depth, uint64_t stack) {
std::vector<target_ulong> stacks;
bool ok = m_kernelFunc->dump_stack(state, stack, 0, stacks, depth);
if (!ok)
return false;
std::stringstream ss;
ss << "[KASAN] {";
ss << "\"ip\": [";
for (unsigned i = 0; i < stacks.size(); i++) {
if (i != 0) {
ss << ", ";
}
ss << std::to_string(stacks[i]);
}
ss << "], ";
if (stacks.size() !=
depth) { // our simple heuristic failed to retrieve backtrace
ss << "\"counter\": " << std::to_string(m_pcMonitor->getCounter())
<< ", ";
}
ss << "\"addr\": " << std::to_string(dstAddr) << ", ";
ss << "\"len\": " << std::to_string(len) << ", ";
ss << "\"reliable\": " << (reliable ? "true" : "false") << ", ";
ss << "\"write\": " << (isWrite ? "true" : "false");
ss << "}\n";
m_reportCounter++;
getDebugStream(state) << ss.str();
return ok;
}
bool KernelAddressSanitizer::reportAccess(S2EExecutionState *state,
uint64_t baseAddr, uint64_t dstAddr,
unsigned len, bool isWrite,
unsigned depth) {
std::vector<target_ulong> stacks;
bool ok = m_kernelFunc->dump_stack(state, 0, 0, stacks, depth);
if (!ok)
return false;
std::stringstream ss;
ss << "[Access] {";
ss << "\"base\": " << std::to_string(baseAddr) << ", ";
ss << "\"offset\": " << std::to_string(dstAddr - baseAddr) << ", ";
ss << "\"len\": " << std::to_string(len) << ", ";
ss << "\"isWrite\": " << (isWrite ? "true" : "false") << ", ";
ss << "\"ip\": [";
for (unsigned i = 0; i < stacks.size(); i++) {
if (i != 0) {
ss << ", ";
}
ss << std::to_string(stacks[i]);
}
ss << "]";
ss << "}\n";
getDebugStream(state) << ss.str();
return ok;
}
bool KernelAddressSanitizer::checkMemory(S2EExecutionState *state,
unsigned size, bool isWrite,
uint64_t ret_ip) {
#ifdef DEBUG_KASAN
getDebugStream() << "Check memory at address " << hexval(ret_ip) << "\n";
#endif
ref<Expr> dstExpr = m_kernelFunc->readSymArgument(state, 0, false);
uint64_t base_addr;
if (m_allocManager->getBaseAddr(state, dstExpr, base_addr)) {
uint64_t dstAddr = readExpr<uint64_t>(state, dstExpr);
AllocObj obj;
if (!m_allocManager->get(state, base_addr, obj, true)) {
return true;
}
if (m_options->track_access) {
reportAccess(state, base_addr, dstAddr, size, isWrite,
DEFAULT_STACK_DEPTH);
}
if (base_addr + obj.width < dstAddr + size) {
m_vulAddr = m_vulAddr ? m_vulAddr : base_addr;
getDebugStream(state) << "Dst: " << hexval(dstAddr)
<< " with size: " << hexval(size) << "\n";
report(state, dstAddr, size, true, isWrite, DEFAULT_STACK_DEPTH, state->regs()->getSp());
return false;
}
ref<Expr> len = E_CONST(size, 64);
// It's time consuming, so we'd better not to check every time we
// encounter a seen pc address.
if (m_visit.find(ret_ip) == m_visit.end() &&
!checkSymMemory(state, dstExpr, len, obj, base_addr)) {
m_vulAddr = m_vulAddr ? m_vulAddr : base_addr;
getDebugStream(state)
<< "Potential Overflow-- Dst: " << hexval(dstAddr)
<< " with size: " << hexval(size) << "\n";
// getDebugStream(state) << dstExpr << "\n";
report(state, dstAddr, size, false, isWrite, DEFAULT_STACK_DEPTH, state->regs()->getSp());
m_visit.insert({ret_ip, true});
return false;
}
m_visit.insert({ret_ip, true});
}
return true;
}
bool KernelAddressSanitizer::checkMemoryRegion(S2EExecutionState *state,
ref<Expr> &dstExpr,
ref<Expr> &size, bool isWrite,
uint64_t ret_ip) {
#ifdef DEBUG_KASAN
getDebugStream() << "Check memory region at " << hexval(ret_ip) << "\n";
#endif
uint64_t base_addr;
if (m_allocManager->getBaseAddr(state, dstExpr, base_addr)) {
uint64_t dstAddr = readExpr<uint64_t>(state, dstExpr);
uint64_t len = readExpr<uint64_t>(state, size);
AllocObj obj;
if (!m_allocManager->get(state, base_addr, obj, true)) {
return true;
}
if (m_options->track_access) {
reportAccess(state, base_addr, dstAddr, len, isWrite,
DEFAULT_STACK_DEPTH);
}
if (base_addr + obj.width < dstAddr + len) {
m_vulAddr = m_vulAddr ? m_vulAddr : base_addr;
getDebugStream(state) << "Dst: " << hexval(dstAddr)
<< " with size: " << hexval(len) << "\n";
report(state, dstAddr, len, true, isWrite, DEFAULT_STACK_DEPTH, state->regs()->getSp());
return false;
}
if (m_visit.find(ret_ip) != m_visit.end() &&
!checkSymMemory(state, dstExpr, size, obj, base_addr)) {
m_vulAddr = m_vulAddr ? m_vulAddr : base_addr;
getDebugStream(state)
<< "Potential Overflow-- Dst: " << hexval(dstAddr)
<< " with size: " << hexval(len) << "\n";
// getDebugStream(state) << dstExpr << "\n";
// getDebugStream(state) << size << "\n";
report(state, dstAddr, len, false, isWrite, DEFAULT_STACK_DEPTH, state->regs()->getSp());
m_visit.insert({ret_ip, true});
return false;
}
m_visit.insert({ret_ip, true});
}
return true;
}
// check potential overflow
bool KernelAddressSanitizer::checkSymMemory(S2EExecutionState *state,
ref<Expr> &dstExpr, ref<Expr> &size,
AllocObj &obj, uint64_t base_addr) {
if (!m_symbolicoverflow) {
return true;
}
Solver *solver = getSolver(state);
bool ok;
// (ReadLSB w64 0x0 v1_alc_0xffff88000a515900_1)
// Add constraint for this
ref<Expr> condition;
ConstraintManager manager;
for (auto c : m_allocManager->AlloConstraint) {
manager.addConstraint(c);
}
for (auto c : state->constraints()) {
manager.addConstraint(c);
}
if (obj.tag == AllocObj::CONCRETE) {
condition = E_LT(E_CONST(base_addr + obj.width, 64),
AddExpr::create(dstExpr, size));
} else {
ref<Expr> len = alignExpr(obj.sym_width, Expr::Int64);
condition = E_LT(
AddExpr::create(obj.sym_width, E_CONST(base_addr, Expr::Int64)),
AddExpr::create(dstExpr, size));
}
if (!solver->mayBeTrue(Query(manager, condition), ok)) {
getDebugStream() << "Error on constraint solving\n";
exit(1);
}
if (ok) {
getDebugStream(state) << "base: " << hexval(base_addr) << "\n";
getDebugStream(state)
<< "Width: " << obj.sym_width << ", " << hexval(obj.width) << "\n";
}
return !ok;
}
bool KernelAddressSanitizer::handleStore1(S2EExecutionState *state,
uint64_t pc) {
KASAN_RET_IP
return checkMemory(state, 1, true, ret_ip);
}
bool KernelAddressSanitizer::handleStore2(S2EExecutionState *state,
uint64_t pc) {
KASAN_RET_IP
return checkMemory(state, 2, true, ret_ip);
}
bool KernelAddressSanitizer::handleStore4(S2EExecutionState *state,
uint64_t pc) {
KASAN_RET_IP
return checkMemory(state, 4, true, ret_ip);
}
bool KernelAddressSanitizer::handleStore8(S2EExecutionState *state,
uint64_t pc) {
KASAN_RET_IP
return checkMemory(state, 8, true, ret_ip);
}
bool KernelAddressSanitizer::handleStore16(S2EExecutionState *state,
uint64_t pc) {
KASAN_RET_IP
return checkMemory(state, 16, true, ret_ip);
}
bool KernelAddressSanitizer::handleStoreN(S2EExecutionState *state,
uint64_t pc) {
KASAN_RET_IP
ref<Expr> dstExpr = m_kernelFunc->readSymArgument(state, 0, false);
ref<Expr> size = m_kernelFunc->readSymArgument(state, 1, false);
return checkMemoryRegion(state, dstExpr, size, true, ret_ip);
}
bool KernelAddressSanitizer::handleLoad1(S2EExecutionState *state,
uint64_t pc) {
KASAN_RET_IP
return checkMemory(state, 1, false, ret_ip);
}
bool KernelAddressSanitizer::handleLoad2(S2EExecutionState *state,
uint64_t pc) {
KASAN_RET_IP
return checkMemory(state, 2, false, ret_ip);
}
bool KernelAddressSanitizer::handleLoad4(S2EExecutionState *state,
uint64_t pc) {
KASAN_RET_IP
return checkMemory(state, 4, false, ret_ip);
}
bool KernelAddressSanitizer::handleLoad8(S2EExecutionState *state,
uint64_t pc) {
KASAN_RET_IP
return checkMemory(state, 8, false, ret_ip);
}
bool KernelAddressSanitizer::handleLoad16(S2EExecutionState *state,
uint64_t pc) {
KASAN_RET_IP
return checkMemory(state, 16, false, ret_ip);
}
bool KernelAddressSanitizer::handleLoadN(S2EExecutionState *state,
uint64_t pc) {
KASAN_RET_IP
ref<Expr> dstExpr = m_kernelFunc->readSymArgument(state, 0, false);
ref<Expr> size = m_kernelFunc->readSymArgument(state, 1, false);
return checkMemoryRegion(state, dstExpr, size, false, ret_ip);
}
// addr, size, write, ret_ip
bool KernelAddressSanitizer::handleCheckMemoryRegion(S2EExecutionState *state,
uint64_t pc) {
uint64_t isWrite;
m_kernelFunc->readArgument(state, 2, isWrite, false);
if (isWrite || !m_options->write_only) {
KASAN_RET_IP
ref<Expr> dstExpr = m_kernelFunc->readSymArgument(state, 0, false);
ref<Expr> size = m_kernelFunc->readSymArgument(state, 1, false);
return checkMemoryRegion(state, dstExpr, size, isWrite, ret_ip);
}
return true;
}
// rdi: source, rsi: destination, edx: len, ecx: csum, r8: src_err_ptr, r9:
// dst_err_ptr
bool KernelAddressSanitizer::handleCsumPartialCopyGeneric(
S2EExecutionState *state, uint64_t pc) {
KASAN_RET_IP
ref<Expr> dstExpr = m_kernelFunc->readSymArgument(state, 1, false);
ref<Expr> size = m_kernelFunc->readSymArgument(state, 2, false);
bool result = checkMemoryRegion(state, dstExpr, size, true, ret_ip);
if (!m_options->write_only) {
ref<Expr> srcExpr = m_kernelFunc->readSymArgument(state, 0, false);
if (!checkMemoryRegion(state, srcExpr, size, false, ret_ip)) {
result = false;
}
}
return result;
}
void KernelAddressSanitizer::decideAddConstraint(uint64_t pc,
bool *allowConstraint) {
if (m_options->mode != MODE_RESOLVE || !allowConstraint) {
return; // remain the same
}
auto it = m_ranges.lower_bound(pc);
if (it == m_ranges.end()) {
return;
}
if (pc >= it->second) {
*allowConstraint = false;
}
}
} // namespace plugins
} // namespace s2e
| 25,382 | 8,372 |
/******************************Module*Header*******************************\
* Module Name: brushobj.cxx
*
* Support for brmemobj.hxx and brushobj.hxx.
*
* Created: 06-Dec-1990 12:02:24
* Author: Walt Moore [waltm]
*
* Copyright (c) 1990-1999 Microsoft Corporation
\**************************************************************************/
#include "precomp.hxx"
extern "C" BOOL bInitBRUSHOBJ();
extern "C" BOOL bInitBrush(int iBrush, COLORREF cr,
DWORD dwHS, PULONG_PTR pdw, BOOL bEnableDither);
#pragma alloc_text(INIT, bInitBRUSHOBJ)
#pragma alloc_text(INIT, bInitBrush)
// Global pointer to the last RBRUSH freed, if any (for one-deep caching).
PRBRUSH gpCachedDbrush = NULL;
PRBRUSH gpCachedEngbrush = NULL;
#define MAX_STOCKBRUSHES 4*1024
LONG gStockBrushFree = MAX_STOCKBRUSHES;
//#define DBG_STOCKBRUSHES 1
#if DBG_STOCKBRUSHES
#define STOCKWARNING DbgPrint
#define STOCKINFO DbgPrint
#else
#define STOCKWARNING
#define STOCKINFO
#endif
extern "C" HFASTMUTEX ghfmMemory;
#if DBG
LONG bo_inits, bo_realize, bo_notdirty, bo_cachehit;
LONG bo_missnotcached, bo_missfg, bo_missbg, bo_misspaltime, bo_misssurftime;
#endif
/****************************Global*Public*Data******************************\
*
* These are the 5 global brushes and 3 global pens maintained by GDI.
* These are retrieved through GetStockObject.
*
* History:
* 20-May-1991 -by- Patrick Haluptzok patrickh
* Wrote it.
\**************************************************************************/
HBRUSH ghbrText;
HBRUSH ghbrBackground;
HBRUSH ghbrGrayPattern;
PBRUSH gpbrText;
PBRUSH gpbrNull;
PBRUSH gpbrBackground;
PPEN gpPenNull;
HBRUSH ghbrDCBrush;
PBRUSH gpbrDCBrush;
HBRUSH ghbrDCPen;
PBRUSH gpbrDCPen;
// Uniqueness so a logical handle can be reused without having it look like
// the same brush as before. We don't really care where this starts.
ULONG BRUSH::_ulGlobalBrushUnique = 0;
ULONG gCacheHandleEntries[GDI_CACHED_HADNLE_TYPES] = {
CACHE_BRUSH_ENTRIES ,
CACHE_PEN_ENTRIES ,
CACHE_REGION_ENTRIES,
CACHE_LFONT_ENTRIES
};
ULONG gCacheHandleOffsets[GDI_CACHED_HADNLE_TYPES] = {
0,
CACHE_BRUSH_ENTRIES,
(
CACHE_BRUSH_ENTRIES +
CACHE_PEN_ENTRIES
),
(
CACHE_BRUSH_ENTRIES +
CACHE_PEN_ENTRIES +
CACHE_PEN_ENTRIES
)
};
/******************************Public*Routine******************************\
* bPEBCacheHandle
*
* Try to place the object(handle) in a free list on the PEB. The objects
* are removed from this list in user mode.
*
* Arguments:
*
* Handle - handle to cache
* HandleType - type of handle to attempt cache
* pBrushattr - pointer to user-mode object
*
* Return Value:
*
* TRUE if handle is cached, FALSE otherwise
*
* History:
*
* 30-Jan-1996 -by- Mark Enstrom [marke]
*
\**************************************************************************/
BOOL
bPEBCacheHandle(
HANDLE Handle,
HANDLECACHETYPE HandleType,
POBJECTATTR pObjectattr,
PENTRY pentry
)
{
BOOL bRet = FALSE;
PBRUSHATTR pBrushattr = (PBRUSHATTR)pObjectattr;
PW32PROCESS pw32Process = W32GetCurrentProcess();
PPEB Peb;
#if !defined(_GDIPLUS_)
ASSERTGDI(((HandleType == BrushHandle) || (HandleType == PenHandle) ||
(HandleType == RegionHandle) ||(HandleType == LFontHandle)
),"hGetPEBHandle: illegal handle type");
Peb = PsGetProcessPeb(pw32Process->Process);
if (Peb != NULL)
{
PGDIHANDLECACHE pCache = (PGDIHANDLECACHE)(&Peb->GdiHandleBuffer[0]);
BOOL bStatus;
//
// Lock Handle cache on PEB
//
LOCK_HANDLE_CACHE(pCache,PsGetCurrentThread(),bStatus);
if (bStatus)
{
//
// are any free slots still availablle
//
if (pCache->ulNumHandles[HandleType] < gCacheHandleEntries[HandleType])
{
ULONG Index = gCacheHandleOffsets[HandleType];
PHANDLE pHandle,pMaxHandle;
//
// calculate handle offset in PEB array
//
pHandle = &(pCache->Handle[Index]);
pMaxHandle = pHandle + gCacheHandleEntries[HandleType];
//
// search array for a free entry
//
while (pHandle != pMaxHandle)
{
if (*pHandle == NULL)
{
//
// for increased robust behavior, increment handle unique
//
pentry->FullUnique += UNIQUE_INCREMENT;
Handle = (HOBJ)MAKE_HMGR_HANDLE((ULONG)(ULONG_PTR)Handle & INDEX_MASK, pentry->FullUnique);
pentry->einfo.pobj->hHmgr = Handle;
//
// store handle in cache and inc stored count
//
*pHandle = Handle;
pCache->ulNumHandles[HandleType]++;
bRet = TRUE;
//
// clear to be deleted and select flags,
// set cached flag
//
pBrushattr->AttrFlags &= ~(ATTR_TO_BE_DELETED | ATTR_CANT_SELECT);
pBrushattr->AttrFlags |= ATTR_CACHED;
break;
}
pHandle++;
}
ASSERTGDI(bRet,"bPEBCacheHandle: count indicates free handle, but none free\n");
}
UNLOCK_HANDLE_CACHE(pCache);
}
}
#endif
return(bRet);
}
/******************************Public*Routine******************************\
* BRUSHMEMOBJ::pbrAllocBrush(bPen)
*
* Base constructor for brush memory object. This constructor is to be
* called by the various public brush constructors only.
*
* History:
* 29-Oct-1992 -by- Michael Abrash [mikeab]
* changed to allocate but not get a handle or lock (so the brush can be fully
* set up before the handle exists, exposing the data to the outside world).
*
* Wed 19-Jun-1991 -by- Patrick Haluptzok [patrickh]
* 0 out the brush.
*
* Thu 06-Dec-1990 12:02:41 -by- Walt Moore [waltm]
* Wrote it.
\**************************************************************************/
PBRUSH BRUSHMEMOBJ::pbrAllocBrush(BOOL bPen)
{
PBRUSH pbrush;
bKeep = FALSE;
// Allocate a new brush or pen
//
// Note: if anyone decides to try turning off zeroinit for performance,
// make sure to initialize the pen's psytle and cstyle to zero. Of
// course, other dependencies may creep in, so do this very very very
// carefully (if you even dare!).
if ((pbrush = (PBRUSH)ALLOCOBJ(bPen ? sizeof(PEN) : sizeof(BRUSH),
BRUSH_TYPE, TRUE)) != NULL)
{
pbrush->pBrushattr(&pbrush->_Brushattr);
pbrush->pIcmDIBList(NULL); // no ICM translated DIBs
pbrush->iUsage(0);
// Set up as initially not caching any realization
pbrush->vSetNotCached(); // no one's trying to cache a realization
// in this logical brush yet
pbrush->crFore((COLORREF)BO_NOTCACHED);
// no cached realization yet (no need to
// worry about crFore not being set when
// someone tries to check for caching,
// because we don't have a handle yet, and
// we'll lock when we do get the handle,
// forcing writes to flush)
pbrush->ulBrushUnique(pbrush->ulGlobalBrushUnique());
// set the uniqueness so the are-you-
// really-dirty check in vInitBrush will
// know this is not the brush in the DC
}
return(pbrush);
}
/******************************Public*Routine******************************\
* BRUSHMEMOBJ::BRUSHMEMOBJ
*
* Create a pattern brush or a DIB brush.
*
* History:
* 29-Oct-1992 -by- Michael Abrash [mikeab]
* changed to get handle only after fully initialized
*
* 14-May-1991 -by- Patrick Haluptzok patrickh
* Wrote it.
\**************************************************************************/
BRUSHMEMOBJ::BRUSHMEMOBJ(HBITMAP hbmClone, HBITMAP hbmClient,BOOL bMono,
FLONG flDIB, FLONG flType, BOOL bPen)
{
if (flDIB == DIB_PAL_COLORS)
{
flType |= BR_IS_DIBPALCOLORS;
}
else if (flDIB == DIB_PAL_INDICES)
{
flType |= BR_IS_DIBPALINDICES;
}
PBRUSH pbrush;
if ((pbp.pbr = pbrush = pbrAllocBrush(bPen)) != NULL)
{
pbrush->crColor(0);
pbrush->ulStyle(HS_PAT);
pbrush->hbmPattern(hbmClone);
pbrush->hbmClient(hbmClient);
pbrush->AttrFlags(0);
pbrush->flAttrs(flType);
if (bMono)
{
pbrush->flAttrs(pbrush->flAttrs() |
(BR_NEED_BK_CLR | BR_NEED_FG_CLR | BR_IS_MONOCHROME));
}
// Now that everything is set up, create the handle and expose this logical
// brush
if (HmgInsertObject(pbrush, HMGR_ALLOC_ALT_LOCK, BRUSH_TYPE) == 0)
{
FREEOBJ(pbrush, BRUSH_TYPE);
pbp.pbr = NULL;
}
}
else
{
WARNING1("Brush allocation failed\n");
}
}
/******************************Public*Routine******************************\
* GreSetSolidBrush
*
* Chicago API to change the color of a solid color brush.
*
* History:
* 19-Apr-1994 -by- Patrick Haluptzok patrickh
* Made it a function that User can call too.
*
* 03-Dec-1993 -by- Eric Kutter [erick]
* Wrote it - bReset.
\**************************************************************************/
BOOL GreSetSolidBrush(HBRUSH hbr, COLORREF clr)
{
return(GreSetSolidBrushInternal(hbr, clr, FALSE, TRUE));
}
BOOL GreSetSolidBrushInternal(
HBRUSH hbr,
COLORREF clr,
BOOL bPen,
BOOL bUserCalled
)
{
BOOL bReturn = FALSE;
BRUSHSELOBJ ebo(hbr);
PBRUSH pbrush = ebo.pbrush();
if (pbrush != NULL)
{
if ((pbrush->flAttrs() & BR_IS_SOLID) &&
((!pbrush->bIsGlobal()) || bUserCalled) &&
((!!pbrush->bIsPen()) == bPen))
{
#if DBG
if (bPen)
{
ASSERTGDI(((PPEN) pbrush)->pstyle() == NULL ||
(pbrush->flAttrs() & BR_IS_DEFAULTSTYLE),
"GreSetSolidBrush - bad attrs\n");
}
#endif
ASSERTGDI(pbrush->hbmPattern() == NULL,
"ERROR how can solid have pat");
PRBRUSH prbrush = (PRBRUSH) NULL;
RBTYPE rbType;
{
//
// Can't do the delete of the RBRUSH under MLOCK, takes too
// long and it may try and grab it again.
//
MLOCKFAST mlo;
//
// User may call when the brush is selected in a DC, but
// the client side should only ever call on a brush that's
// not in use.
//
if ((pbrush->cShareLockGet() == 1) || bUserCalled)
{
bReturn = TRUE;
pbrush->crColor(clr);
HANDLELOCK HandleLock(PENTRY_FROM_POBJ(pbrush), FALSE);
if (HandleLock.bValid())
{
if (pbrush->cShareLockGet() == 1)
{
//
// Nobody is using it and we have the handle lock
// so noone can select it in till we are done. So
// clean out the old realization now.
//
if ((pbrush->crFore() != BO_NOTCACHED) &&
!pbrush->bCachedIsSolid())
{
prbrush = (PRBRUSH) pbrush->ulRealization();
rbType = pbrush->bIsEngine() ? RB_ENGINE
: RB_DRIVER;
}
// Set up as initially not caching any realization
pbrush->vSetNotCached();
// no one's trying to cache a realization
// in this logical brush yet
pbrush->crFore((COLORREF)BO_NOTCACHED);
// no cached realization yet (no need to
// worry about crFore not being set when
// someone tries to check for caching,
// because we don't have a handle yet, and
// we'll lock when we do get the handle,
// forcing writes to flush)
if (!bUserCalled)
{
//
// If it's not User calling we are resetting the
// attributes / type.
//
pbrush->ulStyle(HS_DITHEREDCLR);
pbrush->flAttrs(BR_IS_SOLID | BR_DITHER_OK);
}
else
{
pbrush->vClearSolidRealization();
}
}
else
{
//ASSERTGDI(bUserCalled,
// "Client side is hosed, shouldn't "
// "call this with it still selected");
ASSERTGDI(pbrush->flAttrs() & BR_IS_SOLID,
"ERROR not solid");
ASSERTGDI(pbrush->ulStyle() == HS_DITHEREDCLR,
"ERROR not HS_DI");
//
// Mark this brushes realization as dirty by setting
// it's cache id's to invalid states. Note that if a
// realization hasn't been cached yet this will cause
// no problem either.
//
pbrush->crBack(0xFFFFFFFF);
pbrush->ulPalTime(0xFFFFFFFF);
pbrush->ulSurfTime(0xFFFFFFFF);
//
// This brush is being used other places, check for
// any DC's that have this brush selected in and mark
// their realizations dirty.
//
// Note there is the theoretical possibility that
// somebody is realizing the brush while we are
// marking them dirty and they won't pick up the new
// color. We set the color first and set the
// uniqueness last so that it is extremely unlikely
// (maybe impossible) that someone gets a realization
// that incorrectly thinks it has the proper
// realization. This is fixable by protecting access
// to the realization and cache fields but we aren't
// going to do it for Daytona.
//
// Mark every DC in the system that has this brush
// selected as a dirty brush.
//
HOBJ hobj = (HOBJ) 0;
DC *pdc;
while ((pdc = (DC *) HmgSafeNextObjt(hobj, DC_TYPE))
!= NULL)
{
if (pdc->peboFill()->pbrush() == pbrush)
{
pdc->flbrushAdd(DIRTY_FILL);
}
hobj = (HOBJ) pdc->hGet();
}
}
HandleLock.vUnlock();
}
//
// Set the uniqueness so the are-you-
// really-dirty check in vInitBrush will
// not think an old realization is still valid.
//
pbrush->ulBrushUnique(pbrush->ulGlobalBrushUnique());
}
else
{
WARNING1("Error, SetSolidBrush with cShare != 1");
}
}
if (prbrush)
{
prbrush->vRemoveRef(rbType);
}
}
#if DBG
else
{
if (bPen)
{
WARNING1("bPen True\n");
}
if (pbrush->bIsPen())
{
WARNING1("bIsPen True\n");
}
if (bUserCalled)
{
WARNING1("bUserCalled\n");
}
if (pbrush->bIsGlobal())
{
WARNING1("bIsGlobal\n");
}
if (pbrush->flAttrs() & BR_IS_SOLID)
{
WARNING1("BR_IS_SOLID is set\n");
}
WARNING1("GreSetSolidBrush not passed a solid color brush\n");
}
#endif
}
#if DBG
else
{
WARNING1("GreSetSolidBrush failed to lock down brush\n");
}
#endif
return(bReturn);
}
/******************************Public*Routine******************************\
* GreSetSolidBrushLight:
*
* Private version of GreSetSolidBrush, user can't call
*
* Arguments:
*
* pbrush - pointer to log brush
* clr - new color
* bPen - Brush is a pen
*
* Return Value:
*
* Status
*
* History:
*
* 2-Nov-1995 -by- Mark Enstrom [marke]
*
\**************************************************************************/
BOOL
GreSetSolidBrushLight(
PBRUSH pbrush,
COLORREF clr,
BOOL bPen
)
{
BOOL bReturn = FALSE;
if (pbrush != NULL)
{
if (
(pbrush->flAttrs() & BR_IS_SOLID) &&
(!pbrush->bIsGlobal())
)
{
//
// make sure bPen flag matches brush type
//
if ((bPen != 0) == (pbrush->bIsPen() != 0))
{
#if DBG
if (bPen)
{
ASSERTGDI(((PPEN) pbrush)->pstyle() == NULL ||
(pbrush->flAttrs() & BR_IS_DEFAULTSTYLE),
"GreSetSolidBrushLight - illegal PEN attrs\n");
}
#endif
ASSERTGDI(pbrush->hbmPattern() == NULL,
"ERROR how can solid have pat");
PRBRUSH prbrush = (PRBRUSH) NULL;
RBTYPE rbType;
{
//
// Grab the handle lock to stabize the lock counts.
// Do not attempt to free the realized brush under
// this lock; it may take to long.
//
ASSERTGDI(pbrush->hGet(),
"ERROR brush obj has no handle\n");
HANDLELOCK HandleLock(PENTRY_FROM_POBJ(pbrush),FALSE);
if (HandleLock.bValid())
{
if (pbrush->cShareLockGet() == 1)
{
bReturn = TRUE;
pbrush->crColor(clr);
//
// Nobody is using it and we have the HANDLELOCK
// so noone can select it in till we are done. So
// clean out the old realization now.
//
if ((pbrush->crFore() != BO_NOTCACHED) &&
!pbrush->bCachedIsSolid())
{
prbrush = (PRBRUSH) pbrush->ulRealization();
rbType = pbrush->bIsEngine() ? RB_ENGINE
: RB_DRIVER;
}
//
// Set up as initially not caching any realization
//
pbrush->vSetNotCached();
// no one's trying to cache a realization
// in this logical brush yet
pbrush->crFore((COLORREF)BO_NOTCACHED);
// no cached realization yet (no need to
// worry about crFore not being set when
// someone tries to check for caching,
// because we don't have a handle yet, and
// we'll lock when we do get the handle,
// forcing writes to flush)
//
// we are resetting the attributes / type.
//
if (bPen)
{
pbrush->ulStyle(HS_DITHEREDCLR);
FLONG flOldAttrs = pbrush->flAttrs() &
(BR_IS_PEN | BR_IS_OLDSTYLEPEN);
pbrush->flAttrs(BR_IS_SOLID | flOldAttrs);
}
else
{
pbrush->ulStyle(HS_DITHEREDCLR);
pbrush->flAttrs(BR_IS_SOLID | BR_DITHER_OK);
}
//
// Set the uniqueness so the are-you-
// really-dirty check in vInitBrush will
// not think an old realization is still valid.
//
pbrush->ulBrushUnique(pbrush->ulGlobalBrushUnique());
}
else
{
WARNING1("Error, SetSolidBrush with cShare != 1");
}
HandleLock.vUnlock();
}
}
if (prbrush)
{
prbrush->vRemoveRef(rbType);
}
}
}
#if DBG
else
{
if (pbrush->bIsGlobal())
{
WARNING1("bIsGlobal\n");
}
if (pbrush->flAttrs() & BR_IS_SOLID)
{
WARNING1("BR_IS_SOLID is set\n");
}
WARNING("GreSetSolidBrush not passed a solid color brush\n");
}
#endif
}
#if DBG
else
{
WARNING1("GreSetSolidBrush failed to lock down brush\n");
}
#endif
return(bReturn);
}
/******************************Public*Routine******************************\
* GreGetBrushColor
*
* Call for User to retrieve the color from any brush owned by any process
* so User can repaint the background correctly in full drag. To make sure
* we don't hose an app we need to hold the mult-lock while we do this so
* any operation by the app (such as a Delete) will wait and not fail
* because we're temporarily locking the brush down to peek inside of it.
*
* History:
* 14-Jun-1994 -by- Patrick Haluptzok patrickh
* Wrote it.
\**************************************************************************/
COLORREF GreGetBrushColor(HBRUSH hbr)
{
COLORREF clrRet = 0xFFFFFFFF;
//
// Grab the multi-lock so everyone waits while do our quick hack
// to return the brush color.
//
MLOCKFAST mlo;
//
// Lock it down but don't check ownership because we want to succeed
// no matter what.
//
//
// using try except to make sure we will not crash
// when a bad handle passed in.
//
__try
{
PENTRY pentry = &gpentHmgr[HmgIfromH(hbr)];
PBRUSH pbrush = (PBRUSH)(pentry->einfo.pobj);
if (pbrush)
{
if ((pbrush->ulStyle() == HS_SOLIDCLR) ||
(pbrush->ulStyle() == HS_DITHEREDCLR))
{
clrRet = pbrush->crColor();
}
}
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
WARNING1("GreGetBrushColor - bad handle passed in\n");
}
return(clrRet);
}
/******************************Public*Routine******************************\
* BRUSHMEMOBJ::BRUSHMEMOBJ
*
* Creates hatched brushes and solid color brushes.
*
* History:
* 29-Oct-1992 -by- Michael Abrash [mikeab]
* changed to get handle only after fully initialized
*
* Wed 26-Feb-1992 -by- Patrick Haluptzok [patrickh]
* rewrote to subsume other constructors, add new hatch styles.
*
* Sun 19-May-1991 -by- Patrick Haluptzok [patrickh]
* Wrote it.
\**************************************************************************/
BRUSHMEMOBJ::BRUSHMEMOBJ(COLORREF cr, ULONG ulStyle_, BOOL bPen, BOOL bSharedMem)
{
if (ulStyle_ > HS_NULL)
{
WARNING1("Invalid style type\n");
pbp.pbr = NULL;
return;
}
PBRUSH pbrush;
if ((pbp.pbr = pbrush = pbrAllocBrush(bPen)) == NULL)
{
WARNING1("Brush allocation failed\n");
return;
}
pbrush->crColor(cr);
pbrush->ulStyle(ulStyle_);
pbrush->hbmPattern(0);
pbrush->AttrFlags(0);
if (ulStyle_ < HS_DDI_MAX)
{
// The old hatch brushes have been extended to include all the default
// patterns passed back by the driver. There are 19 default pattens.
pbrush->flAttrs(BR_IS_HATCH | BR_NEED_BK_CLR | BR_IS_MASKING);
goto CreateHandle;
}
// Handle the other brush types
switch(ulStyle_)
{
case HS_SOLIDCLR:
pbrush->flAttrs(BR_IS_SOLID);
break;
case HS_DITHEREDCLR:
pbrush->flAttrs(BR_IS_SOLID | BR_DITHER_OK);
break;
case HS_SOLIDTEXTCLR:
pbrush->flAttrs(BR_IS_SOLID | BR_NEED_FG_CLR);
break;
case HS_DITHEREDTEXTCLR:
pbrush->flAttrs(BR_IS_SOLID | BR_NEED_FG_CLR | BR_DITHER_OK);
break;
case HS_SOLIDBKCLR:
pbrush->flAttrs(BR_IS_SOLID | BR_NEED_BK_CLR);
break;
case HS_DITHEREDBKCLR:
pbrush->flAttrs(BR_IS_SOLID | BR_NEED_BK_CLR | BR_DITHER_OK);
break;
case HS_NULL:
pbrush->flAttrs(BR_IS_NULL);
break;
default:
RIP("ERROR BRUSHMEMOBJ hatches invalid type");
}
// Now that everything is set up, create the handle and expose this logical
// brush
CreateHandle:
if (HmgInsertObject(pbrush, HMGR_ALLOC_ALT_LOCK, BRUSH_TYPE) == 0)
{
FREEOBJ(pbrush, BRUSH_TYPE);
pbp.pbr = NULL;
}
else
{
if (bSharedMem)
{
//
// Setup the user mode BRUSHATTR
//
PBRUSHATTR pUser = (PBRUSHATTR)HmgAllocateObjectAttr();
if (pUser)
{
HANDLELOCK BrushLock;
BrushLock.bLockHobj((HOBJ)pbrush->hHmgr,BRUSH_TYPE);
if (BrushLock.bValid())
{
PENTRY pent = BrushLock.pentry();
//
// fill up the brushattr
//
*pUser = pbrush->_Brushattr;
pent->pUser = (PVOID)pUser;
pbrush->pBrushattr(pUser);
BrushLock.vUnlock();
}
}
}
}
}
/******************************Public*Routine******************************\
* EBRUSHOBJ::vInitBrush
*
* Initializes the brush user object. If the color can be represented
* without dithering, we set iSolidColor.
*
* History:
* Tue 08-Dec-1992 -by- Michael Abrash [mikeab]
* Rewrote for speed.
*
* Sun 23-Jun-1991 -by- Patrick Haluptzok [patrickh]
* Wrote it.
\**************************************************************************/
VOID
EBRUSHOBJ::vInitBrush(
PDC pdc, // current dc or a fake dc with only back/foreground clr info
PBRUSH pbrushIn, // Current logical brush
XEPALOBJ palDC, // Target's DC palette
XEPALOBJ palSurf, // Target's surface palette
SURFACE *pSurface, // Target surface
BOOL bCanDither // If FALSE then never dither
)
{
// Note: If more members of pdc are accessed in the future, then code must be
// added in drvsup.cxx to initialize the members in each place a fake DC
// object is initialized. There's also a fake DC in bDynamicModeChange in
// opendc.cxx which must be updated.
// If the palSurf isn't valid, then the target is a bitmap for a palette
// managed device; therefore the palette means nothing until we actually blt,
// and only the DC palette is relevant. Likewise, if the target is a palette
// managed surface, the brush is realized as indices into the logical palette,
// and unless the logical palette is changed, the brush doesn't need to be
// rerealized. This causes us effectively to check the logical palette time
// twice, but that's cheaper than checking whether we need to check the surface
// palette time and then possibly checking it.
ULONG ulSurfTime = (palSurf.bValid() && !palSurf.bIsPalManaged()) ?
palSurf.ulTime() : 1;
#if DBG
bo_inits++;
#endif
// If the brush really is dirty, we have to set this anyway; if it's not dirty,
// this takes care of the case where the surface has changed out from under us,
// and then a realization is required and we would otherwise fault trying to
// access the target surface structure in the process of realization.
psoTarg1 = pSurface; // surface for which brush is realized
// The journaling code depends on this
// being set correctly. This has the PDEV
// for the device it's selected into.
COLORREF crTextDC = pdc->crTextClr();
COLORREF crBackDC = pdc->crBackClr();
LONG lIcmModeDC = pdc->lIcmMode();
HANDLE hcmXformDC = pdc->hcmXform();
// See if the brush really isn't dirty and doesn't need to be rerealized
if ( ( pbrushIn->ulBrushUnique() == _ulUnique ) &&
(!bCareAboutFg() || (crCurrentText() == crTextDC) ) &&
(!bCareAboutBg() || (crCurrentBack() == crBackDC) ) &&
(palDC.ulTime() == ulDCPalTime()) &&
(ulSurfTime == ulSurfPalTime()) &&
(pbrushIn != gpbrDCBrush)&&
(pbrushIn != gpbrDCPen) &&
(lIcmMode() == lIcmModeDC) &&
(hcmXform() == hcmXformDC) &&
(bCanDither == _bCanDither))
{
#if DBG
bo_notdirty++;
#endif
return;
}
// Get Cached Values
flAttrs = pbrushIn->flAttrs();
// Remember the characteristics of the brush
_pbrush = pbrushIn;
_ulUnique = pbrushIn->ulBrushUnique(); // brush uniqueness
crCurrentText1 = crTextDC; // text color at realization time
crCurrentBack1 = crBackDC; // background color at realization time
_ulDCPalTime = palDC.ulTime(); // DC palette set time at realization time
_ulSurfPalTime = ulSurfTime; // surface palette set time at realization time
_bCanDither = bCanDither; // dither enabled?
// Initialize ICM stuffs
BOOL bCMYKColorSolid = FALSE;
flColorType = 0; // Initialized with zero.
// Set icm modes
if (IS_ICM_ON(lIcmModeDC))
{
BOOL bIcmBrush = FALSE;
// color translation should happen, check we have nessesary data for ICM.
if (flAttrs & (BR_IS_SOLID|BR_IS_HATCH|BR_IS_MONOCHROME))
{
if (IS_ICM_HOST(lIcmModeDC))
{
// DC attributes should have ICM-ed color.
//
// (or with null-ColorTransform, no color translation happen)
if (flAttrs & (BR_IS_SOLID|BR_IS_MONOCHROME))
{
if ((flAttrs & (BR_NEED_FG_CLR|BR_NEED_BK_CLR)) ||
(pbrushIn == gpbrDCBrush) || (pbrushIn == gpbrDCPen))
{
bIcmBrush = TRUE;
}
}
if (bIcmBrush == FALSE)
{
if (pbrushIn->bIsPen())
{
if ((hcmXformDC == NULL) || pdc->bValidIcmPenColor())
{
bIcmBrush = TRUE;
}
else
{
ICMMSG(("vInitBrush():ERROR: No ICMed pen color for this brush\n"));
}
}
else
{
if ((hcmXformDC == NULL) || pdc->bValidIcmBrushColor())
{
bIcmBrush = TRUE;
}
else
{
ICMMSG(("vInitBrush():ERROR: No ICMed brush color for this brush\n"));
}
}
}
}
else // other ICM modes (Device and Apps)
{
bIcmBrush = TRUE;
}
}
else if (flAttrs & BR_IS_DIB)
{
if (IS_ICM_HOST(lIcmModeDC))
{
// Brush should have ICM-ed DIB
//
// (or with null-ColorTransform, no color translation happen)
if ((hcmXformDC == NULL) || pbrushIn->hFindIcmDIB(hcmXformDC))
{
bIcmBrush = TRUE;
}
else
{
ICMMSG(("vInitBrush():ERROR: No ICMed DIB for this brush\n"));
}
}
else // other ICM modes (Device and Apps)
{
bIcmBrush = TRUE;
}
}
else
{
// Other stlyes, no ICM
}
if (bIcmBrush)
{
lIcmMode(lIcmModeDC); // ICM mode
hcmXform(hcmXformDC); // ICM molor Transform handle
// setup colortype flag.
if (bIsAppsICM() || bIsHostICM())
{
flColorType |= BR_HOST_ICM;
}
else if (bIsDeviceICM())
{
flColorType |= BR_DEVICE_ICM;
}
// If the brush is solid, iSolidColor will have CMKY color. Otherwise,
// iSolidColor will be 0xFFFFFFFF and flColorType does not have BR_CMYKCOLOR.
bCMYKColorSolid = (bIsCMYKColor() && (flAttrs & BR_IS_SOLID));
if (bCMYKColorSolid)
{
flColorType |= BR_CMYKCOLOR; // color type is CMYK color
}
}
else
{
ICMMSG(("vInitBrush():This brush is not ICMed\n"));
lIcmMode(DC_ICM_OFF); // ICM mode
hcmXform(NULL); // ICM molor Transform handle
}
}
else
{
lIcmMode(DC_ICM_OFF); // ICM mode
hcmXform(NULL); // ICM molor Transform handle
}
// Get the target PDEV
PDEVOBJ po(pSurface->hdev());
ASSERTGDI(po.bValid(), "ERROR BRUSHOBJ PDEVOBJ");
// Set palettes
palDC1.ppalSet(palDC.ppalGet());
palSurf1.ppalSet(palSurf.ppalGet());
palMeta1.ppalSet(po.ppalSurfNotDynamic());
_iMetaFormat = po.iDitherFormatNotDynamic();
ASSERTGDI(pSurface != NULL, "ERROR BRUSHOBJ::bInit0");
ASSERTGDI(palDC.bValid(), "ERROR BRUSHOBJ::bInit4");
// Clean up what was already here
// If this brush object had an engine brush realization, get rid of it
if (pengbrush1 != (PENGBRUSH) NULL)
{
PRBRUSH prbrush = pengbrush1; // point to engine brush realization
prbrush->vRemoveRef(RB_ENGINE); // decrement the reference count on the
// realization and free the brush if
// this is the last reference
pengbrush1 = NULL; // mark that there's no realization
}
// If this brush object had a device brush realization, get rid of it
if (pvRbrush != (PVOID) NULL)
{
PRBRUSH prbrush = (PDBRUSH)DBRUSHSTART(pvRbrush);
// point to DBRUSH (pvRbrush points to
// realization, which is at the end of DBRUSH)
prbrush->vRemoveRef(RB_DRIVER);
// decrement the reference count on the
// realization and free the brush if
// this is the last reference
pvRbrush = NULL; // mark that there's no realization
}
// Remember the color so we do the realization code correctly later
// if it's a dithered brush. We may need this even if we have
// a hit in the cache since we have driver/engine distinction.
if (flAttrs & BR_IS_SOLID)
{
if (flAttrs & BR_NEED_FG_CLR)
{
crRealize = crCurrentText(); // use text brush
if (bIsHostICM())
crRealizeOrignal = pdc->ulTextClr();
}
else if (flAttrs & BR_NEED_BK_CLR)
{
crRealize = crCurrentBack(); // use back brush
if (bIsHostICM())
crRealizeOrignal = pdc->ulBackClr();
}
else if (pbrushIn == gpbrDCBrush)
{
crRealize = pdc->crDCBrushClr(); // use DC brush
if (bIsHostICM())
crRealizeOrignal = pdc->ulDCBrushClr();
}
else if (pbrushIn == gpbrDCPen)
{
crRealize = pdc->crDCPenClr(); // use DC pen
if (bIsHostICM())
crRealizeOrignal = pdc->ulDCPenClr();
}
else
{
crRealize = pbrushIn->crColor();
if (bIsHostICM())
{
crRealizeOrignal = crRealize;
if (pbrushIn->bIsPen())
{
if (pdc->bValidIcmPenColor())
{
crRealize = pdc->crIcmPenColor(); // use ICM translated pen
}
}
else
{
if (pdc->bValidIcmBrushColor())
{
crRealize = pdc->crIcmBrushColor(); // use ICM translated brush
}
}
}
}
}
else if (flAttrs & BR_IS_HATCH)
{
crRealize = pbrushIn->crColor();
if (bIsHostICM())
{
crRealizeOrignal = crRealize;
if (pbrushIn->bIsPen())
{
if (pdc->bValidIcmPenColor())
{
crRealize = pdc->crIcmPenColor();
}
}
else
{
if (pdc->bValidIcmBrushColor())
{
crRealize = pdc->crIcmBrushColor();
}
}
}
}
// See if there's a cached realization that we can use
// Note that the check for crFore MUST come first, because if and only if
// that field is not BO_NOTCACHED is there a valid cached realization.
#if DBG
bo_realize++;
if ( (pbrushIn->crFore() == BO_NOTCACHED) )
{
bo_missnotcached++;
}
else if ( pbrushIn->bCareAboutFg() &&
(pbrushIn->crFore() != crTextDC) )
{
bo_missfg++;
}
else if (pbrushIn->bCareAboutBg() &&
(pbrushIn->crBack() != crBackDC) )
{
bo_missbg++;
}
else if ( pbrushIn->ulPalTime() != ulDCPalTime() )
{
bo_misspaltime++;
}
else if ( pbrushIn->ulSurfTime() != ulSurfPalTime() )
{
bo_misssurftime++;
}
else
{
bo_cachehit++;
}
#endif
if (
(pbrushIn->crFore() != BO_NOTCACHED) &&
(
(!pbrushIn->bCareAboutFg()) ||
(pbrushIn->crFore() == crTextDC)
) &&
(
(!pbrushIn->bCareAboutBg()) ||
(pbrushIn->crBack() == crBackDC)
) &&
(pbrushIn->ulPalTime() == ulDCPalTime()) &&
(pbrushIn->ulSurfTime() == ulSurfPalTime()) &&
(pbrushIn->hdevRealization() == po.hdev()) &&
(pbrushIn != gpbrDCBrush) &&
(pbrushIn != gpbrDCPen)
)
{
// Uncache the realization according to the realization type (solid,
// driver realization, or engine realization)
if (pbrushIn->bCachedIsSolid())
{
// Retrieve the cached solid color and done
iSolidColor = (ULONG)pbrushIn->ulRealization();
crPaletteColor = pbrushIn->crPalColor();
}
else
{
// See whether this is an engine or driver realization
PRBRUSH prbrush = (PRBRUSH)pbrushIn->ulRealization();
if (pbrushIn->bIsEngine())
{
pengbrush1 = (PENGBRUSH)prbrush;
}
else
{
// Skip over the RBRUSH at the start of the DBRUSH, so that the
// driver doesn't see that
pvRbrush = (PVOID)(((PDBRUSH)prbrush)->aj);
}
// Whether this was an engine or driver realization, now we've got
// it selected into another DC, so increment the reference count
// so it won't get deleted until it's no longer selected into any
// DC and the logical brush no longer exists
prbrush->vAddRef();
// Indicate that this is a pattern brush
iSolidColor = 0xffffffff;
crPaletteColor = pbrushIn->crPalColor();
}
// Nothing more to do once we've found that the realization is cached;
// this tells us all we hoped to find out in this call, either the
// solid color for the realization or else that the realization isn't
// solid (in which case we probably found the realization too, although
// if the cached realization is driver and this time the engine will do
// the drawing, or vice-versa, the cached realization won't help us)
return;
}
// If brush isn't based on color (if it is a bitmap or hatch), we're done
// here, because all we want to do is set iSolidColor if possible
if (!(flAttrs & BR_IS_SOLID))
{
iSolidColor = crPaletteColor = 0xffffffff;
return;
}
// See if we can find exactly the color we want
if (bCMYKColorSolid)
{
// crRealize is CMKY color just set it to iSolidColor
iSolidColor = crPaletteColor = crRealize;
}
else if (po.bCapsForceDither() && bCanDither)
{
// printer drivers may set the FORCEDITHER flag. In this case, we always
// want to dither brushes, even if they map to a color in the drivers palette.
iSolidColor = 0xffffffff;
crPaletteColor = crRealize;
}
else
{
iSolidColor =
ulGetMatchingIndexFromColorref(
palSurf,
palDC,
crRealize
);
crPaletteColor = rgbFromColorref(palSurf,
palDC,
crRealize
);
}
// Under CMYK color context, there is no dither.
if ((iSolidColor == 0xFFFFFFFF) && (!bCMYKColorSolid))
{
// Not an exact match. If we can dither, then we're done for now; we'll
// realize the brush when the driver wants it, so if all conditions are
// met for dithering this brush, then we're done
// we dither the brush if the caller says we can and if either the brush
// says it is ditherable or the driver has requested dithering.
if (((flAttrs & BR_DITHER_OK) || (po.bCapsForceDither())) &&
bCanDither)
{
// ...and the PDEV allows color dithering and either the bitmap is
// for a palette managed device, or if the surface and device
// palettes are the same palette, or if the destination surface is
// monochrome and the pdev has hooked mono dithering.
//
// Note: There is a dynamic mode change synchronization hole here
// between the time we check GCAPS_COLOR_DITHER/MONO_DITHER
// and the time that we go to actually realize the brush --
// the driver's capabilities may have changed in the mean
// time. Note that this will happen only when drawing to
// DIB based compatible bitmaps. Since it will be rare, and
// since we won't fall over, I'm letting it through...
if (
(
(
(!palSurf.bValid()) ||
(palSurf.ppalGet() == po.ppalSurfNotDynamic())
) &&
(po.flGraphicsCapsNotDynamic() & GCAPS_COLOR_DITHER)
) ||
(palSurf.bIsMonochrome() &&
(po.flGraphicsCapsNotDynamic() & GCAPS_MONO_DITHER)
)
)
{
// ...then we can dither this brush, so we can't set iSolidColor
// and we're done. Dithering will be done when the driver
// requests realization
//
crPaletteColor = crRealize;
return;
}
}
// We can't dither and there's no exact match, so find the nearest
// color and that'll have to do
if (pSurface->iFormat() == BMF_1BPP)
{
// For monochrome surface, we'll have background mapped to
// background and everything else mapped to foreground.
iSolidColor = ulGetNearestIndexFromColorref(
palSurf,
palDC,
crBackDC,
SE_DONT_SEARCH_EXACT_FIRST
);
crPaletteColor = rgbFromColorref(palSurf,
palDC,
crBackDC);
if (crBackDC != crRealize)
{
iSolidColor = 1 - iSolidColor;
// Obtain corresponding color from index.
PAL_ULONG ulPalTemp;
ulPalTemp.pal = palSurf.palentryGet(iSolidColor);
crPaletteColor = ulPalTemp.ul;
}
}
else
{
iSolidColor = ulGetNearestIndexFromColorref(
palSurf,
palDC,
crRealize,
SE_DONT_SEARCH_EXACT_FIRST
);
crPaletteColor = rgbFromColorref(palSurf,
palDC,
crRealize);
}
}
// See if we can cache this brush color in the logical brush; we can't if
// another realization has already been cached in the logical brush
// See vTryToCacheRealization, in BRUSHDDI.CXX, for a detailed explanation
// of caching in the logical brush
if ( !pbrushIn->bCacheGrabbed() )
{
// Try to grab the "can cache" flag; if we don't get it, someone just
// sneaked in and got it ahead of us, so we're out of luck and can't
// cache
if ( pbrushIn->bGrabCache() )
{
// We got the "can cache" flag, so now we can cache this realization
// in the logical brush
// These cache ID fields must be set before crFore, because crFore
// is the key that indicates when the cached realization is valid.
// If crFore is -1 when the logical brush is being realized, we
// just go realize the brush; if it's not -1, we check the cache ID
// fields to see if we can use the cached fields.
// InterlockedExchange() is used below to set crFore to make sure
// the cache ID fields are set before crFore
pbrushIn->crBack(crCurrentBack1);
pbrushIn->ulPalTime(ulDCPalTime());
pbrushIn->ulSurfTime(ulSurfPalTime());
pbrushIn->ulRealization(iSolidColor);
pbrushIn->crPalColor(crPaletteColor);
pbrushIn->SetSolidRealization();
// This must be set last, because once it's set, other selections
// of this logical brush will attempt to use the cached brush. The
// use of InterlockedExchange in this method enforces this
pbrushIn->crForeLocked(crCurrentText1);
// The realization is now cached in the logical brush
}
}
return;
}
/******************************Public*Routine******************************\
* EBRUSHOBJ::vNuke()
*
* Clean up framed EBRUSHOBJ
*
* History:
* 20-Mar-1992 -by- Donald Sidoroff [donalds]
* Wrote it.
\**************************************************************************/
VOID EBRUSHOBJ::vNuke()
{
if (pengbrush1 != (PENGBRUSH) NULL)
{
PRBRUSH prbrush = pengbrush1; // point to engine brush realization
prbrush->vRemoveRef(RB_ENGINE); // decrement the reference count on the
// realization and free the brush if
// this is the last reference
}
if (pvRbrush != (PVOID) NULL)
{
PRBRUSH prbrush = (PDBRUSH)DBRUSHSTART(pvRbrush);
// point to DBRUSH (pvRbrush points to
// realization, which is at the end of DBRUSH)
prbrush->vRemoveRef(RB_DRIVER);
// decrement the reference count on the
// realization and free the brush if
// this is the last reference
}
}
// This is the brusheng.cxx section
/******************************Public*Routine******************************\
* bInitBRUSHOBJ
*
* Initializes the default brushes and and the dclevel default values for
* brushes and pens.
*
* Explanation of the NULL brush (alias Hollow Brush)
* The Null brush is special. Only 1 is ever created
* (at initialization time in hbrNull). The only API's for
* getting a Null brush are CreateBrushIndirect and GetStockObject which
* both return "the 1 and only 1" Null brush. A Null brush is never
* realized by a driver or the engine. No output call should ever occur
* that requires a brush if the brush is NULL, the engine should stop
* these before they get to the driver.
*
* History:
* 20-May-1991 -by- Patrick Haluptzok patrickh
* Wrote it.
\**************************************************************************/
extern "C" BOOL bInitBrush(
int iBrush,
COLORREF cr,
DWORD dwHS,
PULONG_PTR pdw,
BOOL bEnableDither
)
{
BOOL bSuccess = FALSE;
BRUSHMEMOBJ brmo(cr,dwHS,FALSE,FALSE);
if (brmo.bValid())
{
brmo.vKeepIt();
brmo.vGlobal();
if (bEnableDither)
brmo.vEnableDither();
if (pdw)
*pdw = (ULONG_PTR)brmo.pbrush();
bSetStockObject(brmo.hbrush(),iBrush);
// init DcAttrDefault brush
if (iBrush == WHITE_BRUSH)
{
DcAttrDefault.hbrush = brmo.hbrush();
}
bSuccess = TRUE;
}
else
{
#if DBG
DbgPrint("couldn't create default brush %lx, %lx\n",cr,iBrush);
#endif
return(FALSE);
}
return(bSuccess);
}
BOOL bInitBRUSHOBJ()
{
if (!bInitBrush(WHITE_BRUSH,(COLORREF)RGB(0xFF,0xFF,0xFF),
HS_DITHEREDCLR,(PULONG_PTR)&dclevelDefault.pbrFill,FALSE) ||
!bInitBrush(BLACK_BRUSH, (COLORREF)RGB(0x0, 0x0, 0x0), HS_DITHEREDCLR,NULL,FALSE) ||
!bInitBrush(GRAY_BRUSH, (COLORREF)RGB(0x80,0x80,0x80),HS_DITHEREDCLR,NULL,TRUE) ||
!bInitBrush(DKGRAY_BRUSH,(COLORREF)RGB(0x40,0x40,0x40),HS_DITHEREDCLR,NULL,TRUE) ||
!bInitBrush(LTGRAY_BRUSH,(COLORREF)RGB(0xc0,0xc0,0xc0),HS_DITHEREDCLR,NULL,TRUE) ||
!bInitBrush(NULL_BRUSH, (COLORREF)0,HS_NULL,(PULONG_PTR)&gpbrNull,FALSE))
{
return(FALSE);
}
// Init default Null Pen
{
BRUSHMEMOBJ brmo((COLORREF) 0, HS_NULL, TRUE, FALSE); // TRUE signifies a pen
if (brmo.bValid())
{
brmo.vKeepIt();
brmo.vGlobal();
brmo.vSetOldStylePen();
brmo.flStylePen(PS_NULL);
brmo.lWidthPen(1);
HmgModifyHandleType((HOBJ)MODIFY_HMGR_TYPE(brmo.hbrush(),LO_PEN_TYPE));
bSetStockObject(brmo.hbrush(),NULL_PEN);
gpPenNull = (PPEN)brmo.pbrush();
}
else
{
WARNING("Failed Null Pen");
return(FALSE);
}
}
// Init default Black Pen
{
BRUSHMEMOBJ brmo((COLORREF) (RGB(0,0,0)), HS_DITHEREDCLR, TRUE, FALSE);
if (brmo.bValid())
{
brmo.vKeepIt();
brmo.vGlobal();
brmo.vSetOldStylePen();
brmo.flStylePen(PS_SOLID);
brmo.lWidthPen(0);
brmo.l_eWidthPen(IEEE_0_0F);
brmo.iJoin(JOIN_ROUND);
brmo.iEndCap(ENDCAP_ROUND);
brmo.pstyle((PFLOAT_LONG) NULL);
HmgModifyHandleType((HOBJ)MODIFY_HMGR_TYPE(brmo.hbrush(),LO_PEN_TYPE));
bSetStockObject(brmo.hbrush(),BLACK_PEN);
DcAttrDefault.hpen = (HPEN)brmo.hbrush();
dclevelDefault.pbrLine = brmo.pbrush();
}
else
{
WARNING("failed black pen");
return(FALSE);
}
}
// Init default White Pen
{
BRUSHMEMOBJ brmo((COLORREF) (RGB(0xFF,0xFF,0xFF)), HS_DITHEREDCLR, TRUE, FALSE);
if (brmo.bValid())
{
brmo.vKeepIt();
brmo.vGlobal();
brmo.vSetOldStylePen();
brmo.flStylePen(PS_SOLID);
brmo.lWidthPen(0);
brmo.l_eWidthPen(IEEE_0_0F);
brmo.iJoin(JOIN_ROUND);
brmo.iEndCap(ENDCAP_ROUND);
brmo.pstyle((PFLOAT_LONG) NULL);
HmgModifyHandleType((HOBJ)MODIFY_HMGR_TYPE(brmo.hbrush(),LO_PEN_TYPE));
bSetStockObject(brmo.hbrush(),WHITE_PEN);
}
else
{
WARNING("Failed white pen");
return(FALSE);
}
}
// Init the stock DC Pen
{
BRUSHMEMOBJ brmo((COLORREF) (RGB(0,0,0)), HS_DITHEREDCLR, TRUE, FALSE);
if (brmo.bValid())
{
brmo.vKeepIt();
brmo.vGlobal();
brmo.vSetOldStylePen();
brmo.flStylePen(PS_SOLID);
brmo.lWidthPen(0);
brmo.l_eWidthPen(IEEE_0_0F);
brmo.iJoin(JOIN_ROUND);
brmo.iEndCap(ENDCAP_ROUND);
brmo.pstyle((PFLOAT_LONG) NULL);
HmgModifyHandleType((HOBJ)MODIFY_HMGR_TYPE(brmo.hbrush(),LO_PEN_TYPE));
bSetStockObject(brmo.hbrush(),DC_PEN);
ghbrDCPen = brmo.hbrush();
gpbrDCPen = brmo.pbrush();
}
else
{
WARNING("Failed DC pen");
return(FALSE);
}
}
// init the text brush
{
BRUSHMEMOBJ brmo((COLORREF) (RGB(0,0,0)),HS_DITHEREDTEXTCLR,FALSE,FALSE);
if (brmo.bValid())
{
brmo.vKeepIt();
brmo.vGlobal();
ghbrText = brmo.hbrush();
gpbrText = brmo.pbrush();
}
else
{
WARNING("Could not create default text brush");
return(FALSE);
}
}
// init the background brush
{
BRUSHMEMOBJ brmo((COLORREF) (RGB(0xff,0xff,0xff)),HS_DITHEREDBKCLR,FALSE,FALSE);
if (brmo.bValid())
{
brmo.vKeepIt();
brmo.vGlobal();
ghbrBackground = brmo.hbrush();
gpbrBackground = brmo.pbrush();
}
else
{
WARNING("Could not create default background brush");
return(FALSE);
}
}
// init the global pattern gray brush
{
static WORD patGray[8] = { 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa };
HBITMAP hbmGray;
hbmGray = GreCreateBitmap(8, 8, 1, 1, (LPBYTE)patGray);
if (hbmGray == (HBITMAP) 0)
{
WARNING1("bInitBRUSHOBJ failed GreCreateBitmap\n");
return(FALSE);
}
ghbrGrayPattern = GreCreatePatternBrush(hbmGray);
if (ghbrGrayPattern == (HBRUSH) 0)
{
WARNING1("bInitBRUSHOBJ failed GreCreatePatternBrush\n");
return(FALSE);
}
GreDeleteObject(hbmGray);
GreSetBrushOwnerPublic((HBRUSH)ghbrGrayPattern);
}
// init the stock DC brush
{
BRUSHMEMOBJ brmo((COLORREF) (RGB(0xff,0xff,0xff)),HS_DITHEREDCLR,FALSE,FALSE);
if (brmo.bValid())
{
brmo.vKeepIt();
brmo.vGlobal();
bSetStockObject(brmo.hbrush(), DC_BRUSH);
ghbrDCBrush = brmo.hbrush();
gpbrDCBrush = brmo.pbrush();
}
else
{
WARNING("Could not create direct dc brush");
return(FALSE);
}
}
return(TRUE);
}
/******************************Public*Routine******************************\
* GreSelectBrush
*
* Selects the given brush into the given DC. Fast SelectObject
*
* History:
* Thu 21-Oct-1993 -by- Patrick Haluptzok [patrickh]
* wrote it.
\**************************************************************************/
HBRUSH GreSelectBrush(HDC hdc, HBRUSH hbrush)
{
HBRUSH hbrReturn = (HBRUSH) 0;
//
// Try to lock the DC. If we fail, we just return failure.
//
XDCOBJ dco(hdc);
if (dco.bValid())
{
//
// call DC locked version
//
hbrReturn = GreDCSelectBrush(dco.pdc,hbrush);
dco.vUnlockFast();
}
return(hbrReturn);
}
/******************************Public*Routine******************************\
* GreDCSelectBrush
*
* Select brush with dc already locked
*
* Arguments:
*
* pdc - locked DC pointer
* hbrush - brush to select
*
* Return Value:
*
* Old hbrush or NULL
*
* History:
*
* 19-May-1995 : copied from GreSelectBrush
*
\**************************************************************************/
HBRUSH
GreDCSelectBrush(
PDC pdc,
HBRUSH hbrush
)
{
HBRUSH hbrReturn = (HBRUSH) 0;
PBRUSH pbrush = NULL;
XDCOBJ dco;
dco.pdc = pdc;
if (dco.bValid())
{
HBRUSH hbrOld;
//
// The DC is locked. Set the return value to the old brush in the DC.
//
hbrOld = (HBRUSH) (dco.pdc->pbrushFill())->hGet();
//
// the return value should be the one cached in the dc
//
hbrReturn = dco.pdc->hbrush();
//
// If the new brush is the same as the old brush, nothing to do.
//
if (DIFFHANDLE(hbrush,hbrOld))
{
//
// Try to lock down the logical brush so we can get the pointer out.
//
pbrush = (BRUSH *)HmgShareCheckLock((HOBJ)hbrush, BRUSH_TYPE);
if (pbrush)
{
//
// Undo the lock from when the brush was selected.
//
DEC_SHARE_REF_CNT_LAZY0(dco.pdc->pbrushFill());
//
// Changing pbrushfill, set flag to force re-realization
//
dco.ulDirtyAdd(DIRTY_FILL);
//
// Save the pointer to the logical brush in the DC. We don't
// unlock the logical brush, because the alt lock count in the
// logical brush is the reference count for DCs in which the brush
// is currently selected; this protects us from having the actual
// logical brush deleted while it's selected into a DC, and allows
// us to reference the brush with a pointer rather than having to
// lock down the logical brush every time.
//
dco.pdc->pbrushFill(pbrush);
}
else
{
WARNING1("SelectBrush got invalid brush handle\n");
hbrReturn = NULL;
}
}
else
{
pbrush = dco.pdc->pbrushFill();
}
if (pbrush != NULL)
{
if (hbrReturn != NULL)
{
//
// must still check brush for new color
//
PBRUSHATTR pUser = pbrush->_pBrushattr;
//
// if the brush handle is a cached solid brush,
// call GreSetSolidBrushInternal to change the color
//
if (pUser != &pbrush->_Brushattr)
{
if (pUser->AttrFlags & ATTR_NEW_COLOR)
{
//
// force re-realization in case handle was same
//
dco.ulDirtyAdd(DIRTY_FILL);
//
// set the new color for the cached brush.
// Note: since pbrush is pulled straight
// from the DC, it's reference count will
// be 1, which is needed by SetSolidBrush
//
if (!GreSetSolidBrushLight(pbrush,pUser->lbColor,FALSE))
{
WARNING1("GreSyncbrush failed to setsolidbrushiternal\n");
}
pUser->AttrFlags &= ~ATTR_NEW_COLOR;
}
}
}
dco.pdc->hbrush(hbrush);
dco.pdc->ulDirtySub(DC_BRUSH_DIRTY);
}
}
return(hbrReturn);
}
/******************************Public*Routine******************************\
* GreDCSelectPen
* Selects a hpen into the given pdc
*
* Arguments:
*
* pdc - locked dc
* hpen - hpen to select
*
* Return Value:
*
* old hpen
*
* History:
*
* 29-Jan-1996 -by- Mark Enstrom [marke]
*
\**************************************************************************/
HPEN GreDCSelectPen(
PDC pdc,
HPEN hpen
)
{
HPEN hpReturn = (HPEN) NULL;
PPEN ppen = NULL;
//
// Try to lock the DC. If we fail, we just return failure.
//
XDCOBJ dco;
dco.pdc = pdc;
if (dco.bValid())
{
HPEN hpOld;
BOOL bRealize = FALSE;
//
// hpOld is the pen (LINE BRUSH) currently realized in the DC
//
hpOld = (HPEN) (dco.pdc->pbrushLine())->hGet();
//
// Set the return value to the old pen in the DCATTR.
// This is the last hpen the user selected
//
hpReturn = (HPEN)dco.pdc->hpen();
//
// If the new pen is the same as the old pen, nothing to do.
//
if (DIFFHANDLE(hpen, hpOld))
{
//
// Try to lock down the logical brush so we can get the pointer out.
//
ppen = (PEN *)HmgShareCheckLock((HOBJ)hpen, BRUSH_TYPE);
if (ppen && ppen->bIsPen())
{
//
// Undo the lock from when the pen was selected.
//
DEC_SHARE_REF_CNT_LAZY0(dco.pdc->pbrushLine());
//
// Mark line relization is invalid.
//
dco.ulDirtyAdd(DIRTY_LINE);
//
// Save the pointer to the logical brush in the DC. We don't
// unlock the logical brush, because the alt lock count in the
// logical brush is the reference count for DCs in which the brush
// is currently selected; this protects us from having the actual
// logical brush deleted while it's selected into a DC, and allows
// us to reference the brush with a pointer rather than having to
// lock down the logical brush every time.
//
dco.pdc->pbrushLine(ppen);
//
// The pen changed, so realize the new LINEATTRS, based on
// the current world transform.
//
bRealize = TRUE;
}
else
{
WARNING1("SelectPen got invalid pen handle\n");
//
// If this is not pen, can't select it as pen.
//
if (ppen)
{
DEC_SHARE_REF_CNT(ppen);
ppen = NULL;
}
hpReturn = NULL;
}
}
else
{
ppen = (PPEN)dco.pdc->pbrushLine();
}
//
// In case the handle stays the same, but the pen is new
// due to re-use of a user hpen, so re-realize it.
//
if (ppen != (PPEN) NULL)
{
if (hpReturn != NULL)
{
PBRUSHATTR pUser = ppen->_pBrushattr;
//
// if the brush handle is a cached solid brush,
// call GreSetSolidBrushInternal to change the color
//
if (pUser != &ppen->_Brushattr)
{
if (pUser->AttrFlags & ATTR_NEW_COLOR)
{
//
// set the new color for the cached brush.
// Note: since pbrush is pulled straight
// from the DC, it's reference count will
// be 1, which is needed by SetSolidBrush
//
if (!GreSetSolidBrushLight(ppen,pUser->lbColor,TRUE))
{
WARNING ("GreDCSelectPen failed to setsolidbrushiternal\n");
}
dco.ulDirtyAdd(DIRTY_LINE);
pUser->AttrFlags &= ~ATTR_NEW_COLOR;
bRealize = TRUE;
}
}
if (bRealize)
{
//
// The pen changed, so realize the new LINEATTRS, based on
// the current world transform.
//
EXFORMOBJ exo(dco, WORLD_TO_DEVICE);
dco.pdc->vRealizeLineAttrs(exo);
LINEATTRS *pla = dco.plaRealized();
}
}
dco.pdc->hpen(hpen);
dco.pdc->ulDirtySub(DC_PEN_DIRTY);
}
}
return(hpReturn);
}
/******************************Public*Routine******************************\
* GreSelectPen
*
* Selects the given brush into the given DC. Fast SelectObject
*
* History:
* Thu 21-Oct-1993 -by- Patrick Haluptzok [patrickh]
* wrote it.
\**************************************************************************/
HPEN GreSelectPen(HDC hdc, HPEN hpen)
{
HPEN hpenReturn = (HPEN) 0;
//
// Try to lock the DC. If we fail, we just return failure.
//
XDCOBJ dco(hdc);
if (dco.bValid())
{
//
// call DC locked version
//
hpenReturn = GreDCSelectPen(dco.pdc,hpen);
dco.vUnlockFast();
}
return(hpenReturn);
}
/******************************Public*Routine******************************\
* bDeleteBrush
*
* This will delete the brush. The brush can only be deleted if it's not
* global and not being used by anyone else.
*
* History:
*
* 7-Feb-1996 -by- Mark Enstrom [marke]
* Add PEB caching for brush and pen objects
* 23-May-1991 -by- Patrick Haluptzok patrickh
* Wrote it.
\**************************************************************************/
BOOL bDeleteBrush(HBRUSH hbrush, BOOL bCleanup)
{
PBRUSHPEN pbp;
BOOL bReturn = TRUE;
HBRUSH hbrushNew;
BOOL bDelete = TRUE;
PBRUSHATTR pUser = NULL;
PENTRY pentTmp;
BOOL bMakeNonStock = FALSE;
//
// check handle for user-mode brush
//
if (!bCleanup)
{
HANDLELOCK BrushLock;
BrushLock.bLockHobj((HOBJ)hbrush,BRUSH_TYPE);
if (BrushLock.bValid())
{
POBJ pobj = BrushLock.pObj();
pUser = (PBRUSHATTR)BrushLock.pUser();
ASSERTGDI(pobj->cExclusiveLock == 0, "deletebrush - exclusive lock not 0\n");
//
// If Brush is still in use, mark for lazy deletion and return true
//
if (BrushLock.ShareCount() > 0)
{
((PBRUSH)pobj)->AttrFlags(ATTR_TO_BE_DELETED);
bDelete = FALSE;
}
else if (pUser != (PBRUSHATTR)NULL)
{
if (!(pUser->AttrFlags & ATTR_CACHED))
{
BOOL bPen = ((PPEN)pobj)->bIsPen();
INT iType = LO_TYPE(hbrush);
#if DBG
//
// make sure handle type agrees with bPen
//
if (bPen)
{
ASSERTGDI(((iType == LO_PEN_TYPE) || (iType == LO_EXTPEN_TYPE)),
"bDeleteBrush Error: PEN TYPE NOT LO_PEN OR LO_EXTPEN");
}
else
{
ASSERTGDI((iType == LO_BRUSH_TYPE),
"bDeleteBrush error: BRUSH type not LO_BRUSH_TYPE");
}
#endif
//
// try to cache the solid brush
// don't cache LO_EXTPEN_TYPE
//
if ((((PBRUSH)pobj)->flAttrs() & BR_IS_SOLID) &&
(!bPen || iType != LO_EXTPEN_TYPE))
{
BOOL bStatus;
bStatus = bPEBCacheHandle(hbrush,bPen?PenHandle:BrushHandle,(POBJECTATTR)pUser,(PENTRY)BrushLock.pentry());
if (bStatus)
{
bDelete = FALSE;
}
}
}
else
{
//
// brush is already cached
//
WARNING1("Trying to delete brush marked as cached\n");
bDelete = FALSE;
}
}
if (bDelete)
{
if (bMakeNonStock = ((PBRUSH)pobj)->bIsMakeNonStock())
{
((PBRUSH)pobj)->vClearMakeNonStock();
}
}
BrushLock.vUnlock();
}
}
if (bDelete)
{
if (bMakeNonStock)
{
STOCKINFO("Brush(%p) is marked MakeNonStock. Doing it\n", hbrush);
if(!GreMakeBrushNonStock(hbrush))
STOCKWARNING("GreMakeBrushNonStock (%p) failed\n", hbrush);
}
//
// Try and remove handle from Hmgr. This will fail if the brush
// is locked down on any threads or if it has been marked global
// or undeletable.
//
pbp.pbr = (PBRUSH) HmgRemoveObject((HOBJ)hbrush, 0, 0, FALSE, BRUSH_TYPE);
if (pbp.pbr!= NULL)
{
//
// Free the style array memory if there is some and it's
// not pointing to our stock default styles:
//
if (pbp.pbr->bIsPen())
{
if ((pbp.ppen->pstyle() != (PFLOAT_LONG) NULL) &&
!pbp.ppen->bIsDefaultStyle())
{
//
// We don't set the field to NULL since this brush
// is on it's way out.
//
VFREEMEM(pbp.ppen->pstyle());
}
}
//
// Free the bitmap pattern in the brush.
//
if (pbp.pbr->hbmPattern())
{
//
// We don't set the field to NULL since this brush
// is on it's way out.
//
BOOL bTemp = bDeleteSurface((HSURF)pbp.pbr->hbmPattern());
ASSERTGDI(bTemp, "ERROR How could pattern brush failed deletion?");
}
//
// Un-reference count the realization cached in the logical brush,
// if any. We don't have to worry about anyone else being in the
// middle of trying to cache a realization for this brush because
// we have removed it from Hmgr and noone else has it locked down.
// We only have to do this if there is a cached realization and the
// brush is non-solid.
//
if ((pbp.pbr->crFore() != BO_NOTCACHED) &&
!pbp.pbr->bCachedIsSolid())
{
ASSERTGDI(pbp.pbr->ulRealization() != NULL,
"ERROR ulRealization() is NULL");
((PRBRUSH)pbp.pbr->ulRealization())->vRemoveRef(
pbp.pbr->bIsEngine() ? RB_ENGINE : RB_DRIVER);
}
//
// Brush is DIB pattern ? if so we may need to free ICM DIBs
//
if (pbp.pbr->flAttrs() & BR_IS_DIB)
{
//
// Free cached color translated ICM DIBs.
//
pbp.pbr->vDeleteIcmDIBs();
}
FREEOBJ(pbp.pbr, BRUSH_TYPE);
//
// free pUser
//
if (!bCleanup && (pUser != (PBRUSHATTR)NULL))
{
HmgFreeObjectAttr((POBJECTATTR)pUser);
}
}
else
{
//
// Under Win31 deleting stock objects returns True.
//
BRUSHSELOBJ bo(hbrush);
if (!bo.bValid() || !bo.bIsGlobal())
bReturn = FALSE;
}
}
return(bReturn);
}
/******************************Public*Routine******************************\
* GreSetBrushGlobal
*
* Sets the brush to be a global one.
*
\**************************************************************************/
void
GreSetBrushGlobal(HBRUSH hbr)
{
BRUSHSELOBJ ebo(hbr);
if (ebo.bValid())
{
ebo.vGlobal();
}
}
/******************************Public*Routine******************************\
* GreMakeBrushStock
*
* Make the brush a stock brush.
*
\**************************************************************************/
HBRUSH
GreMakeBrushStock(HBRUSH hbr)
{
BRUSHSELOBJAPI ebo(hbr);
HANDLE bRet = 0;
BOOL bHandleModified = TRUE;
// Can make the brush a stock brush only when:
// (1) It is valid
// (2) Its not global already (i.e already stock)
// (3) Its not a DIBSection based brush.
// (4) Its not selected into any DC already.
if (!ebo.bValid() || ebo.bIsGlobal() || ebo.pbrush()->cShareLockGet() > 0)
{
STOCKWARNING("GreMakeBrushStock (%p) invalid/global/selected\n",hbr);
return (HBRUSH)0;
}
bRet = (HANDLE)((ULONG_PTR)hbr | GDISTOCKOBJ);
if (InterlockedDecrement(&gStockBrushFree) >= 0 &&
GreSetBrushOwner((HBRUSH)hbr,OBJECT_OWNER_PUBLIC) &&
(bHandleModified = HmgLockAndModifyHandleType((HOBJ)bRet)))
{
ebo.pbrush()->flAttrs(ebo.pbrush()->flAttrs() | BR_IS_GLOBAL);
return (HBRUSH)bRet;
}
else
{
if (!bHandleModified)
GreSetBrushOwner((HBRUSH)hbr,OBJECT_OWNER_CURRENT);
STOCKWARNING("GreMakeBrushStock (%p) Count/GreSetBrushOwner/ModifyH failed\n",bRet);
InterlockedIncrement(&gStockBrushFree);
bRet = 0;
}
return (HBRUSH)bRet;
}
/******************************Public*Routine******************************\
* GreMakeBrushNonStock
*
* Makes the brush a non stock brush
*
\**************************************************************************/
HBRUSH
GreMakeBrushNonStock(HBRUSH hbr)
{
HANDLE bRet = 0;
BRUSHSELOBJAPI ebo(hbr);
// Can make a stock brush non stock only when
// (1) It is valid
// (2) It is a global brush
// (3) It is not a Fixed stock brush
if (ebo.bValid() && ebo.bIsGlobal() && !ebo.pbrush()->bIsFixedStock())
{
bRet = (HANDLE)((ULONG_PTR)hbr & ~GDISTOCKOBJ);
if (ebo.pbrush()->cShareLockGet() > 0)
{
// The brush has more than one share lock. This means it will need
// to be lazy deleted.
ebo.pbrush()->vSetMakeNonStock();
STOCKINFO("GreMakeBrushNonStock (%p) is selected. Delay it\n", hbr);
}
else if(HmgLockAndModifyHandleType((HOBJ)bRet))
{
ebo.pbrush()->flAttrs(ebo.pbrush()->flAttrs() & ~BR_IS_GLOBAL);
if(!GreSetBrushOwner((HBRUSH)bRet,OBJECT_OWNER_CURRENT))
{
bRet = 0;
STOCKWARNING("GreMakeBrushNonStock (%p) GreSetBrushOwner failed\n", bRet);
}
else
{
InterlockedIncrement(&gStockBrushFree);
}
}
else
{
bRet = 0;
}
}
return (HBRUSH)bRet;
}
/******************************Public*Routine******************************\
* GreSetBrushOwner
*
* Sets the brush owner.
*
\**************************************************************************/
BOOL
GreSetBrushOwner(
HBRUSH hbr,
W32PID lPid
)
{
// If it is a global brush which by design are public we dont need to
// do anything.
{
BRUSHSELOBJ ebo(hbr);
if (ebo.bValid())
{
if (ebo.bIsGlobal())
return TRUE;
}
}
BOOL bStatus = FALSE;
PBRUSHATTR pBrushattr = NULL;
PENTRY pentry;
UINT uiIndex = (UINT) HmgIfromH(hbr);
if (uiIndex < gcMaxHmgr)
{
pentry = &gpentHmgr[uiIndex];
if (lPid == OBJECT_OWNER_CURRENT)
{
pBrushattr = (PBRUSHATTR)HmgAllocateObjectAttr();
}
//
// Accquire handle lock. Don't check PID here because owner could
// be NONE, not PUBLIC
//
HANDLELOCK HandleLock(pentry, FALSE);
if (HandleLock.bValid())
{
POBJ pobj = pentry->einfo.pobj;
if ((pentry->Objt == BRUSH_TYPE) && (pentry->FullUnique== HmgUfromH(hbr)))
{
PBRUSH pBrush = (PBRUSH)pobj;
if ((pobj->cExclusiveLock == 0) ||
(pobj->Tid == (PW32THREAD)PsGetCurrentThread()))
{
//
// Handle is locked. It is illegal to accquire the hmgr
// resource when a handle is locked.
//
if ((lPid == OBJECT_OWNER_NONE) ||
(lPid == OBJECT_OWNER_PUBLIC))
{
//
// free PBRUSHATTR if PID matches current process
// transfer brushattributes to kernel mode.
if (HandleLock.Pid() == W32GetCurrentPID())
{
//
// If user mode BRUSHATTR is allocated for this
// brush
//
if (pBrush->pBrushattr() != &pBrush->_Brushattr)
{
// Copy pBrushattr() to _BrushAttr
pBrush->_Brushattr = *(pBrush->pBrushattr());
// Free BRUSHATTR at bottom of function
pBrushattr = pBrush->pBrushattr();
// Set pBrushAttr to point to internal
pBrush->pBrushattr(&pBrush->_Brushattr);
// Clear entry
pentry->pUser = NULL;
}
// Set Brush owner to NONE or PUBLIC
HandleLock.Pid(lPid);
// dec process handle count
HmgDecProcessHandleCount(W32GetCurrentPID());
bStatus = TRUE;
}
else if (HandleLock.Pid() == OBJECT_OWNER_NONE)
{
// Allow to set from NONE to PUBLIC or NONE
HandleLock.Pid(lPid);
bStatus = TRUE;
}
//
// Move bitmap owner if needed. No need to do this if
// we are doing OBJECT_OWNER_NONE.
//
if (bStatus && lPid == OBJECT_OWNER_PUBLIC)
{
if (pBrush->hbmPattern() != (HBITMAP)NULL)
{
GreSetBitmapOwner(pBrush->hbmPattern(), OBJECT_OWNER_PUBLIC);
}
}
}
else if (lPid == OBJECT_OWNER_CURRENT)
{
//
// can only set to OBJECT_OWNER_CURRENT if Brush is
// not owned, or already owned by current pid.
//
lPid = W32GetCurrentPID();
if (HandleLock.Pid() == lPid ||
HandleLock.Pid() == OBJECT_OWNER_NONE ||
HandleLock.Pid() == OBJECT_OWNER_PUBLIC)
{
BOOL bIncHandleCount = FALSE;
bStatus = TRUE;
// only inc handle count if assigning new pid
if (HandleLock.Pid() != lPid)
{
// dont check quota for Brushes. ???
if (HmgIncProcessHandleCount(lPid,BRUSH_TYPE))
bIncHandleCount = TRUE;
}
//
// Check if user object already allocated for this
// handle
//
if (pentry->pUser == NULL)
{
if (pBrushattr != NULL)
{
// Set BrushAttr pointer
pBrush->pBrushattr(pBrushattr);
// Set pUser in ENTRY
pentry->pUser = pBrushattr;
// copy clean brush attrs
*pBrushattr = pBrush->_Brushattr;
// Set pBrushattr to NULL so it is not freed
pBrushattr = NULL;
}
else
{
WARNING("GreSetBrushOwner failed - No BRUSHATTR available");
bStatus = FALSE;
// reduce handle quota count
if (bIncHandleCount)
HmgDecProcessHandleCount(lPid);
}
}
if (bStatus)
{
// Set new owner
HandleLock.Pid(lPid);
//
// Move bitmap owner if needed.
//
if (pBrush->hbmPattern() != (HBITMAP)NULL)
{
GreSetBitmapOwner(pBrush->hbmPattern(), OBJECT_OWNER_CURRENT);
}
}
}
else
{
WARNING("GreSetBrushOwner failed, trying to set directly from one PID to another");
}
}
else
{
WARNING("GreSetBrushOwner failed, bad lPid");
}
}
else
{
WARNING("GreSetBrushOwner failed - Handle is exclusivly locked");
}
}
else
{
WARNING("GreSetBrushOwner failed - bad unique or object type");
}
HandleLock.vUnlock();
}
}
else
{
WARNING("GtreSetBrushOwner failed - invalid handle index\n");
}
// free pBrushattr if needed
if (pBrushattr)
{
HmgFreeObjectAttr((POBJECTATTR)pBrushattr);
}
return(bStatus);
}
/******************************Public*Routine******************************\
* vFreeOrCacheRbrush
*
* Either frees the current RBRUSH (the one pointed to by the this pointer) or
* puts it in the 1-deep RBRUSH cache, if the cache is empty.
*
* History:
*
* 30-Sep-1996 -by- Tom Zakrajsek [tomzak]
* Fixed it for multi brushes (DDML).
*
* 14-Dec-1993 -by- Michael Abrash [mikeab]
* Wrote it.
\**************************************************************************/
VOID MulDestroyBrushInternal(VOID*);
VOID RBRUSH::vFreeOrCacheRBrush(RBTYPE rbtype)
{
//
// If RBRUSH is for UMPD, just free it
//
if (!IS_SYSTEM_ADDRESS(this))
{
ASSERTGDI(bUMPDRBrush(),"RBRUSH::vFreeOrCacheRBrush UserMode brush does not have bUMPDBrush() bit on\n");
EngFreeUserMem(this);
return;
}
PRBRUSH *pprbrush;
// The bMultiBrush check is only valid for DRIVER realizations.
// Otherwise, it is assumed false.
BOOL bMulti = FALSE;
if (rbtype == RB_DRIVER)
{
pprbrush = &gpCachedDbrush;
bMulti = bMultiBrush();
if (bMulti)
{
PVOID pvRbrush = (PVOID)(((PDBRUSH)this)->aj);
MulDestroyBrushInternal(pvRbrush);
}
}
else
{
pprbrush = &gpCachedEngbrush;
}
// If there's already a cached RBRUSH, or this is a DDML brush
// just free this.
if ((*pprbrush != NULL) || (bMulti == TRUE))
{
VFREEMEM(this);
}
else
{
PRBRUSH pOldRbrush;
// There's no cached RBRUSH, and it's not a DDML brush,
// so cache this one.
if ((pOldRbrush = (PRBRUSH)
InterlockedExchangePointer((PVOID *)pprbrush, this))
!= NULL)
{
// Before we could cache this one, someone else cached another one,
// which we just acquired responsibility for, so free it.
VFREEMEM(pOldRbrush);
}
}
}
/******************************Public*Routine******************************\
* BRUSH::hFindIcmDIB
*
* Search ICM DIBs associated with brush until a match is found
*
* Arguments:
*
* Return Value:
*
* History:
*
* 9/25/1996 Mark Enstrom [marke]
*
\**************************************************************************/
HBITMAP BRUSH::hFindIcmDIB(HANDLE hcmXform)
{
ICMMSG(("hFindIcmDIB: FIND ICM DIB \n"));
if (hcmXform == NULL)
{
return _hbmPattern;
}
else
{
GreAcquireFastMutex(ghfmMemory);
PICM_DIB_LIST pDIBList = pIcmDIBList();
while (pDIBList != NULL)
{
if (pDIBList->hcmXform == hcmXform)
{
GreReleaseFastMutex(ghfmMemory);
return(pDIBList->hDIB);
}
pDIBList = pDIBList->pNext;
}
GreReleaseFastMutex(ghfmMemory);
return(NULL);
}
}
BOOL BRUSH::bAddIcmDIB(HANDLE hcmXform,HBITMAP hDIB)
{
ICMMSG(("bAddIcmDIB: ADD ICM DIB \n"));
BOOL bRet = FALSE;
//
// Check current hcmform is not on the list.
//
if (hFindIcmDIB(hcmXform))
{
ICMMSG(("bAddIcmDIB(): The DIB for hcmXform is exist\n"));
//
// hcmXform is exist,
//
// Do we need to do delete existing one and insert new one ??
//
return (FALSE);
}
SURFREF SurfDIB((HSURF) hDIB);
if (SurfDIB.bValid())
{
PICM_DIB_LIST pDIBList = (PICM_DIB_LIST)PALLOCNOZ(sizeof(ICM_DIB_LIST),'ldbG');
if (pDIBList)
{
//
// Inc. ref. count
//
{
SURFACE *ps = SurfDIB.ps;
ps->vInc_cRef();
}
//
// Fill DIBList cell.
//
pDIBList->hcmXform = hcmXform;
pDIBList->hDIB = hDIB;
pDIBList->pNext = pIcmDIBList();
//
// Updates list.
//
GreAcquireFastMutex(ghfmMemory);
pIcmDIBList(pDIBList);
GreReleaseFastMutex(ghfmMemory);
bRet = TRUE;
}
else
{
bRet = FALSE;
}
}
return(bRet);
}
VOID BRUSH::vDeleteIcmDIBs(VOID)
{
ICMMSG(("vDeleteIcmDIBs: Free ICM DIB \n"));
PICM_DIB_LIST pDIBList = pIcmDIBList();
GreAcquireFastMutex(ghfmMemory);
while (pDIBList != NULL)
{
PICM_DIB_LIST pNext = pDIBList->pNext;
HSURF hSurf = (HSURF) pDIBList->hDIB;
BOOL bValidSurface = FALSE;
//
// Dec. ref count, before deleting
//
{
SURFREF SurfDIB(hSurf);
if (SurfDIB.bValid())
{
SURFACE *ps = SurfDIB.ps;
ps->vDec_cRef();
bValidSurface = TRUE;
}
}
if (bValidSurface)
{
//
// Delete ICM-ed DIB surface.
//
if (!bDeleteSurface((HSURF)pDIBList->hDIB))
{
ICMMSG(("vDeleteICMDIBs(): bDeleteSurface is failed\n"));
}
}
else
{
ICMMSG(("vDeleteICMDIBs(): Invalid surface\n"));
}
//
// free the cell.
//
VFREEMEM(pDIBList);
pDIBList = pNext;
}
GreReleaseFastMutex(ghfmMemory);
}
| 96,209 | 29,723 |
/*
* @doc INTERNAL
*
* @module OLSOLE.CPP -- OlsOle LineServices object class
*
* Author:
* Murray Sargent (with lots of help from RickSa's ols code)
*
* Copyright (c) 1997-1998 Microsoft Corporation. All rights reserved.
*/
#include "_common.h"
#include "_font.h"
#include "_edit.h"
#include "_disp.h"
#include "_ols.h"
#include "_render.h"
extern "C" {
#include "objdim.h"
#include "pobjdim.h"
#include "plsdnode.h"
#include "dispi.h"
#include "pdispi.h"
#include "fmti.h"
#include "lsdnset.h"
#include "lsdnfin.h"
#include "brko.h"
#include "pbrko.h"
#include "locchnk.h"
#include "lsqout.h"
#include "lsqin.h"
#include "lsimeth.h"
}
#ifdef LINESERVICES
/*
* OlsOleCreateILSObj(pols, plsc, pclscbk, dword, ppilsobj)
*
* @func
* Create LS Ole object handler. We don't have any need for
* this, so just set it to 0.
*
* @rdesc
* LSERR
*/
LSERR WINAPI OlsOleCreateILSObj(
POLS pols, //[IN]: COls *
PLSC plsc, //[IN]: LineServices context
PCLSCBK,
DWORD,
PILSOBJ *ppilsobj) //[OUT]: ptr to ilsobj
{
*ppilsobj = 0;
return lserrNone;
}
/*
* OlsOleDestroyILSObj(pilsobj)
*
* @func
* Destroy LS Ole handler object. Nothing to do, since we don't
* use the ILSObj.
*
* @rdesc
* LSERR
*/
LSERR WINAPI OlsOleDestroyILSObj(
PILSOBJ pilsobj)
{
return lserrNone;
}
/*
* OlsOleSetDoc(pilsobj, pclsdocinf)
*
* @func
* Set doc info. Nothing to do for Ole objects
*
* @rdesc
* LSERR
*/
LSERR WINAPI OlsOleSetDoc(
PILSOBJ,
PCLSDOCINF)
{
// Ole objects don't care about this
return lserrNone;
}
/*
* OlsOleCreateLNObj(pilsobj, pplnobj)
*
* @func
* Create the line object. Nothing needed in addition to the ped,
* so just return the ped as the LN object.
*
* @rdesc
* LSERR
*/
LSERR WINAPI OlsOleCreateLNObj(
PCILSOBJ pilsobj,
PLNOBJ * pplnobj)
{
*pplnobj = (PLNOBJ)g_pols->_pme->GetPed(); // Just the ped
return lserrNone;
}
/*
* OlsOleDestroyLNObj(plnobj)
*
* @func
* Destroy LN object. Nothing to do, since ped is destroyed
* elsewhere
*
* @rdesc
* LSERR
*/
LSERR WINAPI OlsOleDestroyLNObj(
PLNOBJ plnobj)
{
return lserrNone;
}
/*
* OlsOleFmt(plnobj, pcfmtin, pfmres)
*
* @func
* Compute dimensions of a particular Ole object
*
* @rdesc
* LSERR
*/
LSERR WINAPI OlsOleFmt(
PLNOBJ plnobj,
PCFMTIN pcfmtin,
FMTRES *pfmres)
{
const LONG cp = pcfmtin->lsfrun.plsrun->_cp; //Cannot trust LS cps
LONG dup = 0;
LSERR lserr;
OBJDIM objdim;
CTxtEdit * ped = (CTxtEdit *)plnobj;
COleObject * pobj = ped->GetObjectMgr()->GetObjectFromCp(cp);
Assert(pobj);
ZeroMemory(&objdim, sizeof(objdim));
pobj->MeasureObj(g_pols->_pme->GetDyrInch(), g_pols->_pme->GetDxrInch(),
objdim.dur, objdim.heightsRef.dvAscent,
objdim.heightsRef.dvDescent, pcfmtin->lstxmRef.dvDescent);
pobj->MeasureObj(g_pols->_pme->GetDypInch(), g_pols->_pme->GetDxpInch(),
dup, objdim.heightsPres.dvAscent,
objdim.heightsPres.dvDescent, pcfmtin->lstxmPres.dvDescent);
pobj->_plsdnTop = pcfmtin->plsdnTop;
lserr = g_plsc->dnFinishRegular(1, pcfmtin->lsfrun.plsrun, pcfmtin->lsfrun.plschp, (PDOBJ)pobj, &objdim);
if(lserrNone == lserr)
{
lserr = g_plsc->dnSetRigidDup(pcfmtin->plsdnTop, dup);
if(lserrNone == lserr)
{
*pfmres = fmtrCompletedRun;
if (pcfmtin->lsfgi.urPen + objdim.dur > pcfmtin->lsfgi.urColumnMax
&& !pcfmtin->lsfgi.fFirstOnLine)
{
*pfmres = fmtrExceededMargin;
}
}
}
return lserr;
}
/*
* OlsOleTruncateChunk(plocchnk, posichnk)
*
* @func
* Truncate chunk plocchnk at the point posichnk
*
* @rdesc
* LSERR
*/
LSERR WINAPI OlsOleTruncateChunk(
PCLOCCHNK plocchnk, // (IN): locchnk to truncate
PPOSICHNK posichnk) // (OUT): truncation point
{
LSERR lserr;
OBJDIM objdim;
PLSCHNK plschnk = plocchnk->plschnk;
COleObject * pobj;
long ur = plocchnk->lsfgi.urPen;
long urColumnMax = plocchnk->lsfgi.urColumnMax;
for(DWORD i = 0; ur <= urColumnMax; i++)
{
AssertSz(i < plocchnk->clschnk, "OlsOleTruncateChunk: exceeded group of chunks");
pobj = (COleObject *)plschnk[i].pdobj;
Assert(pobj);
lserr = g_plsc->dnQueryObjDimRange(pobj->_plsdnTop, pobj->_plsdnTop, &objdim);
if(lserr != lserrNone)
return lserr;
ur += objdim.dur;
}
posichnk->ichnk = i - 1;
posichnk->dcp = 1;
return lserrNone;
}
/*
* OlsOleFindPrevBreakChunk(plocchnk, pposichnk, brkcond, pbrkout)
*
* @func
* Find previous break in chunk
*
* @rdesc
* LSERR
*/
LSERR WINAPI OlsOleFindPrevBreakChunk(
PCLOCCHNK plocchnk,
PCPOSICHNK pposichnk,
BRKCOND brkcond, //(IN): recommendation about break after chunk
PBRKOUT pbrkout)
{
ZeroMemory(pbrkout, sizeof(*pbrkout));
if (pposichnk->ichnk == ichnkOutside && (brkcond == brkcondPlease || brkcond == brkcondCan))
{
pbrkout->fSuccessful = fTrue;
pbrkout->posichnk.ichnk = plocchnk->clschnk - 1;
pbrkout->posichnk.dcp = plocchnk->plschnk[plocchnk->clschnk - 1].dcp;
COleObject *pobj = (COleObject *)plocchnk->plschnk[plocchnk->clschnk - 1].pdobj;
Assert(pobj);
g_plsc->dnQueryObjDimRange(pobj->_plsdnTop, pobj->_plsdnTop, &pbrkout->objdim);
}
else
pbrkout->brkcond = brkcondPlease;
return lserrNone;
}
/*
* OlsOleForceBreakChunk(plocchnk, pposichnk, pbrkout)
*
* @func
* Called when forced to break a line.
*
* @rdesc
* LSERR
*/
LSERR WINAPI OlsOleForceBreakChunk(
PCLOCCHNK plocchnk,
PCPOSICHNK pposichnk,
PBRKOUT pbrkout)
{
ZeroMemory(pbrkout, sizeof(*pbrkout));
pbrkout->fSuccessful = fTrue;
if (plocchnk->lsfgi.fFirstOnLine && pposichnk->ichnk == 0 || pposichnk->ichnk == ichnkOutside)
{
pbrkout->posichnk.dcp = 1;
COleObject *pobj = (COleObject *)plocchnk->plschnk[0].pdobj;
Assert(pobj);
g_plsc->dnQueryObjDimRange(pobj->_plsdnTop, pobj->_plsdnTop, &pbrkout->objdim);
}
else
{
pbrkout->posichnk.ichnk = pposichnk->ichnk;
pbrkout->posichnk.dcp = 0;
}
return lserrNone;
}
/*
* OlsOleSetBreak(pdobj, brkkind, nBreakRecord, rgBreakRecord, nActualBreakRecord)
*
* @func
* Set break
*
* @rdesc
* LSERR
*/
LSERR WINAPI OlsOleSetBreak(
PDOBJ pdobj, // (IN): dobj which is broken
BRKKIND brkkind, // (IN): Previous/Next/Force/Imposed was chosen
DWORD nBreakRecord, // (IN): size of array
BREAKREC* rgBreakRecord, // (OUT): array of break records
DWORD* nActualBreakRecord) // (OUT): actual number of used elements in array
{
return lserrNone;
}
LSERR WINAPI OlsOleGetSpecialEffectsInside(
PDOBJ pdobj, // (IN): dobj
UINT *pEffectsFlags) // (OUT): Special effects for this object
{
*pEffectsFlags = 0;
return lserrNone;
}
LSERR WINAPI OlsOleCalcPresentation(
PDOBJ, // (IN): dobj
long, // (IN): dup of dobj
LSKJUST, // (IN): LSKJUST
BOOL fLastVisibleOnLine)// (IN): this object is last visible object on line
{
return lserrNone;
}
/*
* OlsOleQueryPointPcp(pdobj, ppointuvQuery, plsqin, plsqout)
*
* @func
* Query Ole object PointFromCp.
*
* @rdesc
* LSERR
*/
LSERR WINAPI OlsOleQueryPointPcp(
PDOBJ pdobj, //(IN): dobj to query
PCPOINTUV ppointuvQuery, //(IN): query point (uQuery,vQuery)
PCLSQIN plsqin, //(IN): query input
PLSQOUT plsqout) //(OUT): query output
{
ZeroMemory(plsqout, sizeof(LSQOUT));
plsqout->heightsPresObj = plsqin->heightsPresRun;
plsqout->dupObj = plsqin->dupRun;
return lserrNone;
}
/*
* OlsOleQueryCpPpoint(pdobj, dcp, plsqin, plsqout)
*
* @func
* Query Ole object CpFromPoint.
*
* @rdesc
* LSERR
*/
LSERR WINAPI OlsOleQueryCpPpoint(
PDOBJ pdobj, //(IN): dobj to query
LSDCP dcp, //(IN): dcp for query
PCLSQIN plsqin, //(IN): query input
PLSQOUT plsqout) //(OUT): query output
{
ZeroMemory(plsqout, sizeof(LSQOUT));
plsqout->heightsPresObj = plsqin->heightsPresRun;
plsqout->dupObj = plsqin->dupRun;
return lserrNone;
}
/*
* OlsOleDisplay(pdobj, pcdispin)
*
* @func
* Display object
*
* @rdesc
* LSERR
*/
LSERR WINAPI OlsOleDisplay(
PDOBJ pdobj, //(IN): dobj to query
PCDISPIN pcdispin) //(IN): display info
{
POINT pt, ptCur;
COleObject *pobj = (COleObject *)pdobj;
Assert(pobj);
CRenderer *pre = g_pols->GetRenderer();
const CDisplay *pdp = pre->GetPdp();
ptCur = pre->GetCurPoint();
pt.x = pcdispin->ptPen.x;
pt.y = ptCur.y;
if (pcdispin->lstflow == lstflowWS)
pt.x -= pcdispin->dup - 1;
pre->SetCurPoint(pt);
pre->SetClipLeftRight(pcdispin->dup);
RECT rc = pre->GetClipRect();
pre->SetSelected(pcdispin->plsrun->IsSelected());
pre->Check_pccs();
pre->SetFontAndColor(pcdispin->plsrun->_pCF);
// Draw it!
HDC hdc = pre->GetDC();
pobj->DrawObj(pdp, pre->GetDypInch(), pre->GetDxpInch(), hdc, pdp->IsMetafile(), &pt, &rc, pcdispin->ptPen.y - pt.y, pre->GetLine()._yDescent);
return lserrNone;
}
/*
* OlsOleDistroyDObj(pdobj)
*
* @func
* Destroy object: nothing to do since object is destroyed elsewhere
*
* @rdesc
* LSERR
*/
LSERR WINAPI OlsOleDestroyDObj(
PDOBJ pdobj)
{
return lserrNone;
}
extern const LSIMETHODS vlsimethodsOle =
{
OlsOleCreateILSObj,
OlsOleDestroyILSObj,
OlsOleSetDoc,
OlsOleCreateLNObj,
OlsOleDestroyLNObj,
OlsOleFmt,
0,//OlsOleFmtResume
0,//OlsOleGetModWidthPrecedingChar
0,//OlsOleGetModWidthFollowingChar
OlsOleTruncateChunk,
OlsOleFindPrevBreakChunk,
0,//OlsOleFindNextBreakChunk
OlsOleForceBreakChunk,
OlsOleSetBreak,
OlsOleGetSpecialEffectsInside,
0,//OlsOleFExpandWithPrecedingChar
0,//OlsOleFExpandWithFollowingChar
OlsOleCalcPresentation,
OlsOleQueryPointPcp,
OlsOleQueryCpPpoint,
0,//pfnEnum
OlsOleDisplay,
OlsOleDestroyDObj
};
#endif // LINESERVICES
| 9,994 | 4,888 |
#include "CtrlCore.h"
NAMESPACE_UPP
#ifdef flagSO
CtrlFrame::CtrlFrame() {}
CtrlFrame::~CtrlFrame() {}
#endif
void CtrlFrame::FramePaint(Draw& draw, const Rect& r) {}
void CtrlFrame::FrameAdd(Ctrl& ctrl) {}
void CtrlFrame::FrameRemove() {}
int CtrlFrame::OverPaint() const { return 0; }
void NullFrameClass::FrameLayout(Rect& r) {}
void NullFrameClass::FramePaint(Draw& draw, const Rect& r) {}
void NullFrameClass::FrameAddSize(Size& sz) {}
CtrlFrame& GLOBAL_V(NullFrameClass, NullFrame);
#ifdef flagSO
BorderFrame::BorderFrame(const ColorF *border) : border(border) {}
BorderFrame::~BorderFrame() {}
#endif
void BorderFrame::FrameLayout(Rect& r)
{
Size sz = r.GetSize();
int n = (int)(intptr_t)*border;
if(sz.cx >= 2 * n && sz.cy >= 2 * n)
r.Deflate(n);
}
void BorderFrame::FrameAddSize(Size& sz)
{
sz += 2 * (int)(intptr_t)*border;
}
void BorderFrame::FramePaint(Draw& draw, const Rect& r)
{
Size sz = r.GetSize();
int n = (int)(intptr_t)*border;
if(sz.cx >= 2 * n && sz.cy >= 2 * n)
DrawBorder(draw, r.left, r.top, r.Width(), r.Height(), border);
}
CtrlFrame& GLOBAL_VP(BorderFrame, InsetFrame, (InsetBorder()));
CtrlFrame& GLOBAL_VP(BorderFrame, ThinInsetFrame, (ThinInsetBorder()));
CtrlFrame& GLOBAL_VP(BorderFrame, ButtonFrame, (ButtonBorder()));
CtrlFrame& GLOBAL_VP(BorderFrame, BlackFrame, (BlackBorder()));
CtrlFrame& GLOBAL_VP(BorderFrame, WhiteFrame, (WhiteBorder()));
CtrlFrame& GLOBAL_VP(BorderFrame, OutsetFrame, (OutsetBorder()));
CtrlFrame& GLOBAL_VP(BorderFrame, ThinOutsetFrame, (ThinOutsetBorder()));
CH_COLOR(FieldFrameColor, Blend(SColorHighlight, SColorShadow));
class XPFieldFrameCls : public CtrlFrame {
virtual void FrameLayout(Rect& r) { r.Deflate(2); }
virtual void FramePaint(Draw& w, const Rect& r) {
DrawFrame(w, r, FieldFrameColor());
DrawFrame(w, r.Deflated(1), SColorPaper);
}
virtual void FrameAddSize(Size& sz) { sz += 4; }
};
class XPEditFieldFrameCls : public CtrlFrame {
virtual void FrameLayout(Rect& r) { r.Deflate(1); }
virtual void FramePaint(Draw& w, const Rect& r) {
DrawFrame(w, r, FieldFrameColor());
}
virtual void FrameAddSize(Size& sz) { sz += 2; }
};
CtrlFrame& XPFieldFrame() { return Single<XPFieldFrameCls>(); }
CtrlFrame& XPEditFieldFrame() { return Single<XPEditFieldFrameCls>(); }
CH_INT(EditFieldIsThin, 0);
CtrlFrame& FieldFrame() { return GUI_GlobalStyle() >= GUISTYLE_XP ? XPFieldFrame() : InsetFrame(); }
CH_VALUE(TopSeparator1, SColorShadow());
CH_VALUE(TopSeparator2, SColorLight());
class TopSeparatorFrameCls : public CtrlFrame {
virtual void FrameLayout(Rect& r) { r.top += 2; }
virtual void FramePaint(Draw& w, const Rect& r) {
ChPaint(w, r.left, r.top, r.Width(), 1, TopSeparator1());
ChPaint(w, r.left, r.top + 1, r.Width(), 1, TopSeparator2());
}
virtual void FrameAddSize(Size& sz) { sz.cy += 2; }
};
class BottomSeparatorFrameCls : public CtrlFrame {
virtual void FrameLayout(Rect& r) { r.bottom -= 2; }
virtual void FramePaint(Draw& w, const Rect& r) {
w.DrawRect(r.left, r.bottom - 2, r.Width(), 1, SColorShadow);
w.DrawRect(r.left, r.bottom - 1, r.Width(), 1, SColorLight);
}
virtual void FrameAddSize(Size& sz) { sz.cy += 2; }
};
class LeftSeparatorFrameCls : public CtrlFrame {
virtual void FrameLayout(Rect& r) { r.left += 2; }
virtual void FramePaint(Draw& w, const Rect& r) {
w.DrawRect(r.left, r.top, 1, r.Height(), SColorShadow);
w.DrawRect(r.left + 1, r.top, 1, r.Height(), SColorLight);
}
virtual void FrameAddSize(Size& sz) { sz.cx += 2; }
};
class RightSeparatorFrameCls : public CtrlFrame {
virtual void FrameLayout(Rect& r) { r.right -= 2; }
virtual void FramePaint(Draw& w, const Rect& r) {
w.DrawRect(r.right - 2, r.top, 1, r.Height(), SColorShadow);
w.DrawRect(r.right - 1, r.top, 1, r.Height(), SColorLight);
}
virtual void FrameAddSize(Size& sz) { sz.cx += 2; }
};
CtrlFrame& BottomSeparatorFrame() { return Single<BottomSeparatorFrameCls>(); }
CtrlFrame& TopSeparatorFrame() { return Single<TopSeparatorFrameCls>(); }
CtrlFrame& RightSeparatorFrame() { return Single<RightSeparatorFrameCls>(); }
CtrlFrame& LeftSeparatorFrame() { return Single<LeftSeparatorFrameCls>(); }
CH_INT(FrameButtonWidth, 17);
CH_INT(ScrollBarArrowSize, FrameButtonWidth());
void LayoutFrameLeft(Rect& r, Ctrl *ctrl, int cx)
{
if(ctrl) {
cx *= ctrl->IsShown();
ctrl->SetFrameRect(r.left, r.top, cx, r.Height());
r.left += cx;
}
}
void LayoutFrameRight(Rect& r, Ctrl *ctrl, int cx)
{
if(ctrl) {
cx *= ctrl->IsShown();
ctrl->SetFrameRect(r.right - cx, r.top, cx, r.Height());
r.right -= cx;
}
}
void LayoutFrameTop(Rect& r, Ctrl *ctrl, int cy)
{
if(ctrl) {
cy *= ctrl->IsShown();
ctrl->SetFrameRect(r.left, r.top, r.Width(), cy);
r.top += cy;
}
}
void LayoutFrameBottom(Rect& r, Ctrl *ctrl, int cy)
{
if(ctrl) {
cy *= ctrl->IsShown();
ctrl->SetFrameRect(r.left, r.bottom - cy, r.Width(), cy);
r.bottom -= cy;
}
}
END_UPP_NAMESPACE
| 5,031 | 1,926 |
/******************************************************************************
*
* Copyright 2018 Xaptum, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*
*****************************************************************************/
#ifndef XTT_CPP_GROUPPUBLICKEYCONTEXT_HPP
#define XTT_CPP_GROUPPUBLICKEYCONTEXT_HPP
#pragma once
#include <xtt/context.h>
#include <xtt/group_identity.hpp>
#include <xtt/config.hpp>
#include <vector>
#include <memory>
namespace xtt { class group_public_key_context; }
namespace xtt {
class group_public_key_context {
public:
virtual ~group_public_key_context() = default;
virtual std::unique_ptr<group_public_key_context> clone() const = 0;
/*
* Serialize to byte stream,
* as (GPK | basename_length(1 byte) | basename).
*/
virtual std::vector<unsigned char> serialize() const = 0;
/*
* Get GPK as byte string.
*/
virtual std::vector<unsigned char> get_gpk() const = 0;
/*
* Get basename as byte string.
*/
virtual std::vector<unsigned char> get_basename() const = 0;
/*
* Get GPK as ASCII-encoded hexadecimal string
*/
virtual std::string get_gpk_as_text() const = 0;
/*
* Get basename as ASCII-encoded hexadecimal string
*/
virtual std::string get_basename_as_text() const = 0;
virtual struct xtt_group_public_key_context* get() = 0;
virtual const struct xtt_group_public_key_context* get() const = 0;
};
class group_public_key_context_lrsw : public group_public_key_context {
public:
/*
* Build a group_public_key_context_lrsw from
* a single byte string,
* in the form (GPK | basename_length (1 byte) | basename).
*/
static
std::unique_ptr<group_public_key_context>
deserialize(const unsigned char* serialized, std::size_t serialized_length);
static
std::unique_ptr<group_public_key_context>
deserialize(const std::vector<unsigned char>& serialized);
/*
* Build a group_public_key_context_lrsw from
* two separate byte strings,
* one for the basename and the other for the GPK.
*/
static
std::unique_ptr<group_public_key_context>
from_gpk_and_basename(const unsigned char* gpk,
std::size_t gpk_length,
const unsigned char* basename,
std::size_t basename_length);
static
std::unique_ptr<group_public_key_context>
from_gpk_and_basename(const std::vector<unsigned char>& gpk,
const std::vector<unsigned char>& basename);
/*
* Build a group_public_key_context_lrsw from
* two separate ASCII-encoded hexadecimal strings,
* one for the basename and the other for the GPK.
*/
static
std::unique_ptr<group_public_key_context>
from_gpk_and_basename(const std::string& gpk,
const std::string& basename);
public:
group_public_key_context_lrsw();
std::vector<unsigned char> serialize() const final;
std::vector<unsigned char> get_gpk() const final;
std::vector<unsigned char> get_basename() const final;
std::string get_gpk_as_text() const final;
std::string get_basename_as_text() const final;
std::unique_ptr<group_public_key_context> clone() const final;
struct xtt_group_public_key_context* get() final;
const struct xtt_group_public_key_context* get() const final;
private:
xtt_group_public_key_context gpk_ctx_;
};
std::ostream& operator<<(std::ostream& stream, const xtt::group_public_key_context& gpk_ctx);
} // namespace xtt
#endif
| 4,483 | 1,326 |
#include "asd.KeyframeAnimation_Imp.h"
#include <cmath>
namespace asd
{
KeyframeAnimation_Imp::KeyframeAnimation_Imp()
: m_targetType(AnimationCurveTargetType::NoneTarget)
, m_targetAxis(AnimationCurveTargetAxis::NoneTarget)
{
}
KeyframeAnimation_Imp::~KeyframeAnimation_Imp()
{
}
const achar* KeyframeAnimation_Imp::GetName()
{
return m_name.c_str();
}
void KeyframeAnimation_Imp::SetName(const achar* name)
{
m_name = name;
ModelUtils::GetAnimationTarget(m_targetName, m_targetType, m_targetAxis, name);
}
astring& KeyframeAnimation_Imp::GetTargetName()
{
return m_targetName;
}
AnimationCurveTargetType KeyframeAnimation_Imp::GetTargetType()
{
return m_targetType;
}
AnimationCurveTargetAxis KeyframeAnimation_Imp::GetTargetAxis()
{
return m_targetAxis;
}
void KeyframeAnimation_Imp::AddKeyframe(const FCurveKeyframe& kf)
{
m_keyframes.push_back(kf);
}
float KeyframeAnimation_Imp::GetValue(float time)
{
return ModelUtils::GetKeyframeValue(time, m_keyframes);
}
}
| 1,032 | 397 |
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2022 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
////////////////////////////////////////////////////////////////////////////////
#include <errno.h>
#include <string.h>
#include <string>
#include "Basics/Common.h"
#include "Basics/operating-system.h"
#ifdef TRI_HAVE_WINSOCK2_H
#include <WS2tcpip.h>
#include <WinSock2.h>
#endif
#include <openssl/opensslv.h>
#include <openssl/ssl.h>
#ifndef OPENSSL_VERSION_NUMBER
#error expecting OPENSSL_VERSION_NUMBER to be defined
#endif
#include <openssl/err.h>
#include <openssl/opensslconf.h>
#include <openssl/ssl3.h>
#include <openssl/x509.h>
#include "SslClientConnection.h"
#include "Basics/Exceptions.h"
#include "Basics/StringBuffer.h"
#include "Basics/debugging.h"
#include "Basics/error.h"
#include "Basics/socket-utils.h"
#include "Basics/voc-errors.h"
#include "Logger/LogMacros.h"
#include "Logger/Logger.h"
#include "Logger/LoggerStream.h"
#include "Ssl/ssl-helper.h"
#undef TRACE_SSL_CONNECTIONS
#ifdef _WIN32
#define STR_ERROR() \
windowsErrorBuf; \
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), 0, \
windowsErrorBuf, sizeof(windowsErrorBuf), NULL); \
errno = GetLastError();
#else
#define STR_ERROR() strerror(errno)
#endif
using namespace arangodb;
using namespace arangodb::basics;
using namespace arangodb::httpclient;
namespace {
#ifdef TRACE_SSL_CONNECTIONS
static char const* tlsTypeName(int type) {
switch (type) {
#ifdef SSL3_RT_HEADER
case SSL3_RT_HEADER:
return "TLS header";
#endif
case SSL3_RT_CHANGE_CIPHER_SPEC:
return "TLS change cipher";
case SSL3_RT_ALERT:
return "TLS alert";
case SSL3_RT_HANDSHAKE:
return "TLS handshake";
case SSL3_RT_APPLICATION_DATA:
return "TLS app data";
default:
return "TLS Unknown";
}
}
static char const* sslMessageType(int sslVersion, int msg) {
#ifdef SSL2_VERSION_MAJOR
if (sslVersion == SSL2_VERSION_MAJOR) {
switch (msg) {
case SSL2_MT_ERROR:
return "Error";
case SSL2_MT_CLIENT_HELLO:
return "Client hello";
case SSL2_MT_CLIENT_MASTER_KEY:
return "Client key";
case SSL2_MT_CLIENT_FINISHED:
return "Client finished";
case SSL2_MT_SERVER_HELLO:
return "Server hello";
case SSL2_MT_SERVER_VERIFY:
return "Server verify";
case SSL2_MT_SERVER_FINISHED:
return "Server finished";
case SSL2_MT_REQUEST_CERTIFICATE:
return "Request CERT";
case SSL2_MT_CLIENT_CERTIFICATE:
return "Client CERT";
}
} else
#endif
if (sslVersion == SSL3_VERSION_MAJOR) {
switch (msg) {
case SSL3_MT_HELLO_REQUEST:
return "Hello request";
case SSL3_MT_CLIENT_HELLO:
return "Client hello";
case SSL3_MT_SERVER_HELLO:
return "Server hello";
#ifdef SSL3_MT_NEWSESSION_TICKET
case SSL3_MT_NEWSESSION_TICKET:
return "Newsession Ticket";
#endif
case SSL3_MT_CERTIFICATE:
return "Certificate";
case SSL3_MT_SERVER_KEY_EXCHANGE:
return "Server key exchange";
case SSL3_MT_CLIENT_KEY_EXCHANGE:
return "Client key exchange";
case SSL3_MT_CERTIFICATE_REQUEST:
return "Request CERT";
case SSL3_MT_SERVER_DONE:
return "Server finished";
case SSL3_MT_CERTIFICATE_VERIFY:
return "CERT verify";
case SSL3_MT_FINISHED:
return "Finished";
#ifdef SSL3_MT_CERTIFICATE_STATUS
case SSL3_MT_CERTIFICATE_STATUS:
return "Certificate Status";
#endif
}
}
return "Unknown";
}
static void sslTlsTrace(int direction, int sslVersion, int contentType,
void const* buf, size_t, SSL*, void*) {
// enable this for tracing SSL connections
if (sslVersion) {
sslVersion >>= 8; /* check the upper 8 bits only below */
char const* tlsRtName;
if (sslVersion == SSL3_VERSION_MAJOR && contentType)
tlsRtName = tlsTypeName(contentType);
else
tlsRtName = "";
LOG_TOPIC("5e087", TRACE, arangodb::Logger::FIXME)
<< "SSL connection trace: " << (direction ? "out" : "in") << ", "
<< tlsRtName << ", "
<< sslMessageType(sslVersion, *static_cast<char const*>(buf));
}
}
#endif
} // namespace
////////////////////////////////////////////////////////////////////////////////
/// @brief creates a new client connection
////////////////////////////////////////////////////////////////////////////////
SslClientConnection::SslClientConnection(
application_features::CommunicationFeaturePhase& comm, Endpoint* endpoint,
double requestTimeout, double connectTimeout, size_t connectRetries,
uint64_t sslProtocol)
: GeneralClientConnection(comm, endpoint, requestTimeout, connectTimeout,
connectRetries),
_ssl(nullptr),
_ctx(nullptr),
_sslProtocol(sslProtocol) {
init(sslProtocol);
}
SslClientConnection::SslClientConnection(
application_features::CommunicationFeaturePhase& comm,
std::unique_ptr<Endpoint>& endpoint, double requestTimeout,
double connectTimeout, size_t connectRetries, uint64_t sslProtocol)
: GeneralClientConnection(comm, endpoint, requestTimeout, connectTimeout,
connectRetries),
_ssl(nullptr),
_ctx(nullptr),
_sslProtocol(sslProtocol) {
init(sslProtocol);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief destroys a client connection
////////////////////////////////////////////////////////////////////////////////
SslClientConnection::~SslClientConnection() {
disconnect();
if (_ssl != nullptr) {
SSL_free(_ssl);
}
if (_ctx != nullptr) {
SSL_CTX_free(_ctx);
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief internal initialization method, called from ctor
////////////////////////////////////////////////////////////////////////////////
void SslClientConnection::init(uint64_t sslProtocol) {
TRI_invalidatesocket(&_socket);
SSL_METHOD SSL_CONST* meth = nullptr;
switch (SslProtocol(sslProtocol)) {
case SSL_V2:
THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_NOT_IMPLEMENTED,
"support for SSLv2 has been dropped");
#ifndef OPENSSL_NO_SSL3_METHOD
case SSL_V3:
meth = SSLv3_method();
break;
#endif
case SSL_V23:
meth = SSLv23_method();
break;
case TLS_V1:
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
meth = TLS_client_method();
#else
meth = TLSv1_method();
#endif
break;
case TLS_V12:
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
meth = TLS_client_method();
#else
meth = TLSv1_2_method();
#endif
break;
// TLS 1.3, only supported from OpenSSL 1.1.1 onwards
// openssl version number format is
// MNNFFPPS: major minor fix patch status
#if OPENSSL_VERSION_NUMBER >= 0x10101000L
case TLS_V13:
meth = TLS_client_method();
break;
#endif
case TLS_GENERIC:
meth = TLS_client_method();
break;
case SSL_UNKNOWN:
default:
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
// The actual protocol version used will be negotiated to the highest
// version mutually supported by the client and the server. The supported
// protocols are SSLv3, TLSv1, TLSv1.1 and TLSv1.2. Applications should
// use these methods, and avoid the version-specific methods described
// below.
meth = TLS_method();
#else
// default to TLS 1.2
meth = TLSv1_2_method();
#endif
break;
}
_ctx = SSL_CTX_new(meth);
if (_ctx != nullptr) {
#ifdef TRACE_SSL_CONNECTIONS
SSL_CTX_set_msg_callback(_ctx, sslTlsTrace);
#endif
SSL_CTX_set_cipher_list(_ctx, "ALL");
// TODO: better use the following ciphers...
// SSL_CTX_set_cipher_list(_ctx,
// "ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH");
bool sslCache = true;
SSL_CTX_set_session_cache_mode(
_ctx, sslCache ? SSL_SESS_CACHE_SERVER : SSL_SESS_CACHE_OFF);
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief connect
////////////////////////////////////////////////////////////////////////////////
bool SslClientConnection::connectSocket() {
TRI_ASSERT(_endpoint != nullptr);
if (_endpoint->isConnected()) {
disconnectSocket();
_isConnected = false;
}
_errorDetails.clear();
_socket = _endpoint->connect(_connectTimeout, _requestTimeout);
if (!TRI_isvalidsocket(_socket) || _ctx == nullptr) {
_errorDetails = _endpoint->_errorMessage;
_isConnected = false;
return false;
}
_isConnected = true;
_ssl = SSL_new(_ctx);
if (_ssl == nullptr) {
_errorDetails = std::string("failed to create ssl context");
disconnectSocket();
_isConnected = false;
return false;
}
switch (SslProtocol(_sslProtocol)) {
case TLS_V1:
case TLS_V12:
#if OPENSSL_VERSION_NUMBER >= 0x10101000L
case TLS_V13:
#endif
case TLS_GENERIC:
default:
SSL_set_tlsext_host_name(_ssl, _endpoint->host().c_str());
}
SSL_set_connect_state(_ssl);
if (SSL_set_fd(_ssl, (int)TRI_get_fd_or_handle_of_socket(_socket)) != 1) {
_errorDetails = std::string("SSL: failed to create context ") +
ERR_error_string(ERR_get_error(), nullptr);
disconnectSocket();
_isConnected = false;
return false;
}
SSL_set_verify(_ssl, SSL_VERIFY_NONE, nullptr);
ERR_clear_error();
int ret = SSL_connect(_ssl);
if (ret != 1) {
_errorDetails.append("SSL: during SSL_connect: ");
int errorDetail;
long certError;
errorDetail = SSL_get_error(_ssl, ret);
if ((errorDetail == SSL_ERROR_WANT_READ) ||
(errorDetail == SSL_ERROR_WANT_WRITE)) {
return true;
}
/* Gets the earliest error code from the
thread's error queue and removes the entry. */
unsigned long lastError = ERR_get_error();
if (errorDetail == SSL_ERROR_SYSCALL && lastError == 0) {
if (ret == 0) {
_errorDetails +=
"an EOF was observed that violates the protocol. this may happen "
"when the other side has closed the connection";
} else if (ret == -1) {
_errorDetails += "I/O reported by BIO";
}
}
switch (errorDetail) {
case 0x1407E086:
/* 1407E086:
SSL routines:
SSL2_SET_CERTIFICATE:
certificate verify failed */
/* fall-through */
case 0x14090086:
/* 14090086:
SSL routines:
SSL3_GET_SERVER_CERTIFICATE:
certificate verify failed */
certError = SSL_get_verify_result(_ssl);
if (certError != X509_V_OK) {
_errorDetails += std::string("certificate problem: ") +
X509_verify_cert_error_string(certError);
} else {
_errorDetails =
std::string("certificate problem, verify that the CA cert is OK");
}
break;
default:
char errorBuffer[256];
ERR_error_string_n(errorDetail, errorBuffer, sizeof(errorBuffer));
_errorDetails += std::string(" - details: ") + errorBuffer;
break;
}
disconnectSocket();
_isConnected = false;
return false;
}
LOG_TOPIC("b3d52", TRACE, arangodb::Logger::FIXME)
<< "SSL connection opened: " << SSL_get_cipher(_ssl) << ", "
<< SSL_get_cipher_version(_ssl) << " ("
<< SSL_get_cipher_bits(_ssl, nullptr) << " bits)";
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief disconnect
////////////////////////////////////////////////////////////////////////////////
void SslClientConnection::disconnectSocket() {
_endpoint->disconnect();
TRI_invalidatesocket(&_socket);
if (_ssl != nullptr) {
SSL_free(_ssl);
_ssl = nullptr;
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief write data to the connection
////////////////////////////////////////////////////////////////////////////////
bool SslClientConnection::writeClientConnection(void const* buffer,
size_t length,
size_t* bytesWritten) {
TRI_ASSERT(bytesWritten != nullptr);
#ifdef _WIN32
char windowsErrorBuf[256];
#endif
*bytesWritten = 0;
if (_ssl == nullptr) {
return false;
}
int written = SSL_write(_ssl, buffer, (int)length);
int err = SSL_get_error(_ssl, written);
switch (err) {
case SSL_ERROR_NONE:
*bytesWritten = written;
#ifdef ARANGODB_ENABLE_MAINTAINER_MODE
_written += written;
#endif
return true;
case SSL_ERROR_ZERO_RETURN:
SSL_shutdown(_ssl);
break;
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
case SSL_ERROR_WANT_CONNECT:
break;
case SSL_ERROR_SYSCALL: {
char const* pErr = STR_ERROR();
_errorDetails =
std::string("SSL: while writing: SYSCALL returned errno = ") +
std::to_string(errno) + std::string(" - ") + pErr;
break;
}
case SSL_ERROR_SSL: {
/* A failure in the SSL library occurred, usually a protocol error.
The OpenSSL error queue contains more information on the error. */
unsigned long errorDetail = ERR_get_error();
char errorBuffer[256];
ERR_error_string_n(errorDetail, errorBuffer, sizeof(errorBuffer));
_errorDetails = std::string("SSL: while writing: ") + errorBuffer;
break;
}
default:
/* a true error */
_errorDetails =
std::string("SSL: while writing: error ") + std::to_string(err);
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief read data from the connection
////////////////////////////////////////////////////////////////////////////////
bool SslClientConnection::readClientConnection(StringBuffer& stringBuffer,
bool& connectionClosed) {
#ifdef _WIN32
char windowsErrorBuf[256];
#endif
connectionClosed = true;
if (_ssl == nullptr) {
return false;
}
if (!_isConnected) {
return true;
}
connectionClosed = false;
do {
again:
// reserve some memory for reading
if (stringBuffer.reserve(READBUFFER_SIZE) == TRI_ERROR_OUT_OF_MEMORY) {
// out of memory
TRI_set_errno(TRI_ERROR_OUT_OF_MEMORY);
return false;
}
ERR_clear_error();
int lenRead = SSL_read(_ssl, stringBuffer.end(), READBUFFER_SIZE - 1);
switch (SSL_get_error(_ssl, lenRead)) {
case SSL_ERROR_NONE:
stringBuffer.increaseLength(lenRead);
#ifdef ARANGODB_ENABLE_MAINTAINER_MODE
_read += lenRead;
#endif
break;
case SSL_ERROR_ZERO_RETURN:
connectionClosed = true;
SSL_shutdown(_ssl);
_isConnected = false;
return true;
case SSL_ERROR_WANT_READ:
goto again;
case SSL_ERROR_WANT_WRITE:
case SSL_ERROR_WANT_CONNECT:
case SSL_ERROR_SYSCALL:
default: {
char const* pErr = STR_ERROR();
unsigned long errorDetail = ERR_get_error();
char errorBuffer[256];
ERR_error_string_n(errorDetail, errorBuffer, sizeof(errorBuffer));
_errorDetails = std::string("SSL: while reading: error '") +
std::to_string(errno) + std::string("' - ") +
errorBuffer + std::string("' - ") + pErr;
/* unexpected */
connectionClosed = true;
return false;
}
}
} while (readable());
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief return whether the connection is readable
////////////////////////////////////////////////////////////////////////////////
bool SslClientConnection::readable() {
// must use SSL_pending() and not select() as SSL_read() might read more
// bytes from the socket into the _ssl structure than we actually requested
// via SSL_read().
// if we used select() to check whether there is more data available, select()
// might return 0 already but we might not have consumed all bytes yet
// ...........................................................................
// SSL_pending(...) is an OpenSSL function which returns the number of bytes
// which are available inside ssl for reading.
// ...........................................................................
if (SSL_pending(_ssl) > 0) {
return true;
}
if (prepare(_socket, 0.0, false)) {
return checkSocket();
}
return false;
}
| 17,635 | 5,524 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/android/data_usage/data_use_ui_tab_model.h"
#include <stddef.h>
#include <stdint.h>
#include "base/macros.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "chrome/browser/android/data_usage/data_use_tab_model.h"
#include "chrome/browser/android/data_usage/data_use_ui_tab_model_factory.h"
#include "chrome/browser/android/data_usage/external_data_use_observer.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sessions/session_tab_helper.h"
#include "components/data_usage/core/data_use_aggregator.h"
#include "components/data_usage/core/data_use_amortizer.h"
#include "components/data_usage/core/data_use_annotator.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/page_transition_types.h"
#include "url/gurl.h"
namespace chrome {
namespace android {
namespace {
const char kFooLabel[] = "foo_label";
const char kFooPackage[] = "com.foo";
class TestDataUseTabModel : public DataUseTabModel {
public:
TestDataUseTabModel() {}
~TestDataUseTabModel() override {}
using DataUseTabModel::NotifyObserversOfTrackingStarting;
using DataUseTabModel::NotifyObserversOfTrackingEnding;
};
class DataUseUITabModelTest : public testing::Test {
public:
DataUseUITabModelTest()
: thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP) {}
DataUseUITabModel* data_use_ui_tab_model() { return &data_use_ui_tab_model_; }
ExternalDataUseObserver* external_data_use_observer() const {
return external_data_use_observer_.get();
}
TestDataUseTabModel* data_use_tab_model() const {
return data_use_tab_model_.get();
}
void RegisterURLRegexes(const std::vector<std::string>& app_package_name,
const std::vector<std::string>& domain_path_regex,
const std::vector<std::string>& label) {
data_use_tab_model_->RegisterURLRegexes(app_package_name, domain_path_regex,
label);
}
protected:
void SetUp() override {
io_task_runner_ = content::BrowserThread::GetMessageLoopProxyForThread(
content::BrowserThread::IO);
ui_task_runner_ = content::BrowserThread::GetMessageLoopProxyForThread(
content::BrowserThread::UI);
data_use_aggregator_.reset(
new data_usage::DataUseAggregator(nullptr, nullptr));
external_data_use_observer_.reset(new ExternalDataUseObserver(
data_use_aggregator_.get(), io_task_runner_, ui_task_runner_));
// Wait for |external_data_use_observer_| to create the Java object.
base::RunLoop().RunUntilIdle();
data_use_tab_model_.reset(new TestDataUseTabModel());
data_use_tab_model_->InitOnUIThread(
io_task_runner_, external_data_use_observer_->GetWeakPtr());
data_use_ui_tab_model_.SetDataUseTabModel(data_use_tab_model_.get());
data_use_tab_model_->OnControlAppInstallStateChange(true);
}
private:
content::TestBrowserThreadBundle thread_bundle_;
DataUseUITabModel data_use_ui_tab_model_;
scoped_refptr<base::SingleThreadTaskRunner> io_task_runner_;
scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner_;
scoped_ptr<data_usage::DataUseAggregator> data_use_aggregator_;
scoped_ptr<ExternalDataUseObserver> external_data_use_observer_;
scoped_ptr<TestDataUseTabModel> data_use_tab_model_;
};
} // namespace
// Tests that DataUseTabModel is notified of tab closure and navigation events,
// and DataUseTabModel notifies DataUseUITabModel.
TEST_F(DataUseUITabModelTest, ReportTabEventsTest) {
std::vector<std::string> url_regexes;
url_regexes.push_back(
"http://www[.]foo[.]com/#q=.*|https://www[.]foo[.]com/#q=.*");
RegisterURLRegexes(std::vector<std::string>(url_regexes.size(), kFooPackage),
url_regexes,
std::vector<std::string>(url_regexes.size(), kFooLabel));
const struct {
ui::PageTransition transition_type;
std::string expected_label;
} tests[] = {
{ui::PageTransitionFromInt(ui::PageTransition::PAGE_TRANSITION_LINK |
ui::PAGE_TRANSITION_FROM_API),
kFooLabel},
{ui::PageTransition::PAGE_TRANSITION_LINK, kFooLabel},
{ui::PageTransition::PAGE_TRANSITION_TYPED, kFooLabel},
{ui::PageTransition::PAGE_TRANSITION_AUTO_BOOKMARK, kFooLabel},
{ui::PageTransition::PAGE_TRANSITION_AUTO_TOPLEVEL, std::string()},
{ui::PageTransition::PAGE_TRANSITION_GENERATED, kFooLabel},
{ui::PageTransition::PAGE_TRANSITION_RELOAD, kFooLabel},
};
SessionID::id_type foo_tab_id = 100;
for (size_t i = 0; i < arraysize(tests); ++i) {
// Start a new tab.
++foo_tab_id;
data_use_ui_tab_model()->ReportBrowserNavigation(
GURL("https://www.foo.com/#q=abc"), tests[i].transition_type,
foo_tab_id);
// |data_use_ui_tab_model| should receive callback about starting of
// tracking of data usage for |foo_tab_id|.
EXPECT_EQ(!tests[i].expected_label.empty(),
data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(
foo_tab_id))
<< i;
EXPECT_FALSE(data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(
foo_tab_id))
<< i;
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingEnded(foo_tab_id))
<< i;
std::string got_label;
data_use_tab_model()->GetLabelForTabAtTime(
foo_tab_id, base::TimeTicks::Now(), &got_label);
EXPECT_EQ(tests[i].expected_label, got_label) << i;
// Report closure of tab.
data_use_ui_tab_model()->ReportTabClosure(foo_tab_id);
// DataUse object should not be labeled.
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingEnded(foo_tab_id));
data_use_tab_model()->GetLabelForTabAtTime(
foo_tab_id, base::TimeTicks::Now() + base::TimeDelta::FromMinutes(10),
&got_label);
EXPECT_EQ(std::string(), got_label) << i;
}
// Start a custom tab with matching package name and verify if tracking
// started is not being set.
const SessionID::id_type bar_tab_id = foo_tab_id + 1;
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(bar_tab_id));
data_use_ui_tab_model()->ReportCustomTabInitialNavigation(
bar_tab_id, kFooPackage, std::string());
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(bar_tab_id));
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingEnded(bar_tab_id));
data_use_ui_tab_model()->ReportTabClosure(bar_tab_id);
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingEnded(bar_tab_id));
}
// Tests if the Entrance/Exit UI state is tracked correctly.
TEST_F(DataUseUITabModelTest, EntranceExitState) {
const SessionID::id_type kFooTabId = 1;
const SessionID::id_type kBarTabId = 2;
const SessionID::id_type kBazTabId = 3;
// CheckAndResetDataUseTrackingStarted should return true only once.
data_use_tab_model()->NotifyObserversOfTrackingStarting(kFooTabId);
EXPECT_TRUE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(kFooTabId));
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(kFooTabId));
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingEnded(kFooTabId));
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(kBarTabId));
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingEnded(kBarTabId));
// CheckAndResetDataUseTrackingEnded should return true only once.
data_use_tab_model()->NotifyObserversOfTrackingEnding(kFooTabId);
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(kFooTabId));
EXPECT_TRUE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingEnded(kFooTabId));
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingEnded(kFooTabId));
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(kFooTabId));
// The tab enters the tracking state again.
data_use_tab_model()->NotifyObserversOfTrackingStarting(kFooTabId);
EXPECT_TRUE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(kFooTabId));
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(kFooTabId));
// The tab exits the tracking state.
data_use_tab_model()->NotifyObserversOfTrackingEnding(kFooTabId);
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(kFooTabId));
// The tab enters the tracking state again.
data_use_tab_model()->NotifyObserversOfTrackingStarting(kFooTabId);
data_use_tab_model()->NotifyObserversOfTrackingStarting(kFooTabId);
EXPECT_TRUE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(kFooTabId));
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(kFooTabId));
// ShowExit should return true only once.
data_use_tab_model()->NotifyObserversOfTrackingEnding(kBarTabId);
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(kBarTabId));
EXPECT_TRUE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingEnded(kBarTabId));
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingEnded(kBarTabId));
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(kBarTabId));
data_use_ui_tab_model()->ReportTabClosure(kFooTabId);
data_use_ui_tab_model()->ReportTabClosure(kBarTabId);
// CheckAndResetDataUseTrackingStarted/Ended should return false for closed
// tabs.
data_use_tab_model()->NotifyObserversOfTrackingStarting(kBazTabId);
data_use_ui_tab_model()->ReportTabClosure(kBazTabId);
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(kBazTabId));
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingEnded(kBazTabId));
}
// Tests if the Entrance/Exit UI state is tracked correctly.
TEST_F(DataUseUITabModelTest, EntranceExitStateForDialog) {
const SessionID::id_type kFooTabId = 1;
std::vector<std::string> url_regexes;
url_regexes.push_back(
"http://www[.]foo[.]com/#q=.*|https://www[.]foo[.]com/#q=.*");
RegisterURLRegexes(std::vector<std::string>(url_regexes.size(), kFooPackage),
url_regexes,
std::vector<std::string>(url_regexes.size(), kFooLabel));
SessionID::id_type foo_tab_id = kFooTabId;
const struct {
// True if a dialog box was shown to the user. It may not be shown if the
// user has previously selected the option to opt out.
bool continue_dialog_box_shown;
bool user_proceeded_with_navigation;
} tests[] = {
{false, false}, {true, true}, {true, false},
};
for (size_t i = 0; i < arraysize(tests); ++i) {
// Start a new tab.
++foo_tab_id;
data_use_ui_tab_model()->ReportBrowserNavigation(
GURL("https://www.foo.com/#q=abc"), ui::PAGE_TRANSITION_GENERATED,
foo_tab_id);
// |data_use_ui_tab_model| should receive callback about starting of
// tracking of data usage for |foo_tab_id|.
EXPECT_TRUE(data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(
foo_tab_id))
<< i;
EXPECT_FALSE(data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(
foo_tab_id))
<< i;
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingEnded(foo_tab_id))
<< i;
std::string got_label;
data_use_tab_model()->GetLabelForTabAtTime(
foo_tab_id, base::TimeTicks::Now(), &got_label);
EXPECT_EQ(kFooLabel, got_label) << i;
// Tab enters non-tracking state.
data_use_ui_tab_model()->ReportBrowserNavigation(
GURL("https://www.bar.com/#q=abc"),
ui::PageTransition::PAGE_TRANSITION_TYPED, foo_tab_id);
EXPECT_TRUE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingEnded(foo_tab_id))
<< i;
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingEnded(foo_tab_id))
<< i;
// Tab enters tracking state.
data_use_ui_tab_model()->ReportBrowserNavigation(
GURL("https://www.foo.com/#q=abc"), ui::PAGE_TRANSITION_GENERATED,
foo_tab_id);
EXPECT_TRUE(data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(
foo_tab_id))
<< i;
// Tab may enter non-tracking state.
EXPECT_TRUE(data_use_ui_tab_model()->WouldDataUseTrackingEnd(
"https://www.bar.com/#q=abc", ui::PageTransition::PAGE_TRANSITION_TYPED,
foo_tab_id));
if (tests[i].continue_dialog_box_shown &&
tests[i].user_proceeded_with_navigation) {
data_use_ui_tab_model()->UserClickedContinueOnDialogBox(foo_tab_id);
}
if (tests[i].user_proceeded_with_navigation) {
data_use_ui_tab_model()->ReportBrowserNavigation(
GURL("https://www.bar.com/#q=abc"),
ui::PageTransition::PAGE_TRANSITION_TYPED, foo_tab_id);
}
const std::string expected_label =
tests[i].user_proceeded_with_navigation ? "" : kFooLabel;
data_use_tab_model()->GetLabelForTabAtTime(
foo_tab_id, base::TimeTicks::Now(), &got_label);
EXPECT_EQ(expected_label, got_label) << i;
if (tests[i].user_proceeded_with_navigation) {
// No UI element should be shown afterwards if the dialog box was shown
// before.
EXPECT_NE(tests[i].continue_dialog_box_shown,
data_use_ui_tab_model()->CheckAndResetDataUseTrackingEnded(
foo_tab_id))
<< i;
} else {
EXPECT_FALSE(data_use_ui_tab_model()->CheckAndResetDataUseTrackingEnded(
foo_tab_id))
<< i;
}
}
}
// Checks if page transition type is converted correctly.
TEST_F(DataUseUITabModelTest, ConvertTransitionType) {
DataUseTabModel::TransitionType transition_type;
EXPECT_TRUE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_TYPED), &transition_type));
EXPECT_EQ(DataUseTabModel::TRANSITION_OMNIBOX_NAVIGATION, transition_type);
EXPECT_TRUE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_TYPED | 0xFF00),
&transition_type));
EXPECT_EQ(DataUseTabModel::TRANSITION_OMNIBOX_NAVIGATION, transition_type);
EXPECT_TRUE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_TYPED | 0xFFFF00),
&transition_type));
EXPECT_EQ(DataUseTabModel::TRANSITION_OMNIBOX_NAVIGATION, transition_type);
EXPECT_TRUE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_TYPED | 0x12FFFF00),
&transition_type));
EXPECT_EQ(DataUseTabModel::TRANSITION_OMNIBOX_NAVIGATION, transition_type);
EXPECT_TRUE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_AUTO_BOOKMARK), &transition_type));
EXPECT_EQ(DataUseTabModel::TRANSITION_BOOKMARK, transition_type);
EXPECT_TRUE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_AUTO_BOOKMARK | 0xFF00),
&transition_type));
EXPECT_EQ(DataUseTabModel::TRANSITION_BOOKMARK, transition_type);
EXPECT_TRUE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_AUTO_BOOKMARK | 0xFFFF00),
&transition_type));
EXPECT_EQ(DataUseTabModel::TRANSITION_BOOKMARK, transition_type);
EXPECT_TRUE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_AUTO_BOOKMARK | 0x12FFFF00),
&transition_type));
EXPECT_EQ(DataUseTabModel::TRANSITION_BOOKMARK, transition_type);
EXPECT_TRUE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_GENERATED), &transition_type));
EXPECT_EQ(DataUseTabModel::TRANSITION_OMNIBOX_SEARCH, transition_type);
EXPECT_TRUE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_GENERATED | 0xFF00),
&transition_type));
EXPECT_EQ(DataUseTabModel::TRANSITION_OMNIBOX_SEARCH, transition_type);
EXPECT_TRUE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_GENERATED | 0xFFFF00),
&transition_type));
EXPECT_EQ(DataUseTabModel::TRANSITION_OMNIBOX_SEARCH, transition_type);
EXPECT_TRUE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_GENERATED | 0x12FFFF00),
&transition_type));
EXPECT_EQ(DataUseTabModel::TRANSITION_OMNIBOX_SEARCH, transition_type);
EXPECT_TRUE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_RELOAD), &transition_type));
EXPECT_EQ(DataUseTabModel::TRANSITION_RELOAD, transition_type);
EXPECT_TRUE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_RELOAD | 0xFF00),
&transition_type));
EXPECT_EQ(DataUseTabModel::TRANSITION_RELOAD, transition_type);
EXPECT_TRUE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_RELOAD | 0xFFFF00),
&transition_type));
EXPECT_EQ(DataUseTabModel::TRANSITION_RELOAD, transition_type);
EXPECT_TRUE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_RELOAD | 0x12FFFF00),
&transition_type));
EXPECT_EQ(DataUseTabModel::TRANSITION_RELOAD, transition_type);
// Navigating back or forward.
EXPECT_FALSE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_RELOAD |
ui::PAGE_TRANSITION_FORWARD_BACK),
&transition_type));
EXPECT_FALSE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_AUTO_SUBFRAME), &transition_type));
EXPECT_FALSE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_MANUAL_SUBFRAME),
&transition_type));
EXPECT_FALSE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_FORM_SUBMIT), &transition_type));
}
} // namespace android
} // namespace chrome
| 18,471 | 6,576 |
#include <example/lib/c.hpp>
int main() {
c();
}
| 51 | 25 |
// Copyright 2013, James Mitchell, All rights reserved.
#pragma once
#include "typetraits/EnableIf.hpp"
#include "typetraits/CallTraits.hpp"
#include "typetraits/HasOstreamOut.hpp"
#include "typetraits/HasMemberFunction.hpp"
#include "typetraits/IsArithmetic.hpp"
#include "typetraits/IsPointer.hpp"
#include "typetraits/IsSame.hpp"
namespace util
{
}
| 356 | 137 |
#include "../../std_lib_facilities.h"
int square(int x)
{
return x * x;
}
int main(void)
{
//constexpr int first {1000};
//constexpr int second {1000000};
constexpr int third {1000000000};
bool is_overflow{false};
for (int i{0}, temp{0}; is_overflow || temp < third; ++i)
{
temp = square(i);
cout << i << " : " << temp << "\n";
}
} | 383 | 155 |
#include <ngp/ngp.hpp>
namespace ares::NeoGeoPocket {
auto enumerate() -> vector<string> {
return {
"[SNK] Neo Geo Pocket",
"[SNK] Neo Geo Pocket Color",
};
}
auto load(Node::System& node, string name) -> bool {
if(!enumerate().find(name)) return false;
return system.load(node, name);
}
Scheduler scheduler;
System system;
#include "controls.cpp"
#include "debugger.cpp"
#include "serialization.cpp"
auto System::game() -> string {
if(cartridge.node) {
return cartridge.title();
}
return "(no cartridge connected)";
}
auto System::run() -> void {
scheduler.enter();
}
auto System::load(Node::System& root, string name) -> bool {
if(node) unload();
information = {};
if(name.find("Neo Geo Pocket")) {
information.name = "Neo Geo Pocket";
information.model = Model::NeoGeoPocket;
}
if(name.find("Neo Geo Pocket Color")) {
information.name = "Neo Geo Pocket Color";
information.model = Model::NeoGeoPocketColor;
}
node = Node::System::create(information.name);
node->setGame({&System::game, this});
node->setRun({&System::run, this});
node->setPower({&System::power, this});
node->setSave({&System::save, this});
node->setUnload({&System::unload, this});
node->setSerialize({&System::serialize, this});
node->setUnserialize({&System::unserialize, this});
root = node;
if(!node->setPak(pak = platform->pak(node))) return false;
fastBoot = node->append<Node::Setting::Boolean>("Fast Boot", false);
bios.allocate(64_KiB);
if(auto fp = pak->read("bios.rom")) {
bios.load(fp);
}
scheduler.reset();
controls.load(node);
cpu.load(node);
apu.load(node);
kge.load(node);
psg.load(node);
cartridgeSlot.load(node);
debugger.load(node);
return true;
}
auto System::save() -> void {
if(!node) return;
cpu.save();
apu.save();
cartridge.save();
}
auto System::unload() -> void {
if(!node) return;
debugger.unload(node);
bios.reset();
cpu.unload();
apu.unload();
kge.unload();
psg.unload();
cartridgeSlot.unload();
pak.reset();
node.reset();
}
auto System::power(bool reset) -> void {
for(auto& setting : node->find<Node::Setting::Setting>()) setting->setLatch();
cartridge.power();
cpu.power();
apu.power();
kge.power();
psg.power();
scheduler.power(cpu);
if(fastBoot->latch() && cartridge.flash[0]) cpu.fastBoot();
}
}
| 2,372 | 886 |
#include <cstdlib>
#include <string>
// Implementation of the DJB hash
uint64_t djb(const std::string& str)
{
uint64_t hash = 5381;
// mix in each octet
for (auto oct : str)
{
hash += hash << 5;
hash += oct;
}
return hash;
}
| 238 | 107 |
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int sum = 0;
void *summer(void *); //function to run inside thread
int main(int argc, char *argv[])
{
pthread_t tid;
pthread_attr_t attr;
if (argc != 2) // if 2 arguments are not passed on commandline, show error
{
fprintf(stderr, "usage: %s <integer value>\n", argv[0]);
exit(1);
}
else if (atoi(argv[1]) < 0) // if a negative value is passed as an argument, show error
{
fprintf(stderr, "integer value must be > 0\n");
exit(1);
}
pthread_attr_init(&attr); // initializing attributes of the thread
pthread_create(&tid, &attr, summer, argv[1]); // creating thread
pthread_join(tid,NULL); // wating for thread to exit
printf("SUM: %d\n",sum);
return 0;
}
void *summer(void *param)
{
int n = atoi((char*)param);
for(int i=0;i<=n;i++)
sum+=i;
pthread_exit(0);
}
| 1,058 | 352 |
#include<iostream>
using namespace std;
int main(){
unsigned long a,b,c;
cin>>a>>b>>c;
while(a != 0, b != 0, c != 0){
if(c-b == b-a){
cout<<"AP "<< c + c - b<<endl;
}
else{
cout<<"GP "<< c * (c/b) <<endl;
}
cin>>a>>b>>c;
}
return 0;
}
| 259 | 144 |
// @doc
#include "PyWinTypes.h"
#include "PyWinObjects.h"
#include "malloc.h"
#include "Userenv.h"
#define CHECK_PFN(fname) \
if (pfn##fname == NULL) \
return PyErr_Format(PyExc_NotImplementedError, "%s is not available on this platform", #fname);
typedef BOOL(WINAPI *DeleteProfilefunc)(WCHAR *, WCHAR *, WCHAR *);
static DeleteProfilefunc pfnDeleteProfile = NULL;
typedef BOOL(WINAPI *GetAllUsersProfileDirectoryfunc)(WCHAR *, DWORD *);
static GetAllUsersProfileDirectoryfunc pfnGetAllUsersProfileDirectory = NULL;
typedef BOOL(WINAPI *GetDefaultUserProfileDirectoryfunc)(WCHAR *, DWORD *);
static GetDefaultUserProfileDirectoryfunc pfnGetDefaultUserProfileDirectory = NULL;
typedef BOOL(WINAPI *GetProfilesDirectoryfunc)(WCHAR *, DWORD *);
static GetProfilesDirectoryfunc pfnGetProfilesDirectory = NULL;
typedef BOOL(WINAPI *GetProfileTypefunc)(DWORD *);
static GetProfileTypefunc pfnGetProfileType = NULL;
typedef BOOL(WINAPI *GetUserProfileDirectoryfunc)(HANDLE, WCHAR *, DWORD *);
static GetUserProfileDirectoryfunc pfnGetUserProfileDirectory = NULL;
typedef BOOL(WINAPI *LoadUserProfilefunc)(HANDLE, LPPROFILEINFOW);
static LoadUserProfilefunc pfnLoadUserProfile = NULL;
typedef BOOL(WINAPI *UnloadUserProfilefunc)(HANDLE, HANDLE);
static UnloadUserProfilefunc pfnUnloadUserProfile = NULL;
typedef BOOL(WINAPI *ExpandEnvironmentStringsForUserfunc)(HANDLE, LPWSTR, LPWSTR, DWORD);
static ExpandEnvironmentStringsForUserfunc pfnExpandEnvironmentStringsForUser = NULL;
/* Takes an environment block and returns a dict suitable for passing to CreateProcess
or CreateProcessAsUser. Length is not known, so you have to depend on the block being correctly formatted.
There are also several other pieces of code handling these types of strings:
win32process(building an environment block from a dict), win32service (service dependencies),
win32print(list of driver files), win32api(REG_MULTI_SZ values)
Should probably consolidate into one place
*/
PyObject *PyWinObject_FromEnvironmentBlock(WCHAR *multistring)
{
PyObject *key, *val, *ret = NULL;
WCHAR *eq;
size_t keylen, vallen, totallen;
if (multistring == NULL) {
Py_INCREF(Py_None);
return Py_None;
}
ret = PyDict_New();
if (ret == NULL)
return NULL;
totallen = wcslen(multistring);
while (totallen) {
/* Use *last* equal sign as separator, since per-drive working dirs are stored in the environment in the form
"=C:=C:\\somedir","=D:=D:\\someotherdir". These are retrievable by win32api.GetEnvironmentVariable('=C:'),
but don't appear in os.environ and are apparently undocumented
*/
eq = wcsrchr(multistring, '=');
if (eq == NULL) {
// Use blank string for value if no equal sign present. ???? Maybe throw an error instead ????
vallen = 0;
val = PyWinObject_FromWCHAR(L"");
}
else {
vallen = wcslen(++eq);
val = PyUnicode_FromWideChar(eq, vallen);
}
keylen = totallen - (vallen + 1);
key = PyUnicode_FromWideChar(multistring, keylen);
if ((key == NULL) || (val == NULL) || (PyDict_SetItem(ret, key, val) == -1)) {
Py_XDECREF(key);
Py_XDECREF(val);
Py_DECREF(ret);
return NULL;
}
Py_DECREF(key);
Py_DECREF(val);
multistring += (totallen + 1);
totallen = wcslen(multistring);
}
return ret;
}
void PyWinObject_FreePROFILEINFO(LPPROFILEINFO pi)
{
PyWinObject_FreeWCHAR(pi->lpUserName);
PyWinObject_FreeWCHAR(pi->lpProfilePath);
PyWinObject_FreeWCHAR(pi->lpDefaultPath);
PyWinObject_FreeWCHAR(pi->lpServerName);
PyWinObject_FreeWCHAR(pi->lpPolicyPath);
ZeroMemory(pi, sizeof(PROFILEINFO));
}
// @object PyPROFILEINFO|Dictionary containing data to fill a PROFILEINFO struct, to be passed to <om
// win32profile.LoadUserProfile>. UserName is only required member.
// @pyseeapi PROFILEINFO
// @prop <o PyUnicode>|UserName|Name of user for which to load profile
// @prop int|Flags|Combination of PI_* flags
// @prop <o PyUnicode>|ProfilePath|Path to roaming profile, can be None. Use <om win32net.NetUserGetInfo> to retrieve
// user's profile path
// @prop <o PyUnicode>|DefaultPath|Path to Default user profile, can be None
// @prop <o PyUnicode>|ServerName|Domain controller, can be None
// @prop <o PyUnicode>|PolicyPath|Location of policy file, can be None
// @prop <o PyHKEY>|Profile|Handle to root of user's registry key. This member is output.
BOOL PyWinObject_AsPROFILEINFO(PyObject *ob, LPPROFILEINFO pi)
{
BOOL ret;
static char *elements[] = {"UserName", "Flags", "ProfilePath", "DefaultPath",
"ServerName", "PolicyPath", "Profile", NULL};
PyObject *obUserName = Py_None, *obProfilePath = Py_None, *obDefaultPath = Py_None, *obServerName = Py_None,
*obPolicyPath = Py_None, *obhProfile = Py_None;
PyObject *dummy_args = NULL;
ZeroMemory(pi, sizeof(PROFILEINFOW));
pi->dwSize = sizeof(PROFILEINFOW);
if (!PyDict_Check(ob)) {
PyErr_SetString(PyExc_TypeError, "PROFILEINFO must be a dictionary");
return FALSE;
}
dummy_args = PyTuple_New(0);
if (dummy_args == NULL)
return FALSE;
ret = PyArg_ParseTupleAndKeywords(dummy_args, ob, "O|kOOOOO:LoadUserProfile", elements, &obUserName, &pi->dwFlags,
&obProfilePath, &obDefaultPath, &obServerName, &obPolicyPath, &obhProfile) &&
PyWinObject_AsWCHAR(obUserName, &pi->lpUserName, FALSE) &&
PyWinObject_AsWCHAR(obProfilePath, &pi->lpProfilePath, TRUE) &&
PyWinObject_AsWCHAR(obDefaultPath, &pi->lpDefaultPath, TRUE) &&
PyWinObject_AsWCHAR(obServerName, &pi->lpServerName, TRUE) &&
PyWinObject_AsWCHAR(obPolicyPath, &pi->lpPolicyPath, TRUE) && PyWinObject_AsHANDLE(obhProfile, &pi->hProfile);
Py_DECREF(dummy_args);
if (!ret)
PyWinObject_FreePROFILEINFO(pi);
return ret;
}
// @pymethod <o PyHKEY>|win32profile|LoadUserProfile|Loads user settings into registry
// @comm SE_BACKUP_NAME and SE_RESTORE_NAME privs are required, but do not have to be enabled
// @rdesc Returns a handle to user's registry key.
PyObject *PyLoadUserProfile(PyObject *self, PyObject *args, PyObject *kwargs)
{
static char *keywords[] = {"Token", "ProfileInfo", NULL};
CHECK_PFN(LoadUserProfile)
PyObject *obhToken, *obPROFILEINFO, *ret = NULL;
HANDLE hToken;
DWORD dwFlags = 0;
BOOL success = TRUE;
PROFILEINFOW profileinfo = {NULL};
if (!PyArg_ParseTupleAndKeywords(
args, kwargs, "OO:LoadUserProfile", keywords,
&obhToken, // @pyparm <o PyHANDLE>|hToken||Logon token as returned by <om win32security.LogonUser>, <om
// win32security.OpenThreadToken>, etc
&obPROFILEINFO)) // @pyparm <o PyPROFILEINFO>|ProfileInfo||Dictionary representing a PROFILEINFO structure
return NULL;
if (!PyWinObject_AsHANDLE(obhToken, &hToken))
return NULL;
if (!PyWinObject_AsPROFILEINFO(obPROFILEINFO, &profileinfo))
return NULL;
if (!(*pfnLoadUserProfile)(hToken, &profileinfo))
PyWin_SetAPIError("LoadUserProfile");
else
ret = new PyHKEY(profileinfo.hProfile);
PyWinObject_FreePROFILEINFO(&profileinfo);
return ret;
}
// @pymethod |win32profile|UnloadUserProfile|Unloads user profile loaded by <om win32profile.LoadUserProfile>
PyObject *PyUnloadUserProfile(PyObject *self, PyObject *args, PyObject *kwargs)
{
static char *keywords[] = {"Token", "Profile", NULL};
CHECK_PFN(UnloadUserProfile);
PyObject *obhToken = NULL, *obhProfile = NULL;
HANDLE hToken, hProfile;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO:UnloadUserProfile", keywords,
&obhToken, // @pyparm <o PyHANDLE>|Token||Logon token as returned by <om
// win32security.LogonUser>, <om win32security.OpenProcessToken>, etc
&obhProfile)) // @pyparm <o PyHKEY>|Profile||Registry handle as returned by <om
// win32profile.LoadUserProfile>
return NULL;
if (!PyWinObject_AsHANDLE(obhToken, &hToken))
return NULL;
if (!PyWinObject_AsHANDLE(obhProfile, &hProfile))
return NULL;
if (!(*pfnUnloadUserProfile)(hToken, hProfile)) {
PyWin_SetAPIError("UnloadUserProfile");
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod <o PyUnicode>|win32profile|GetProfilesDirectory|Retrieves directory where user profiles are stored
static PyObject *PyGetProfilesDirectory(PyObject *self, PyObject *args, PyObject *kwargs)
{
static char *keywords[] = {NULL};
CHECK_PFN(GetProfilesDirectory);
WCHAR *profile_path = NULL;
DWORD bufsize = 0, err = 0;
PyObject *ret = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, ":GetProfilesDirectory", keywords))
return (NULL);
(*pfnGetProfilesDirectory)(profile_path, &bufsize);
if (bufsize == 0)
return PyWin_SetAPIError("GetProfilesDirectory");
profile_path = (WCHAR *)malloc(bufsize * sizeof(WCHAR));
if (profile_path == NULL) {
PyErr_Format(PyExc_MemoryError, "Unable to allocate %d characters", bufsize);
return NULL;
}
if (!(*pfnGetProfilesDirectory)(profile_path, &bufsize))
PyWin_SetAPIError("GetProfilesDirectory");
else
ret = PyWinObject_FromWCHAR(profile_path);
free(profile_path);
return ret;
}
// @pymethod <o PyUnicode>|win32profile|GetAllUsersProfileDirectory|Retrieve All Users profile path
static PyObject *PyGetAllUsersProfileDirectory(PyObject *self, PyObject *args, PyObject *kwargs)
{
static char *keywords[] = {NULL};
CHECK_PFN(GetAllUsersProfileDirectory);
WCHAR *profile_path = NULL;
DWORD bufsize = 0, err = 0;
PyObject *ret = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, ":GetAllUsersProfileDirectory", keywords))
return (NULL);
(*pfnGetAllUsersProfileDirectory)(profile_path, &bufsize);
if (bufsize == 0)
return PyWin_SetAPIError("GetAllUsersProfileDirectory");
profile_path = (WCHAR *)malloc(bufsize * sizeof(WCHAR));
if (profile_path == NULL) {
PyErr_Format(PyExc_MemoryError, "Unable to allocate %d characters", bufsize);
return NULL;
}
if (!(*pfnGetAllUsersProfileDirectory)(profile_path, &bufsize))
PyWin_SetAPIError("GetAllUsersProfileDirectory");
else
ret = PyWinObject_FromWCHAR(profile_path);
free(profile_path);
return ret;
}
// @pymethod <o PyUnicode>|win32profile|GetDefaultUserProfileDirectory|Retrieve Default user profile
static PyObject *PyGetDefaultUserProfileDirectory(PyObject *self, PyObject *args, PyObject *kwargs)
{
static char *keywords[] = {NULL};
CHECK_PFN(GetDefaultUserProfileDirectory);
WCHAR *profile_path = NULL;
DWORD bufsize = 0, err = 0;
PyObject *ret = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, ":GetDefaultUserProfileDirectory", keywords))
return (NULL);
(*pfnGetDefaultUserProfileDirectory)(profile_path, &bufsize);
if (bufsize == 0)
return PyWin_SetAPIError("GetDefaultUserProfileDirectory");
profile_path = (WCHAR *)malloc(bufsize * sizeof(WCHAR));
if (profile_path == NULL) {
PyErr_SetString(PyExc_MemoryError, "GetDefaultUserProfileDirectory unable to allocate unicode buffer");
return NULL;
}
if (!(*pfnGetDefaultUserProfileDirectory)(profile_path, &bufsize))
PyWin_SetAPIError("GetDefaultUserProfileDirectory");
else
ret = PyWinObject_FromWCHAR(profile_path);
free(profile_path);
return ret;
}
// @pymethod <o PyUnicode>|win32profile|GetUserProfileDirectory|Returns profile directory for a logon token
PyObject *PyGetUserProfileDirectory(PyObject *self, PyObject *args, PyObject *kwargs)
{
static char *keywords[] = {"Token", NULL};
CHECK_PFN(GetUserProfileDirectory);
HANDLE hToken;
WCHAR *profile_path = NULL;
DWORD bufsize = 0;
PyObject *obhToken = NULL, *ret = NULL;
if (!PyArg_ParseTupleAndKeywords(
args, kwargs, "O:GetUserProfileDirectory", keywords,
&obhToken)) // @pyparm <o PyHANDLE>|Token||User token as returned by <om win32security.LogonUser>
return NULL;
if (!PyWinObject_AsHANDLE(obhToken, &hToken))
return NULL;
(*pfnGetUserProfileDirectory)(hToken, profile_path, &bufsize);
if (bufsize == 0)
return PyWin_SetAPIError("GetUserProfileDirectory");
profile_path = (WCHAR *)malloc(bufsize * sizeof(WCHAR));
if (profile_path == NULL) {
PyErr_Format(PyExc_MemoryError, "Unable to allocate %d characters", bufsize);
return NULL;
}
if (!(*pfnGetUserProfileDirectory)(hToken, profile_path, &bufsize))
PyWin_SetAPIError("GetUserProfileDirectory");
else
ret = PyWinObject_FromWCHAR(profile_path);
free(profile_path);
return ret;
}
//@pymethod |win32profile|DeleteProfile|Remove profile for a user identified by string SID from specified machine.
PyObject *PyDeleteProfile(PyObject *self, PyObject *args, PyObject *kwargs)
{
static char *keywords[] = {"SidString", "ProfilePath", "ComputerName", NULL};
CHECK_PFN(DeleteProfile);
PyObject *obstrsid = Py_None, *obprofile_path = Py_None, *obmachine = Py_None, *ret = NULL;
WCHAR *strsid = NULL, *profile_path = NULL, *machine = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|OO:DeleteProfile", keywords,
&obstrsid, // @pyparm <o PyUnicode>|SidString||String representation of user's
// Sid. See <om win32security.ConvertSidToStringSid>.
&obprofile_path, // @pyparm <o PyUnicode>|ProfilePath|None|Profile directory,
// value queried from registry if not specified
&obmachine)) // @pyparm <o PyUnicode>|ComputerName|None|Name of computer from
// which to delete profile, local machine assumed if not specified
return NULL;
if (PyWinObject_AsWCHAR(obstrsid, &strsid, FALSE) && PyWinObject_AsWCHAR(obprofile_path, &profile_path, TRUE) &&
PyWinObject_AsWCHAR(obmachine, &machine, TRUE)) {
if ((*pfnDeleteProfile)(strsid, profile_path, machine)) {
Py_INCREF(Py_None);
ret = Py_None;
}
else
PyWin_SetAPIError("DeleteProfile");
}
PyWinObject_FreeWCHAR(strsid);
PyWinObject_FreeWCHAR(profile_path);
PyWinObject_FreeWCHAR(machine);
return ret;
}
// @pymethod int|win32profile|GetProfileType|Returns type of current user's profile
// @rdesc Returns a combination of PT_* flags
PyObject *PyGetProfileType(PyObject *self, PyObject *args, PyObject *kwargs)
{
static char *keywords[] = {NULL};
CHECK_PFN(GetProfileType);
if (!PyArg_ParseTupleAndKeywords(args, kwargs, ":GetProfileType", keywords))
return NULL;
DWORD ptype = 0;
if (!(*pfnGetProfileType)(&ptype)) {
PyWin_SetAPIError("GetProfileType");
return NULL;
}
return PyLong_FromUnsignedLong(ptype);
}
// @pymethod dict|win32profile|CreateEnvironmentBlock|Retrieves environment variables for a user
PyObject *PyCreateEnvironmentBlock(PyObject *self, PyObject *args, PyObject *kwargs)
{
static char *keywords[] = {"Token", "Inherit", NULL};
HANDLE hToken;
BOOL inherit;
LPVOID env;
PyObject *obhToken = NULL, *ret = NULL;
if (!PyArg_ParseTupleAndKeywords(
args, kwargs, "Ol:CreateEnvironmentBlock", keywords,
&obhToken, // @pyparm <o PyHANDLE>|Token||User token as returned by <om win32security.LogonUser>, use None
// to retrieve system variables only
&inherit)) // @pyparm boolean|Inherit||Indicates if environment of current process should be inherited
return NULL;
if (!PyWinObject_AsHANDLE(obhToken, &hToken))
return NULL;
if (!CreateEnvironmentBlock(&env, hToken, inherit))
PyWin_SetAPIError("CreateEnvironmentBlock");
else {
ret = PyWinObject_FromEnvironmentBlock((WCHAR *)env);
DestroyEnvironmentBlock(env);
}
return ret;
}
// @pymethod dict|win32profile|GetEnvironmentStrings|Retrieves environment variables for current process
PyObject *PyGetEnvironmentStrings(PyObject *self, PyObject *args, PyObject *kwargs)
{
static char *keywords[] = {NULL};
WCHAR *env;
PyObject *ret = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, ":GetEnvironmentStrings", keywords))
return NULL;
env = GetEnvironmentStrings();
if (env == NULL)
PyWin_SetAPIError("GetEnvironmentStrings");
else {
ret = PyWinObject_FromEnvironmentBlock((WCHAR *)env);
FreeEnvironmentStrings(env);
}
return ret;
}
//@pymethod <o PyUnicode>|win32profile|ExpandEnvironmentStringsForUser|Replaces environment variables in a string with
// per-user values
PyObject *PyExpandEnvironmentStringsForUser(PyObject *self, PyObject *args, PyObject *kwargs)
{
static char *keywords[] = {"Token", "Src", NULL};
CHECK_PFN(ExpandEnvironmentStringsForUser);
PyObject *obtoken, *obsrc, *ret = NULL;
HANDLE htoken;
WCHAR *src = NULL, *dst = NULL;
DWORD bufsize;
if (!PyArg_ParseTupleAndKeywords(
args, kwargs, "OO:ExpandEnvironmentStringsForUser", keywords,
&obtoken, // @pyparm <o PyHANDLE>|Token||The logon token for a user. Use None for system variables.
&obsrc)) // @pyparm <o PyUnicode>|Src||String containing environment variables enclosed in % signs
return NULL;
if (!PyWinObject_AsHANDLE(obtoken, &htoken) || !PyWinObject_AsWCHAR(obsrc, &src, FALSE, &bufsize))
return NULL;
// Increase initial allocation to reduce reallocation
// MSDN says the Size param is in TCHARS, but it acts as if it's in bytes
bufsize *= 4;
while (TRUE) {
if (dst != NULL)
free(dst);
bufsize *= 2;
dst = (WCHAR *)malloc(bufsize);
if (dst == NULL) {
PyErr_Format(PyExc_MemoryError, "Unable to allocate %d bytes", bufsize);
break;
}
if ((*pfnExpandEnvironmentStringsForUser)(htoken, src, dst, bufsize)) {
ret = PyWinObject_FromWCHAR(dst);
break;
}
if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
PyWin_SetAPIError("ExpandEnvironmentStringsForUser");
break;
}
}
PyWinObject_FreeWCHAR(src);
if (dst != NULL)
free(dst);
return ret;
}
// @module win32profile|Wraps functions for dealing with user profiles
static struct PyMethodDef win32profile_functions[] = {
//@pymeth CreateEnvironmentBlock|Retrieves environment variables for a user
{"CreateEnvironmentBlock", (PyCFunction)PyCreateEnvironmentBlock, METH_VARARGS | METH_KEYWORDS,
"Retrieves environment variables for a user"},
// @pymeth DeleteProfile|Removes a user's profile
{"DeleteProfile", (PyCFunction)PyDeleteProfile, METH_VARARGS | METH_KEYWORDS, "Remove a user's profile"},
// @pymeth ExpandEnvironmentStringsForUser|Replaces environment variables in a string with per-user values
{"ExpandEnvironmentStringsForUser", (PyCFunction)PyExpandEnvironmentStringsForUser, METH_VARARGS | METH_KEYWORDS,
"Replaces environment variables in a string with per-user values"},
//@pymeth GetAllUsersProfileDirectory|Retrieve All Users profile directory
{"GetAllUsersProfileDirectory", (PyCFunction)PyGetAllUsersProfileDirectory, METH_VARARGS | METH_KEYWORDS,
"Retrieve All Users profile directory"},
//@pymeth GetDefaultUserProfileDirectory|Retrieve profile path for Default user
{"GetDefaultUserProfileDirectory", (PyCFunction)PyGetDefaultUserProfileDirectory, METH_VARARGS | METH_KEYWORDS,
"Retrieve profile path for Default user"},
//@pymeth GetEnvironmentStrings|Retrieves environment variables for current process
{"GetEnvironmentStrings", (PyCFunction)PyGetEnvironmentStrings, METH_VARARGS | METH_KEYWORDS,
"Retrieves environment variables for current process"},
//@pymeth GetProfilesDirectory|Retrieves directory where user profiles are stored
{"GetProfilesDirectory", (PyCFunction)PyGetProfilesDirectory, METH_VARARGS | METH_KEYWORDS,
"Retrieves directory where user profiles are stored"},
//@pymeth GetProfileType|Returns type of current user's profile
{"GetProfileType", (PyCFunction)PyGetProfileType, METH_VARARGS | METH_KEYWORDS,
"Returns type of current user's profile"},
// @pymeth GetUserProfileDirectory|Returns profile directory for a logon token
{"GetUserProfileDirectory", (PyCFunction)PyGetUserProfileDirectory, METH_VARARGS | METH_KEYWORDS,
"Returns profile directory for a logon token"},
//@pymeth LoadUserProfile|Load user settings for a login token
{"LoadUserProfile", (PyCFunction)PyLoadUserProfile, METH_VARARGS | METH_KEYWORDS,
"Load user settings for a login token"},
//@pymeth UnloadUserProfile|Unload profile loaded by LoadUserProfile
{"UnloadUserProfile", (PyCFunction)PyUnloadUserProfile, METH_VARARGS | METH_KEYWORDS,
"Unload profile loaded by LoadUserProfile"},
{NULL, NULL}};
PYWIN_MODULE_INIT_FUNC(win32profile)
{
PYWIN_MODULE_INIT_PREPARE(win32profile, win32profile_functions, "Interface to the User Profile Api.");
// PROFILEINFO flags
PyModule_AddIntConstant(module, "PI_NOUI", PI_NOUI);
PyModule_AddIntConstant(module, "PI_APPLYPOLICY", PI_APPLYPOLICY);
// profile types
PyModule_AddIntConstant(module, "PT_MANDATORY", PT_MANDATORY);
PyModule_AddIntConstant(module, "PT_ROAMING", PT_ROAMING);
PyModule_AddIntConstant(module, "PT_TEMPORARY", PT_TEMPORARY);
HMODULE hmodule;
hmodule = GetModuleHandle(L"Userenv.dll");
if (hmodule == NULL)
hmodule = LoadLibrary(L"Userenv.dll");
if (hmodule != NULL) {
pfnDeleteProfile = (DeleteProfilefunc)GetProcAddress(hmodule, "DeleteProfileW");
pfnExpandEnvironmentStringsForUser =
(ExpandEnvironmentStringsForUserfunc)GetProcAddress(hmodule, "ExpandEnvironmentStringsForUserW");
pfnGetAllUsersProfileDirectory =
(GetAllUsersProfileDirectoryfunc)GetProcAddress(hmodule, "GetAllUsersProfileDirectoryW");
pfnGetDefaultUserProfileDirectory =
(GetDefaultUserProfileDirectoryfunc)GetProcAddress(hmodule, "GetDefaultUserProfileDirectoryW");
pfnGetProfilesDirectory = (GetProfilesDirectoryfunc)GetProcAddress(hmodule, "GetProfilesDirectoryW");
pfnGetProfileType = (GetProfileTypefunc)GetProcAddress(hmodule, "GetProfileType");
pfnGetUserProfileDirectory = (GetUserProfileDirectoryfunc)GetProcAddress(hmodule, "GetUserProfileDirectoryW");
pfnLoadUserProfile = (LoadUserProfilefunc)GetProcAddress(hmodule, "LoadUserProfileW");
pfnUnloadUserProfile = (UnloadUserProfilefunc)GetProcAddress(hmodule, "UnloadUserProfile");
}
PYWIN_MODULE_INIT_RETURN_SUCCESS;
}
| 23,451 | 7,252 |
/* The key of each element is the array index of the element.
* Time: O(log N)
* Memory: O(N)
*/
#include <bits/stdc++.h>
using namespace std;
struct Splay {
struct Node {
int val, sz;
Node *child[2], *par;
Node() {}
Node(int val, int sz = 1) : val(val), sz(sz) {
child[0] = child[1] = par = this;
}
};
Node *root;
static Node *null;
Splay() {
null = new Node();
null->child[0] = null->child[1] = null->par = null;
null->sz = 0;
root = null;
}
static void connect(Node *u, Node *v, int dir) {
u->child[dir] = v;
v->par = u;
}
static void update(Node *u) {
if (u != null)
u->sz = 1 + u->child[0]->sz + u->child[1]->sz;
}
// 0 = left, 1 = right;
static Node *rotate(Node *u, int dir) {
Node *c = u->child[dir ^ 1], *p = u->par, *pp = p->par;
connect(p, c, dir);
connect(u, p, dir ^ 1);
connect(pp, u, getDir(p, pp));
update(p);
update(u);
update(pp);
return u;
}
static int getDir(Node *u, Node *p) {
return p->child[0] == u ? 0 : 1;
}
static Node *splay(Node *u) {
while (u->par != null) {
Node *p = u->par, *pp = p->par;
int dp = getDir(u, p), dpp = getDir(p, pp);
if (pp == null)
rotate(u, dp);
else if (dp == dpp)
rotate(p, dpp), rotate(u, dp);
else
rotate(u, dp), rotate(u, dpp);
}
return u;
}
static Node *nodeAt(Node *u, int index) {
if (u == null)
return u;
Node *ret = u;
while (u != null) {
ret = u;
if (u->child[0]->sz + 1 < index)
index -= u->child[0]->sz + 1, u = u->child[1];
else if (u->child[0]->sz + 1 > index)
u = u->child[0];
else
return u;
}
return ret;
}
// precondition: all values of u are smaller than all values of v
static Node *join(Node *u, Node *v) {
if (u == null)
return v;
while (u->child[1] != null)
u = u->child[1];
splay(u);
u->child[1] = v;
update(u);
if (v != null)
v->par = u;
return u;
}
static pair<Node *, Node *> split(Node *u, int index) {
if (u == null)
return {null, null};
splay(u = nodeAt(u, index));
if (u->child[0]->sz + 1 <= index) {
Node *ret = u->child[1];
u->child[1] = (u->child[1]->par = null);
update(u);
update(ret);
return {u, ret};
} else {
Node *ret = u->child[0];
u->child[0] = (u->child[0]->par = null);
update(u);
update(ret);
return {ret, u};
}
}
void modify(int index, int val) {
Node *curr = root;
while (curr != null) {
if (curr->child[0]->sz + 1 < index)
index -= curr->child[0]->sz + 1, curr = curr->child[1];
else if (curr->child[0]->sz + 1 > index)
curr = curr->child[0];
else {
curr->val = val;
return;
}
}
}
void push_back(int val) {
Node *u = new Node(val);
u->child[0] = u->child[1] = u->par = null;
root = join(root, u);
}
void insert(int index, int val) {
auto res = split(root, index);
root = new Node(val);
root->par = null;
root->child[0] = res.first, root->child[1] = res.second;
update(root);
if (root->child[0] != null)
root->child[0]->par = root;
if (root->child[1] != null)
root->child[1]->par = root;
}
void remove(int index) {
Node *curr = nodeAt(root, index);
splay(curr);
curr->child[0]->par = curr->child[1]->par = null;
root = join(curr->child[0], curr->child[1]);
}
int get(int index) {
return nodeAt(root, index)->val;
}
};
Splay::Node *Splay::null = new Node(0, 0);
| 3,657 | 1,455 |
#include <iostream>
using namespace std;
int main()
{
int k, l, m, n, d;
cin >> k >> l >> m >> n >> d;
// kth got punched in the face with frying pan
// lth got shut in the balcony door
// mmeth got his paws trampled
// nth to call her mom
int count = d;
if (l == 1 || k == 1 || m == 1 || n == 1)
cout << count << endl;
else
{
for (int i = 1; i <= d; i++)
{
// we are subtracting the ones where all are not divisible by
// any of k, l, m and n
if (i % k != 0 && i % l != 0 && i % m != 0 && i % n != 0)
count--;
}
cout << count << endl;
}
return 0;
} | 694 | 251 |
// ----------------- BEGIN LICENSE BLOCK ---------------------------------
//
// Copyright (C) 2018-2020 Intel Corporation
//
// SPDX-License-Identifier: MIT
//
// ----------------- END LICENSE BLOCK -----------------------------------
#include <ad/map/access/Factory.hpp>
#include <ad/map/access/Operation.hpp>
#include <ad/map/lane/LaneOperation.hpp>
#include <ad/map/point/Operation.hpp>
#include <ad/map/serialize/SerializerFileCRC32.hpp>
#include <gtest/gtest.h>
#include "../src/access/GeometryStore.hpp"
using namespace ::ad;
using namespace ::ad::map;
using namespace ::ad::map::point;
using namespace ::ad::map::lane;
struct GeometryStoreTest : ::testing::Test
{
GeometryStoreTest()
{
}
virtual void SetUp()
{
}
virtual void TearDown()
{
access::cleanup();
}
};
TEST_F(GeometryStoreTest, GeometryStore)
{
ASSERT_TRUE(access::init("test_files/Town01.txt"));
access::GeometryStore geoStore;
EXPECT_THROW(geoStore.store(NULL), std::runtime_error);
EXPECT_THROW(geoStore.restore(NULL), std::runtime_error);
EXPECT_THROW(geoStore.check(NULL), std::runtime_error);
auto lanes = lane::getLanes();
ASSERT_GT(lanes.size(), 0u);
auto lanePtr = lane::getLanePtr(lanes[0]);
ASSERT_TRUE(geoStore.store(lanePtr));
ASSERT_TRUE(geoStore.check(lanePtr));
lane::Lane::Ptr oneLane;
oneLane.reset(new lane::Lane());
oneLane->id = lanes[0];
ASSERT_TRUE(geoStore.restore(oneLane));
ASSERT_EQ(oneLane->edgeLeft.ecefEdge, lanePtr->edgeLeft.ecefEdge);
ASSERT_EQ(oneLane->edgeRight.ecefEdge, lanePtr->edgeRight.ecefEdge);
}
TEST_F(GeometryStoreTest, StoreSerialization)
{
ASSERT_TRUE(access::init("test_files/Town01.txt"));
access::Store &store = access::getStore();
size_t versionMajor = ::ad::map::serialize::SerializerFileCRC32::VERSION_MAJOR;
size_t versionMinor = ::ad::map::serialize::SerializerFileCRC32::VERSION_MINOR;
serialize::SerializerFileCRC32 serializer_w(true);
ASSERT_TRUE(serializer_w.open("test_files/test_StoreSerialization.adm", versionMajor, versionMinor));
ASSERT_TRUE(store.save(serializer_w, false, false, true));
ASSERT_TRUE(serializer_w.close());
serialize::SerializerFileCRC32 serializer_r(false);
ASSERT_EQ(serializer_r.getStorageType(), "File");
ASSERT_EQ(serializer_r.getChecksumType(), "CRC-32");
ASSERT_TRUE(serializer_r.open("test_files/test_StoreSerialization.adm", versionMajor, versionMinor));
access::Store::Ptr storeRead;
storeRead.reset(new access::Store());
ASSERT_TRUE(storeRead->load(serializer_r));
ASSERT_TRUE(serializer_r.close());
serialize::SerializerFileCRC32 serializer_w2(true);
ASSERT_TRUE(serializer_w2.open("test_files/test_StoreSerialization.adm", versionMajor, versionMinor));
ASSERT_TRUE(store.save(serializer_w2, false, true, true));
ASSERT_TRUE(serializer_w2.close());
serialize::SerializerFileCRC32 serializer_r2(false);
ASSERT_TRUE(serializer_r2.open("test_files/test_StoreSerialization.adm", versionMajor, versionMinor));
access::Store::Ptr storeRead2;
storeRead2.reset(new access::Store());
ASSERT_TRUE(storeRead2->load(serializer_r2));
ASSERT_TRUE(serializer_r2.close());
}
| 3,140 | 1,179 |
#include "logger.hpp"
using namespace VictoryConnect;
| 54 | 16 |
#include <QApplication>
#include <QMainWindow>
#include <QGridLayout>
#include <QPushButton>
#include <QMouseEvent>
#include <QPainter>
#include <QTimer>
#include "kgd/external/cxxopts.hpp"
#include "kgd/utils/indentingostream.h"
#include "minicgp.h"
DEFINE_NAMESPACE_PRETTY_ENUMERATION(watchmaker, VideoInputs, X, Y, T, R, G, B)
DEFINE_NAMESPACE_PRETTY_ENUMERATION(watchmaker, RGBOutputs, R_, G_, B_)
using CGP = cgp::CGP<watchmaker::VideoInputs, 10, watchmaker::RGBOutputs>;
namespace watchmaker {
using Callback = std::function<void(const CGP&)>;
static constexpr int STEPS = 50;
static constexpr int LOOP_DURATION = 2; // seconds
struct CGPViewer : public QPushButton {
static constexpr int SIDE = 50;
static constexpr int MARGIN = 10;
static constexpr QSize SIZE = QSize(SIDE + 2 * MARGIN, SIDE + 2 * MARGIN);
CGP &cgp;
Callback callback;
QImage img;
int step;
bool up = true;
CGPViewer(CGP &cgp, Callback c)
: QPushButton(nullptr), cgp(cgp), callback(c),
img(SIDE, SIDE, QImage::Format_RGB32) {
img.fill(Qt::gray);
setFocusPolicy(Qt::NoFocus);
setAutoExclusive(true);
setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
step = 0;
}
void cgpUpdated (void) {
setToolTip(QString::fromStdString(cgp.toTex()));
img.fill(Qt::gray);
}
void nextFrame (void) {
QRgb *pixels = reinterpret_cast<QRgb*>(img.scanLine(0));
CGP::Inputs inputs;
inputs[T] = 2. * step / (STEPS - 1) - 1;
for (int i=0; i<SIDE; i++) {
for (int j=0; j<SIDE; j++) {
inputs[X] = double(2) * i / (SIDE-1) - 1;
inputs[Y] = double(2) * j / (SIDE-1) - 1;
QRgb &pixel = pixels[i*SIDE+j];
inputs[R] = 2 * qRed(pixel) / 255. - 1;
inputs[G] = 2 * qGreen(pixel) / 255. - 1;
inputs[B] = 2 * qBlue(pixel) / 255. - 1;
CGP::Outputs outputs;
cgp.evaluate(inputs, outputs);
pixel = qRgb(255 * (outputs[R_] * .5 + .5),
255 * (outputs[G_] * .5 + .5),
255 * (outputs[B_] * .5 + .5));
}
}
if (up) {
step++;
up = (step < STEPS);
} else {
step--;
up = (step <= 0);
}
update();
}
QSize sizeHint (void) const {
return SIZE;
}
void paintEvent(QPaintEvent *event) {
QPushButton::paintEvent(event);
QPainter painter (this);
painter.drawImage(rect().adjusted(MARGIN, MARGIN, -MARGIN, -MARGIN), img);
}
void mouseReleaseEvent(QMouseEvent *event) {
if (event->button() == Qt::LeftButton)
callback(cgp);
else if (event->button() == Qt::RightButton) {
static int i = 0;
std::ostringstream oss;
oss << "cgp_bw_test_" << i++ << ".pdf";
stdfs::path path = oss.str();
cgp.toDot(path, CGP::FULL | CGP::NO_ARITY);
oss.str("");
oss << "xdg-open " << path;
std::string cmd = oss.str();
system(cmd.c_str());
}
}
};
} // end of namespace watchmaker
int main (int argc, char *argv[]) {
// ===========================================================================
// == Command line arguments parsing
using Verbosity = config::Verbosity;
std::string configFile = "auto"; // Default to auto-config
Verbosity verbosity = Verbosity::SHOW;
cxxopts::Options options("MiniCGP-blindwatchmaker",
"Exhibit MiniCGP capabilities through a blind"
" watchmaker algorithm");
options.add_options()
("h,help", "Display help")
("a,auto-config", "Load configuration data from default location")
("c,config", "File containing configuration data",
cxxopts::value(configFile))
("v,verbosity", "Verbosity level. " + config::verbosityValues(),
cxxopts::value(verbosity))
;
auto result = options.parse(argc, argv);
if (result.count("help")) {
std::cout << options.help()
<< std::endl;
return 0;
}
if (result.count("auto-config") && result["auto-config"].as<bool>())
configFile = "auto";
config::CGP::setupConfig(configFile, verbosity);
if (configFile.empty()) config::CGP::printConfig("");
rng::FastDice dice;
auto cgps = utils::make_array<CGP, 9>([&dice] (auto) {
return CGP::null(dice);
});
std::cout << "Generated with seed " << dice.getSeed() << std::endl;
QApplication app (argc, argv);
QMainWindow w;
QWidget *widget = new QWidget;
QGridLayout *layout = new QGridLayout;
w.setCentralWidget(widget);
widget->setLayout(layout);
std::array<watchmaker::CGPViewer*, 9> viewers;
auto updateCGPs = [&dice, &viewers, &cgps]
(const CGP &newParent) {
cgps[4] = newParent;
for (uint i=0; i<3; i++) {
for (uint j=0; j<3; j++) {
uint ix = i*3+j;
if (ix != 4) {
CGP child = newParent;
// std::cerr << "Mutating IX=" << ix << ", i=" << i << ", j=" << j
// << ":\n";
// utils::IndentingOStreambuf indent (std::cerr);
child.mutate(dice);
cgps[ix] = child;
// std::cerr << std::endl;
}
viewers[ix]->cgpUpdated();
}
}
};
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++) {
uint ix = i*3+j;
auto viewer = new watchmaker::CGPViewer(cgps[ix], updateCGPs);
viewers[ix] = viewer;
layout->addWidget(viewer, i, j);
}
}
updateCGPs(cgps[4]);
w.show();
QTimer timer;
QObject::connect(&timer, &QTimer::timeout, [&viewers] {
for (watchmaker::CGPViewer *v: viewers) v->nextFrame();
});
timer.start(watchmaker::LOOP_DURATION * 1000.f / watchmaker::STEPS);
return app.exec();
}
| 5,653 | 2,193 |
#include <dqcsim>
#include <memory>
#include <vector>
#include <xpu.h>
#include <xpu/runtime>
#include <qx_representation.h>
#include "json.hpp"
#include "bimap.hpp"
// Alias the dqcsim::wrap namespace to something shorter.
namespace dqcs = dqcsim::wrap;
/**
* Function pointer type for constructing/binding QX gates.
*/
using GateConstructor = void (*)(std::vector<qx::gate*>&, std::vector<size_t>&&, dqcs::ArbData&&);
/**
* Hadamard gate constructor.
*/
static void construct_h(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
gates.push_back(new qx::hadamard(qubits[0]));
}
/**
* CNOT gate constructor.
*/
static void construct_cnot(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
gates.push_back(new qx::cnot(qubits[0], qubits[1]));
}
/**
* Toffoli gate constructor.
*/
static void construct_toffoli(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
gates.push_back(new qx::toffoli(qubits[0], qubits[1], qubits[2]));
}
/**
* Identity gate constructor.
*/
static void construct_identity(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
gates.push_back(new qx::identity(qubits[0]));
}
/**
* X gate constructor.
*/
static void construct_pauli_x(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
gates.push_back(new qx::pauli_x(qubits[0]));
}
/**
* Y gate constructor.
*/
static void construct_pauli_y(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
gates.push_back(new qx::pauli_y(qubits[0]));
}
/**
* Z gate constructor.
*/
static void construct_pauli_z(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
gates.push_back(new qx::pauli_z(qubits[0]));
}
/**
* S gate constructor.
*/
static void construct_s(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
gates.push_back(new qx::phase_shift(qubits[0]));
}
/**
* S dagger gate constructor.
*/
static void construct_s_dag(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
gates.push_back(new qx::s_dag_gate(qubits[0]));
}
/**
* T gate constructor.
*/
static void construct_t(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
gates.push_back(new qx::t_gate(qubits[0]));
}
/**
* T dagger gate constructor.
*/
static void construct_t_dag(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
gates.push_back(new qx::t_dag_gate(qubits[0]));
}
/**
* Controlled phase gate constructor.
*/
static void construct_ctrl_phase_shift(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
double angle = data.pop_arb_arg_as<double>();
gates.push_back(new qx::ctrl_phase_shift(qubits[0], qubits[1], angle));
}
/**
* Swap gate constructor.
*/
static void construct_swap(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
gates.push_back(new qx::swap(qubits[0], qubits[1]));
}
/**
* RX gate constructor.
*/
static void construct_rx(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
gates.push_back(new qx::rx(qubits[0], data.get_arb_arg_as<double>(0)));
}
/**
* RY gate constructor.
*/
static void construct_ry(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
gates.push_back(new qx::ry(qubits[0], data.get_arb_arg_as<double>(0)));
}
/**
* RZ gate constructor.
*/
static void construct_rz(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
gates.push_back(new qx::rz(qubits[0], data.get_arb_arg_as<double>(0)));
}
/**
* Measure Z constructor.
*/
static void construct_measure_z(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
for (size_t qubit : qubits) {
gates.push_back(new qx::measure(qubit));
}
}
/**
* Measure X constructor.
*/
static void construct_measure_x(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
for (size_t qubit : qubits) {
gates.push_back(new qx::measure_x(qubit));
}
}
/**
* Measure Y constructor.
*/
static void construct_measure_y(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
for (size_t qubit : qubits) {
gates.push_back(new qx::measure_y(qubit));
}
}
/**
* Prep Z constructor.
*/
static void construct_prep_z(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
for (size_t qubit : qubits) {
gates.push_back(new qx::prepz(qubit));
}
}
/**
* Prep X constructor.
*/
static void construct_prep_x(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
for (size_t qubit : qubits) {
gates.push_back(new qx::prepx(qubit));
}
}
/**
* Prep Y constructor.
*/
static void construct_prep_y(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
for (size_t qubit : qubits) {
gates.push_back(new qx::prepy(qubit));
}
}
/**
* Main plugin class for QX.
*/
class QxPlugin {
public:
// List of gates that have been received but have not been simulated yet.
// The integer before the gate specifies the number of simulation cycles
// advanced between the previous gate and this gate.
std::vector<qx::gate*> pending;
// Number of qubits allocated/to allocate within QX. This can't be changed
// anymore once QX is initialized.
size_t num_qubits = 0;
// Counter for the circuit name generator.
size_t circuit_counter = 0;
// The current quantum register. Initialized only when the first measurement
// is received.
std::shared_ptr<qx::qu_register> qreg;
// Map from upstream qubits to QX qubits.
QubitBiMap dqcs2qx;
// Map from DQCsim gates to QX gates.
dqcs::GateMap<GateConstructor> gatemap;
// Values for the depolarizing channel error model.
bool depolarizing_channel = false;
double error_probability = 0.0;
// Epsilon for gate recognition.
double epsilon = 1.0e-6;
/**
* Initialization callback.
*/
void initialize(
dqcs::PluginState &state,
dqcs::ArbCmdQueue &&cmds
) {
// Parse parameters.
for (; cmds.size() > 0; cmds.next()) {
handle_cmd(state, &cmds);
}
// Construct the gatemap.
gatemap.with_unitary(construct_h, dqcs::PredefinedGate::H, 0, epsilon);
gatemap.with_unitary(construct_cnot, dqcs::PredefinedGate::X, 1, epsilon);
gatemap.with_unitary(construct_toffoli, dqcs::PredefinedGate::X, 2, epsilon);
gatemap.with_unitary(construct_identity, dqcs::PredefinedGate::I, 0, epsilon);
gatemap.with_unitary(construct_pauli_x, dqcs::PredefinedGate::X, 0, epsilon);
gatemap.with_unitary(construct_pauli_y, dqcs::PredefinedGate::Y, 0, epsilon);
gatemap.with_unitary(construct_pauli_z, dqcs::PredefinedGate::Z, 0, epsilon);
gatemap.with_unitary(construct_s, dqcs::PredefinedGate::S, 0, epsilon);
gatemap.with_unitary(construct_s_dag, dqcs::PredefinedGate::S_DAG, 0, epsilon);
gatemap.with_unitary(construct_t, dqcs::PredefinedGate::T, 0, epsilon);
gatemap.with_unitary(construct_t_dag, dqcs::PredefinedGate::T_DAG, 0, epsilon);
gatemap.with_unitary(construct_ctrl_phase_shift, dqcs::PredefinedGate::Phase, 1, epsilon);
gatemap.with_unitary(construct_swap, dqcs::PredefinedGate::Swap, 0, epsilon);
gatemap.with_unitary(construct_rx, dqcs::PredefinedGate::RX, 0, epsilon);
gatemap.with_unitary(construct_ry, dqcs::PredefinedGate::RY, 0, epsilon);
gatemap.with_unitary(construct_rz, dqcs::PredefinedGate::RZ, 0, epsilon);
gatemap.with_measure(construct_measure_z, dqcs::PauliBasis::Z, epsilon);
gatemap.with_measure(construct_measure_x, dqcs::PauliBasis::X, epsilon);
gatemap.with_measure(construct_measure_y, dqcs::PauliBasis::Y, epsilon);
gatemap.with_prep(construct_prep_z, dqcs::PauliBasis::Z, epsilon);
gatemap.with_prep(construct_prep_x, dqcs::PauliBasis::X, epsilon);
gatemap.with_prep(construct_prep_y, dqcs::PauliBasis::Y, epsilon);
}
/**
* Qubit allocation callback.
*
* DQCsim supports allocating and freeing qubits at will, but QX doesn't.
* The trivial solution would be to just error out on the N+1'th qubit
* allocation, but we can do better than that when there are deallocations
* as well by reusing qubits that were freed. Furthermore, we only initialize
* QX when the first measurement is performed, with as many qubits as have
* been allocated at that point. The dqcs2qx bimap is used to keep track of
* which upstream qubit maps to which QX qubit.
*/
void allocate(
dqcs::PluginState &state,
dqcs::QubitSet &&qubits,
dqcs::ArbCmdQueue &&cmds
) {
// Loop over the qubits that are to be allocated.
while (qubits.size()) {
// A new DQCsim upstream qubit index to allocate.
size_t dqcsim_qubit = qubits.pop().get_index();
// Look for the first free QX qubit index.
ssize_t qx_qubit = -1;
for (size_t q = 0; q < num_qubits; q++) {
if (dqcs2qx.reverse_lookup(q) < 0) {
qx_qubit = q;
break;
}
}
// If no qubits are free, see if we can still allocate more.
if (!qreg) {
qx_qubit = num_qubits;
num_qubits++;
}
if (qx_qubit >= 0) {
DQCSIM_DEBUG("Placed upstream qubit %d at QX index %d", dqcsim_qubit, qx_qubit);
dqcs2qx.map(dqcsim_qubit, qx_qubit);
} else {
throw std::runtime_error("Upstream plugin requires too many live qubits!");
}
}
}
/**
* Qubit deallocation callback.
*
* Inverse of `allocate()`.
*/
void free(
dqcs::PluginState &state,
dqcs::QubitSet &&qubits
) {
// Loop over the qubits that are to be freed.
while (qubits.size()) {
// The DQCsim upstream qubit index to free.
size_t dqcsim_qubit = qubits.pop().get_index();
// Unmap it in the bimap to do the free.
DQCSIM_DEBUG("Freed upstream qubit %d", dqcsim_qubit);
dqcs2qx.unmap_upstream(dqcsim_qubit);
}
}
/**
* Simulates all pending gates.
*
* When this is called for the first time, it also initializes the quantum
* register.
*/
void simulate_pending() {
// Initialize the qubit state if we haven't already.
if (!qreg) {
DQCSIM_INFO("Creating quantum register of %d qubits...", num_qubits);
try {
qreg = std::make_shared<qx::qu_register>(num_qubits);
} catch(std::bad_alloc& exception) {
DQCSIM_FATAL("Not enough memory for quantum state");
throw std::runtime_error("out of memory");
}
}
// Construct a circuit from the pending gates.
qx::circuit perfect_circuit = qx::circuit(
num_qubits, "circuit_" + std::to_string(circuit_counter++));
for (qx::gate *gate : pending) {
perfect_circuit.add(gate);
}
pending.clear();
// Add error using the depolarizing channel model if required.
qx::circuit *circuit = &perfect_circuit;
if (depolarizing_channel) {
size_t total_errors = 0;
circuit = qx::noisy_dep_ch(&perfect_circuit, error_probability, total_errors);
DQCSIM_INFO("Depolarizing channel model inserted %d errors", total_errors);
}
// Simulate the circuit.
circuit->execute(*qreg);
}
/**
* Gate callback.
*/
dqcs::MeasurementSet gate(
dqcs::PluginState &state,
dqcs::Gate &&gate
) {
// Convert the DQCsim gate to a QX gate and queue it up.
const GateConstructor *gate_constructor = nullptr;
dqcs::QubitSet dqcsim_qubits = dqcs::QubitSet(0);
dqcs::ArbData data = dqcs::ArbData(0);
if (!gatemap.detect(gate, &gate_constructor, &dqcsim_qubits, &data)) {
DQCSIM_DEBUG("Unsupported gate! Here's a dump: %s", gate.dump().c_str());
throw std::runtime_error("unsupported gate");
}
std::vector<size_t> qx_qubits;
while (dqcsim_qubits.size()) {
size_t dqcsim_index = dqcsim_qubits.pop().get_index();
ssize_t qx_index = dqcs2qx.forward_lookup(dqcsim_index);
if (qx_index < 0) {
throw std::runtime_error("failed to resolve DQCsim qubit to QX qubit");
}
qx_qubits.push_back(qx_index);
}
(*gate_constructor)(pending, std::move(qx_qubits), std::move(data));
// Simulate once we receive a measurement, because then we have to return a
// result.
if (gate.has_measures()) {
simulate_pending();
}
// Return the state of the measurement register for any measured qubits.
dqcs::QubitSet measured_qubits = gate.get_measures();
dqcs::MeasurementSet measurements = dqcs::MeasurementSet();
while (measured_qubits.size()) {
dqcs::QubitRef dqcsim_ref = measured_qubits.pop();
size_t dqcsim_index = dqcsim_ref.get_index();
ssize_t qx_index = dqcs2qx.forward_lookup(dqcsim_index);
if (qx_index < 0) {
throw std::runtime_error("failed to resolve DQCsim qubit to QX qubit");
}
dqcs::MeasurementValue value = qreg->get_measurement(qx_index)
? dqcs::MeasurementValue::One : dqcs::MeasurementValue::Zero;
measurements.set(dqcs::Measurement(dqcsim_ref, value));
}
return measurements;
}
/**
* Drop callback.
*
* We use this to flush out any pending operations occurring after the last
* measurement.
*/
void drop(
dqcs::PluginState &state
) {
simulate_pending();
}
/**
* Handles an ArbCmd. Used for both upstream, host, and init arbs alike.
*/
dqcs::ArbData handle_cmd(
dqcs::PluginState &state,
const dqcs::Cmd *cmd
) {
if (cmd->is_iface("qx")) {
if (cmd->is_oper("epsilon")) {
auto json = cmd->get_arb_json<nlohmann::json>();
epsilon = json["epsilon"];
DQCSIM_DEBUG("Set gate detection epsilon to %f", epsilon);
} else if (cmd->is_oper("error")) {
auto json = cmd->get_arb_json<nlohmann::json>();
std::string model = json["model"];
if (model == "none") {
depolarizing_channel = false;
DQCSIM_DEBUG("Disabled error modelling");
} else if (model == "depolarizing_channel") {
depolarizing_channel = true;
error_probability = json["error_probability"];
DQCSIM_DEBUG("Selected depolarizing channel error model with probability %f", error_probability);
} else {
throw std::runtime_error("Unknown error model requested: " + model + "!");
}
} else if (cmd->is_oper("dump_state")) {
DQCSIM_DEBUG("Simulating pending gates due to state dump request");
simulate_pending();
if (!qreg) {
throw std::runtime_error("No state register after simulate_pending(), this is weird!");
} else {
qreg->dump(false);
}
} else {
throw std::runtime_error("Unknown ArbCmd: qx." + cmd->get_oper() + "!");
}
}
return dqcs::ArbData();
}
/**
* Upstream or host ArbCmd callback.
*/
dqcs::ArbData arbcmd(
dqcs::PluginState &state,
dqcs::ArbCmd cmd
) {
return handle_cmd(state, &cmd);
}
};
int main(int argc, char *argv[]) {
QxPlugin qxPlugin;
return dqcs::Plugin::Backend("qx", "JvS", "0.0.5")
.with_initialize(&qxPlugin, &QxPlugin::initialize)
.with_allocate(&qxPlugin, &QxPlugin::allocate)
.with_free(&qxPlugin, &QxPlugin::free)
.with_gate(&qxPlugin, &QxPlugin::gate)
.with_drop(&qxPlugin, &QxPlugin::drop)
.with_host_arb(&qxPlugin, &QxPlugin::arbcmd)
.with_upstream_arb(&qxPlugin, &QxPlugin::arbcmd)
.run(argc, argv);
}
| 15,723 | 5,920 |
// $Id: OccupancyOcTreeBase.hxx 440 2012-11-02 10:41:10Z ahornung $
/**
* OctoMap:
* A probabilistic, flexible, and compact 3D mapping library for robotic systems.
* @author K. M. Wurm, A. Hornung, University of Freiburg, Copyright (C) 2009.
* @see http://octomap.sourceforge.net/
* License: New BSD License
*/
/*
* Copyright (c) 2009-2011, K. M. Wurm, A. Hornung, University of Freiburg
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the University of Freiburg nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <bitset>
namespace octomap {
template <class NODE>
OccupancyOcTreeBase<NODE>::OccupancyOcTreeBase(double resolution)
: OcTreeBaseImpl<NODE,AbstractOccupancyOcTree>(resolution), use_bbx_limit(false), use_change_detection(false)
{
}
template <class NODE>
OccupancyOcTreeBase<NODE>::OccupancyOcTreeBase(double resolution, unsigned int tree_depth, unsigned int tree_max_val)
: OcTreeBaseImpl<NODE,AbstractOccupancyOcTree>(resolution, tree_depth, tree_max_val), use_bbx_limit(false), use_change_detection(false)
{
}
template <class NODE>
OccupancyOcTreeBase<NODE>::~OccupancyOcTreeBase(){
}
template <class NODE>
OccupancyOcTreeBase<NODE>::OccupancyOcTreeBase(const OccupancyOcTreeBase<NODE>& rhs) :
OcTreeBaseImpl<NODE,AbstractOccupancyOcTree>(rhs), use_bbx_limit(rhs.use_bbx_limit),
bbx_min(rhs.bbx_min), bbx_max(rhs.bbx_max),
bbx_min_key(rhs.bbx_min_key), bbx_max_key(rhs.bbx_max_key),
use_change_detection(rhs.use_change_detection), changed_keys(rhs.changed_keys)
{
this->clamping_thres_min = rhs.clamping_thres_min;
this->clamping_thres_max = rhs.clamping_thres_max;
this->prob_hit_log = rhs.prob_hit_log;
this->prob_miss_log = rhs.prob_miss_log;
this->occ_prob_thres_log = rhs.occ_prob_thres_log;
}
// performs transformation to data and sensor origin first
template <class NODE>
void OccupancyOcTreeBase<NODE>::insertScan(const ScanNode& scan, double maxrange, bool pruning, bool lazy_eval) {
Pointcloud& cloud = *(scan.scan);
pose6d frame_origin = scan.pose;
point3d sensor_origin = frame_origin.inv().transform(scan.pose.trans());
insertScan(cloud, sensor_origin, frame_origin, maxrange, pruning, lazy_eval);
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::insertScan(const Pointcloud& scan, const octomap::point3d& sensor_origin,
double maxrange, bool pruning, bool lazy_eval) {
KeySet free_cells, occupied_cells;
computeUpdate(scan, sensor_origin, free_cells, occupied_cells, maxrange);
// insert data into tree -----------------------
for (KeySet::iterator it = free_cells.begin(); it != free_cells.end(); ++it) {
updateNode(*it, false, lazy_eval);
}
for (KeySet::iterator it = occupied_cells.begin(); it != occupied_cells.end(); ++it) {
updateNode(*it, true, lazy_eval);
}
// TODO: does pruning make sense if we used "lazy_eval"?
if (pruning) this->prune();
}
template <class NODE>
template <class SCAN>
void OccupancyOcTreeBase<NODE>::insertScan_templ(const SCAN& scan, const octomap::point3d& sensor_origin,
double maxrange, bool pruning, bool lazy_eval) {
KeySet free_cells, occupied_cells;
computeUpdate(scan, sensor_origin, free_cells, occupied_cells, maxrange);
// insert data into tree -----------------------
for (KeySet::iterator it = free_cells.begin(); it != free_cells.end(); ++it) {
updateNode(*it, false, lazy_eval);
}
for (KeySet::iterator it = occupied_cells.begin(); it != occupied_cells.end(); ++it) {
updateNode(*it, true, lazy_eval);
}
// TODO: does pruning make sense if we used "lazy_eval"?
if (pruning) this->prune();
}
// performs transformation to data and sensor origin first
template <class NODE>
void OccupancyOcTreeBase<NODE>::insertScan(const Pointcloud& pc, const point3d& sensor_origin, const pose6d& frame_origin,
double maxrange, bool pruning, bool lazy_eval) {
Pointcloud transformed_scan (pc);
transformed_scan.transform(frame_origin);
point3d transformed_sensor_origin = frame_origin.transform(sensor_origin);
insertScan(transformed_scan, transformed_sensor_origin, maxrange, pruning, lazy_eval);
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::insertScanNaive(const Pointcloud& pc, const point3d& origin, double maxrange, bool pruning, bool lazy_eval) {
if (pc.size() < 1)
return;
// integrate each single beam
octomap::point3d p;
for (octomap::Pointcloud::const_iterator point_it = pc.begin();
point_it != pc.end(); ++point_it) {
this->insertRay(origin, *point_it, maxrange, lazy_eval);
}
if (pruning)
this->prune();
}
template <class NODE>
inline void OccupancyOcTreeBase<NODE>::computeUpdate_onePoint(const point3d& p, const octomap::point3d& origin,
KeySet& free_cells, KeySet& occupied_cells, double maxrange)
{
if (!use_bbx_limit) {
// -------------- no BBX specified ---------------
if ((maxrange < 0.0) || ((p - origin).norm() <= maxrange) ) { // is not maxrange meas.
// free cells
if (this->computeRayKeys(origin, p, this->keyray)){
free_cells.insert(this->keyray.begin(), this->keyray.end());
}
// occupied endpoint
OcTreeKey key;
if (this->coordToKeyChecked(p, key))
occupied_cells.insert(key);
} // end if NOT maxrange
else { // user set a maxrange and this is reached
point3d direction = (p - origin).normalized ();
point3d new_end = origin + direction * (float) maxrange;
if (this->computeRayKeys(origin, new_end, this->keyray)){
free_cells.insert(this->keyray.begin(), this->keyray.end());
}
} // end if maxrange
}
// --- update limited by user specified BBX -----
else {
// endpoint in bbx and not maxrange?
if ( inBBX(p) && ((maxrange < 0.0) || ((p - origin).norm () <= maxrange) ) ) {
// occupied endpoint
OcTreeKey key;
if (this->coordToKeyChecked(p, key))
occupied_cells.insert(key);
// update freespace, break as soon as bbx limit is reached
if (this->computeRayKeys(origin, p, this->keyray)){
for(KeyRay::reverse_iterator rit=this->keyray.rbegin(); rit != this->keyray.rend(); ++rit) {
if (inBBX(*rit)) {
free_cells.insert(*rit);
}
else break;
}
} // end if compute ray
} // end if in BBX and not maxrange
} // end bbx case
}
template <class NODE>
template <class POINTCLOUD>
void OccupancyOcTreeBase<NODE>::computeUpdate_templ( const POINTCLOUD& scan, const octomap::point3d& origin, KeySet& free_cells, KeySet& occupied_cells, double maxrange)
{
const size_t N = scan.size();
const std::vector<float> &xs = scan.getPointsBufferRef_x();
const std::vector<float> &ys = scan.getPointsBufferRef_y();
const std::vector<float> &zs = scan.getPointsBufferRef_z();
for (size_t i=0;i<N;i++)
{
const point3d p(xs[i],ys[i],zs[i]);
computeUpdate_onePoint(p,origin,free_cells,occupied_cells,maxrange);
}
// prefer occupied cells over free ones (and make sets disjunct)
for(KeySet::iterator it = free_cells.begin(), end=free_cells.end(); it!= end; )
{
if (occupied_cells.find(*it) != occupied_cells.end())
it = free_cells.erase(it);
else ++it;
}
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::computeUpdate(const Pointcloud& scan, const octomap::point3d& origin,
KeySet& free_cells, KeySet& occupied_cells,
double maxrange)
{
//#pragma omp parallel private (local_key_ray, point_it)
for (Pointcloud::const_iterator point_it = scan.begin(); point_it != scan.end(); ++point_it) {
const point3d& p = *point_it;
computeUpdate_onePoint(p,origin,free_cells,occupied_cells,maxrange);
}
// prefer occupied cells over free ones (and make sets disjunct)
for(KeySet::iterator it = free_cells.begin(), end=free_cells.end(); it!= end; ){
if (occupied_cells.find(*it) != occupied_cells.end()){
it = free_cells.erase(it);
} else {
++it;
}
}
}
template <class NODE>
NODE* OccupancyOcTreeBase<NODE>::updateNode(const OcTreeKey& key, float log_odds_update, bool lazy_eval) {
return updateNodeRecurs(this->root, false, key, 0, log_odds_update, lazy_eval);
}
template <class NODE>
NODE* OccupancyOcTreeBase<NODE>::updateNode(const point3d& value, float log_odds_update, bool lazy_eval) {
OcTreeKey key;
if (!this->coordToKeyChecked(value, key))
return NULL;
return updateNode(key, log_odds_update, lazy_eval);
}
template <class NODE>
NODE* OccupancyOcTreeBase<NODE>::updateNode(double x, double y, double z, float log_odds_update, bool lazy_eval) {
OcTreeKey key;
if (!this->coordToKeyChecked(x, y, z, key))
return NULL;
return updateNode(key, log_odds_update, lazy_eval);
}
template <class NODE>
NODE* OccupancyOcTreeBase<NODE>::updateNode(const OcTreeKey& key, bool occupied, bool lazy_eval) {
NODE* leaf = this->search(key);
// no change: node already at threshold
if (leaf && (this->isNodeAtThreshold(leaf)) && (this->isNodeOccupied(leaf) == occupied)) {
return leaf;
}
if (occupied) return updateNodeRecurs(this->root, false, key, 0, this->prob_hit_log, lazy_eval);
else return updateNodeRecurs(this->root, false, key, 0, this->prob_miss_log, lazy_eval);
}
template <class NODE>
NODE* OccupancyOcTreeBase<NODE>::updateNode(const point3d& value, bool occupied, bool lazy_eval) {
OcTreeKey key;
if (!this->coordToKeyChecked(value, key))
return NULL;
return updateNode(key, occupied, lazy_eval);
}
template <class NODE>
NODE* OccupancyOcTreeBase<NODE>::updateNode(double x, double y, double z, bool occupied, bool lazy_eval) {
OcTreeKey key;
if (!this->coordToKeyChecked(x, y, z, key))
return NULL;
return updateNode(key, occupied, lazy_eval);
}
template <class NODE>
NODE* OccupancyOcTreeBase<NODE>::updateNodeRecurs(NODE* node, bool node_just_created, const OcTreeKey& key,
unsigned int depth, const float& log_odds_update, bool lazy_eval) {
unsigned int pos = computeChildIdx(key, this->tree_depth-1-depth);
bool created_node = false;
// follow down to last level
if (depth < this->tree_depth) {
if (!node->childExists(pos)) {
// child does not exist, but maybe it's a pruned node?
if ((!node->hasChildren()) && !node_just_created && (node != this->root)) {
// current node does not have children AND it is not a new node
// AND its not the root node
// -> expand pruned node
node->expandNode();
this->tree_size+=8;
this->size_changed = true;
}
else {
// not a pruned node, create requested child
node->createChild(pos);
this->tree_size++;
this->size_changed = true;
created_node = true;
}
}
if (lazy_eval)
return updateNodeRecurs(node->getChild(pos), created_node, key, depth+1, log_odds_update, lazy_eval);
else {
NODE* retval = updateNodeRecurs(node->getChild(pos), created_node, key, depth+1, log_odds_update, lazy_eval);
// set own probability according to prob of children
node->updateOccupancyChildren();
return retval;
}
}
// at last level, update node, end of recursion
else {
if (use_change_detection) {
bool occBefore = this->isNodeOccupied(node);
updateNodeLogOdds(node, log_odds_update);
if (node_just_created){ // new node
changed_keys.insert(std::pair<OcTreeKey,bool>(key, true));
} else if (occBefore != this->isNodeOccupied(node)) { // occupancy changed, track it
KeyBoolMap::iterator it = changed_keys.find(key);
if (it == changed_keys.end())
changed_keys.insert(std::pair<OcTreeKey,bool>(key, false));
else if (it->second == false)
changed_keys.erase(it);
}
}
else {
updateNodeLogOdds(node, log_odds_update);
}
return node;
}
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::calcNumThresholdedNodes(unsigned int& num_thresholded,
unsigned int& num_other) const {
num_thresholded = 0;
num_other = 0;
// TODO: The recursive call could be completely replaced with the new iterators
calcNumThresholdedNodesRecurs(this->root, num_thresholded, num_other);
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::calcNumThresholdedNodesRecurs (NODE* node,
unsigned int& num_thresholded,
unsigned int& num_other) const {
assert(node != NULL);
for (unsigned int i=0; i<8; i++) {
if (node->childExists(i)) {
NODE* child_node = node->getChild(i);
if (this->isNodeAtThreshold(child_node))
num_thresholded++;
else
num_other++;
calcNumThresholdedNodesRecurs(child_node, num_thresholded, num_other);
} // end if child
} // end for children
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::updateInnerOccupancy(){
this->updateInnerOccupancyRecurs(this->root, 0);
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::updateInnerOccupancyRecurs(NODE* node, unsigned int depth){
// only recurse and update for inner nodes:
if (node->hasChildren()){
// return early for last level:
if (depth < this->tree_depth){
for (unsigned int i=0; i<8; i++) {
if (node->childExists(i)) {
updateInnerOccupancyRecurs(node->getChild(i), depth+1);
}
}
}
node->updateOccupancyChildren();
}
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::toMaxLikelihood() {
// convert bottom up
for (unsigned int depth=this->tree_depth; depth>0; depth--) {
toMaxLikelihoodRecurs(this->root, 0, depth);
}
// convert root
nodeToMaxLikelihood(this->root);
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::toMaxLikelihoodRecurs(NODE* node, unsigned int depth,
unsigned int max_depth) {
if (depth < max_depth) {
for (unsigned int i=0; i<8; i++) {
if (node->childExists(i)) {
toMaxLikelihoodRecurs(node->getChild(i), depth+1, max_depth);
}
}
}
else { // max level reached
nodeToMaxLikelihood(node);
}
}
template <class NODE>
bool OccupancyOcTreeBase<NODE>::castRay(const point3d& origin, const point3d& directionP, point3d& end,
bool ignoreUnknown, double maxRange) const {
/// ---------- see OcTreeBase::computeRayKeys -----------
// Initialization phase -------------------------------------------------------
OcTreeKey current_key;
if ( !OcTreeBaseImpl<NODE,AbstractOccupancyOcTree>::coordToKeyChecked(origin, current_key) ) {
OCTOMAP_WARNING_STR("Coordinates out of bounds during ray casting");
return false;
}
NODE* startingNode = this->search(current_key);
if (startingNode){
if (this->isNodeOccupied(startingNode)){
// Occupied node found at origin
// (need to convert from key, since origin does not need to be a voxel center)
end = this->keyToCoord(current_key);
return true;
}
} else if(!ignoreUnknown){
OCTOMAP_ERROR_STR("Origin node at " << origin << " for raycasting not found, does the node exist?");
end = this->keyToCoord(current_key);
return false;
}
point3d direction = directionP.normalized();
bool max_range_set = (maxRange > 0.0);
int step[3];
double tMax[3];
double tDelta[3];
for(unsigned int i=0; i < 3; ++i) {
// compute step direction
if (direction(i) > 0.0) step[i] = 1;
else if (direction(i) < 0.0) step[i] = -1;
else step[i] = 0;
// compute tMax, tDelta
if (step[i] != 0) {
// corner point of voxel (in direction of ray)
double voxelBorder = this->keyToCoord(current_key[i]);
voxelBorder += double(step[i] * this->resolution * 0.5);
tMax[i] = ( voxelBorder - origin(i) ) / direction(i);
tDelta[i] = this->resolution / fabs( direction(i) );
}
else {
tMax[i] = std::numeric_limits<double>::max();
tDelta[i] = std::numeric_limits<double>::max();
}
}
if (step[0] == 0 && step[1] == 0 && step[2] == 0){
OCTOMAP_ERROR("Raycasting in direction (0,0,0) is not possible!");
return false;
}
// for speedup:
double maxrange_sq = maxRange *maxRange;
// Incremental phase ---------------------------------------------------------
bool done = false;
while (!done) {
unsigned int dim;
// find minimum tMax:
if (tMax[0] < tMax[1]){
if (tMax[0] < tMax[2]) dim = 0;
else dim = 2;
}
else {
if (tMax[1] < tMax[2]) dim = 1;
else dim = 2;
}
// check for overflow:
if ((step[dim] < 0 && current_key[dim] == 0)
|| (step[dim] > 0 && current_key[dim] == 2* this->tree_max_val-1))
{
OCTOMAP_WARNING("Coordinate hit bounds in dim %d, aborting raycast\n", dim);
// return border point nevertheless:
end = this->keyToCoord(current_key);
return false;
}
// advance in direction "dim"
current_key[dim] += step[dim];
tMax[dim] += tDelta[dim];
// generate world coords from key
end = this->keyToCoord(current_key);
// check for maxrange:
if (max_range_set){
double dist_from_origin_sq(0.0);
for (unsigned int j = 0; j < 3; j++) {
dist_from_origin_sq += ((end(j) - origin(j)) * (end(j) - origin(j)));
}
if (dist_from_origin_sq > maxrange_sq)
return false;
}
NODE* currentNode = this->search(current_key);
if (currentNode){
if (this->isNodeOccupied(currentNode)) {
done = true;
break;
}
// otherwise: node is free and valid, raycasting continues
} else if (!ignoreUnknown){ // no node found, this usually means we are in "unknown" areas
OCTOMAP_WARNING_STR("Search failed in OcTree::castRay() => an unknown area was hit in the map: " << end);
return false;
}
} // end while
return true;
}
template <class NODE> inline bool
OccupancyOcTreeBase<NODE>::integrateMissOnRay(const point3d& origin, const point3d& end, bool lazy_eval) {
if (!this->computeRayKeys(origin, end, this->keyray)) {
return false;
}
for(KeyRay::iterator it=this->keyray.begin(); it != this->keyray.end(); ++it) {
updateNode(*it, false, lazy_eval); // insert freespace measurement
}
return true;
}
template <class NODE> bool
OccupancyOcTreeBase<NODE>::insertRay(const point3d& origin, const point3d& end, double maxrange, bool lazy_eval)
{
// cut ray at maxrange
if ((maxrange > 0) && ((end - origin).norm () > maxrange))
{
point3d direction = (end - origin).normalized ();
point3d new_end = origin + direction * (float) maxrange;
return integrateMissOnRay(origin, new_end,lazy_eval);
}
// insert complete ray
else
{
if (!integrateMissOnRay(origin, end,lazy_eval))
return false;
updateNode(end, true, lazy_eval); // insert hit cell
return true;
}
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::getOccupied(point3d_list& node_centers, unsigned int max_depth) const {
if (max_depth == 0)
max_depth = this->tree_depth;
for(typename OccupancyOcTreeBase<NODE>::leaf_iterator it = this->begin(max_depth),
end=this->end(); it!= end; ++it)
{
if(this->isNodeOccupied(*it))
node_centers.push_back(it.getCoordinate());
}
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::getOccupied(std::list<OcTreeVolume>& occupied_nodes, unsigned int max_depth) const{
if (max_depth == 0)
max_depth = this->tree_depth;
for(typename OccupancyOcTreeBase<NODE>::leaf_iterator it = this->begin(max_depth),
end=this->end(); it!= end; ++it)
{
if(this->isNodeOccupied(*it))
occupied_nodes.push_back(OcTreeVolume(it.getCoordinate(), it.getSize()));
}
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::getOccupied(std::list<OcTreeVolume>& binary_nodes,
std::list<OcTreeVolume>& delta_nodes,
unsigned int max_depth) const{
if (max_depth == 0)
max_depth = this->tree_depth;
for(typename OccupancyOcTreeBase<NODE>::leaf_iterator it = this->begin(max_depth),
end=this->end(); it!= end; ++it)
{
if(this->isNodeOccupied(*it)){
if (it->getLogOdds() >= this->clamping_thres_max)
binary_nodes.push_back(OcTreeVolume(it.getCoordinate(), it.getSize()));
else
delta_nodes.push_back(OcTreeVolume(it.getCoordinate(), it.getSize()));
}
}
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::getFreespace(std::list<OcTreeVolume>& free_nodes, unsigned int max_depth) const{
if (max_depth == 0)
max_depth = this->tree_depth;
for(typename OccupancyOcTreeBase<NODE>::leaf_iterator it = this->begin(max_depth),
end=this->end(); it!= end; ++it)
{
if(!this->isNodeOccupied(*it))
free_nodes.push_back(OcTreeVolume(it.getCoordinate(), it.getSize()));
}
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::getFreespace(std::list<OcTreeVolume>& binary_nodes,
std::list<OcTreeVolume>& delta_nodes,
unsigned int max_depth) const{
if (max_depth == 0)
max_depth = this->tree_depth;
for(typename OccupancyOcTreeBase<NODE>::leaf_iterator it = this->begin(max_depth),
end=this->end(); it!= end; ++it)
{
if(!this->isNodeOccupied(*it)){
if (it->getLogOdds() <= this->clamping_thres_min)
binary_nodes.push_back(OcTreeVolume(it.getCoordinate(), it.getSize()));
else
delta_nodes.push_back(OcTreeVolume(it.getCoordinate(), it.getSize()));
}
}
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::setBBXMin (point3d& min) {
bbx_min = min;
if (!this->genKey(bbx_min, bbx_min_key)) {
OCTOMAP_ERROR("ERROR while generating bbx min key.\n");
}
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::setBBXMax (point3d& max) {
bbx_max = max;
if (!this->genKey(bbx_max, bbx_max_key)) {
OCTOMAP_ERROR("ERROR while generating bbx max key.\n");
}
}
template <class NODE>
bool OccupancyOcTreeBase<NODE>::inBBX(const point3d& p) const {
return ((p.x() >= bbx_min.x()) && (p.y() >= bbx_min.y()) && (p.z() >= bbx_min.z()) &&
(p.x() <= bbx_max.x()) && (p.y() <= bbx_max.y()) && (p.z() <= bbx_max.z()) );
}
template <class NODE>
bool OccupancyOcTreeBase<NODE>::inBBX(const OcTreeKey& key) const {
return ((key[0] >= bbx_min_key[0]) && (key[1] >= bbx_min_key[1]) && (key[2] >= bbx_min_key[2]) &&
(key[0] <= bbx_max_key[0]) && (key[1] <= bbx_max_key[1]) && (key[2] <= bbx_max_key[2]) );
}
template <class NODE>
point3d OccupancyOcTreeBase<NODE>::getBBXBounds () const {
octomap::point3d obj_bounds = (bbx_max - bbx_min);
obj_bounds /= 2.;
return obj_bounds;
}
template <class NODE>
point3d OccupancyOcTreeBase<NODE>::getBBXCenter () const {
octomap::point3d obj_bounds = (bbx_max - bbx_min);
obj_bounds /= 2.;
return bbx_min + obj_bounds;
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::getOccupiedLeafsBBX(point3d_list& node_centers, point3d min, point3d max) const {
OcTreeKey root_key, min_key, max_key;
root_key[0] = root_key[1] = root_key[2] = this->tree_max_val;
if (!this->genKey(min, min_key)) return;
if (!this->genKey(max, max_key)) return;
getOccupiedLeafsBBXRecurs(node_centers, this->tree_depth, this->root, 0, root_key, min_key, max_key);
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::getOccupiedLeafsBBXRecurs( point3d_list& node_centers, unsigned int max_depth,
NODE* node, unsigned int depth, const OcTreeKey& parent_key,
const OcTreeKey& min, const OcTreeKey& max) const {
if (depth == max_depth) { // max level reached
if (this->isNodeOccupied(node)) {
node_centers.push_back(this->keyToCoords(parent_key, depth));
}
}
if (!node->hasChildren()) return;
unsigned short int center_offset_key = this->tree_max_val >> (depth + 1);
OcTreeKey child_key;
for (unsigned int i=0; i<8; ++i) {
if (node->childExists(i)) {
computeChildKey(i, center_offset_key, parent_key, child_key);
// overlap of query bbx and child bbx?
if (!(
( min[0] > (child_key[0] + center_offset_key)) ||
( max[0] < (child_key[0] - center_offset_key)) ||
( min[1] > (child_key[1] + center_offset_key)) ||
( max[1] < (child_key[1] - center_offset_key)) ||
( min[2] > (child_key[2] + center_offset_key)) ||
( max[2] < (child_key[2] - center_offset_key))
)) {
getOccupiedLeafsBBXRecurs(node_centers, max_depth, node->getChild(i), depth+1, child_key, min, max);
}
}
}
}
// -- I/O -----------------------------------------
template <class NODE>
std::istream& OccupancyOcTreeBase<NODE>::readBinaryData(std::istream &s){
this->readBinaryNode(s, this->root);
this->size_changed = true;
this->tree_size = OcTreeBaseImpl<NODE,AbstractOccupancyOcTree>::calcNumNodes(); // compute number of nodes
return s;
}
template <class NODE>
std::ostream& OccupancyOcTreeBase<NODE>::writeBinaryData(std::ostream &s) const{
OCTOMAP_DEBUG("Writing %u nodes to output stream...", static_cast<unsigned int>(this->size()));
this->writeBinaryNode(s, this->root);
return s;
}
template <class NODE>
std::istream& OccupancyOcTreeBase<NODE>::readBinaryNode(std::istream &s, NODE* node) const {
char child1to4_char;
char child5to8_char;
s.read((char*)&child1to4_char, sizeof(char));
s.read((char*)&child5to8_char, sizeof(char));
std::bitset<8> child1to4 ((unsigned long long) child1to4_char);
std::bitset<8> child5to8 ((unsigned long long) child5to8_char);
// std::cout << "read: "
// << child1to4.to_string<char,std::char_traits<char>,std::allocator<char> >() << " "
// << child5to8.to_string<char,std::char_traits<char>,std::allocator<char> >() << std::endl;
// inner nodes default to occupied
node->setLogOdds(this->clamping_thres_max);
for (unsigned int i=0; i<4; i++) {
if ((child1to4[i*2] == 1) && (child1to4[i*2+1] == 0)) {
// child is free leaf
node->createChild(i);
node->getChild(i)->setLogOdds(this->clamping_thres_min);
}
else if ((child1to4[i*2] == 0) && (child1to4[i*2+1] == 1)) {
// child is occupied leaf
node->createChild(i);
node->getChild(i)->setLogOdds(this->clamping_thres_max);
}
else if ((child1to4[i*2] == 1) && (child1to4[i*2+1] == 1)) {
// child has children
node->createChild(i);
node->getChild(i)->setLogOdds(-200.); // child is unkown, we leave it uninitialized
}
}
for (unsigned int i=0; i<4; i++) {
if ((child5to8[i*2] == 1) && (child5to8[i*2+1] == 0)) {
// child is free leaf
node->createChild(i+4);
node->getChild(i+4)->setLogOdds(this->clamping_thres_min);
}
else if ((child5to8[i*2] == 0) && (child5to8[i*2+1] == 1)) {
// child is occupied leaf
node->createChild(i+4);
node->getChild(i+4)->setLogOdds(this->clamping_thres_max);
}
else if ((child5to8[i*2] == 1) && (child5to8[i*2+1] == 1)) {
// child has children
node->createChild(i+4);
node->getChild(i+4)->setLogOdds(-200.); // set occupancy when all children have been read
}
// child is unkown, we leave it uninitialized
}
// read children's children and set the label
for (unsigned int i=0; i<8; i++) {
if (node->childExists(i)) {
NODE* child = node->getChild(i);
if (fabs(child->getLogOdds() + 200.)<1e-3) {
readBinaryNode(s, child);
child->setLogOdds(child->getMaxChildLogOdds());
}
} // end if child exists
} // end for children
return s;
}
template <class NODE>
std::ostream& OccupancyOcTreeBase<NODE>::writeBinaryNode(std::ostream &s, const NODE* node) const{
// 2 bits for each children, 8 children per node -> 16 bits
std::bitset<8> child1to4;
std::bitset<8> child5to8;
// 10 : child is free node
// 01 : child is occupied node
// 00 : child is unkown node
// 11 : child has children
// speedup: only set bits to 1, rest is init with 0 anyway,
// can be one logic expression per bit
for (unsigned int i=0; i<4; i++) {
if (node->childExists(i)) {
const NODE* child = node->getChild(i);
if (child->hasChildren()) { child1to4[i*2] = 1; child1to4[i*2+1] = 1; }
else if (this->isNodeOccupied(child)) { child1to4[i*2] = 0; child1to4[i*2+1] = 1; }
else { child1to4[i*2] = 1; child1to4[i*2+1] = 0; }
}
else {
child1to4[i*2] = 0; child1to4[i*2+1] = 0;
}
}
for (unsigned int i=0; i<4; i++) {
if (node->childExists(i+4)) {
const NODE* child = node->getChild(i+4);
if (child->hasChildren()) { child5to8[i*2] = 1; child5to8[i*2+1] = 1; }
else if (this->isNodeOccupied(child)) { child5to8[i*2] = 0; child5to8[i*2+1] = 1; }
else { child5to8[i*2] = 1; child5to8[i*2+1] = 0; }
}
else {
child5to8[i*2] = 0; child5to8[i*2+1] = 0;
}
}
// std::cout << "wrote: "
// << child1to4.to_string<char,std::char_traits<char>,std::allocator<char> >() << " "
// << child5to8.to_string<char,std::char_traits<char>,std::allocator<char> >() << std::endl;
char child1to4_char = (char) child1to4.to_ulong();
char child5to8_char = (char) child5to8.to_ulong();
s.write((char*)&child1to4_char, sizeof(char));
s.write((char*)&child5to8_char, sizeof(char));
// write children's children
for (unsigned int i=0; i<8; i++) {
if (node->childExists(i)) {
const NODE* child = node->getChild(i);
if (child->hasChildren()) {
writeBinaryNode(s, child);
}
}
}
return s;
}
//-- Occupancy queries on nodes:
template <class NODE>
void OccupancyOcTreeBase<NODE>::updateNodeLogOdds(NODE* occupancyNode, const float& update) const {
occupancyNode->addValue(update);
if (occupancyNode->getLogOdds() < this->clamping_thres_min) {
occupancyNode->setLogOdds(this->clamping_thres_min);
return;
}
if (occupancyNode->getLogOdds() > this->clamping_thres_max) {
occupancyNode->setLogOdds(this->clamping_thres_max);
}
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::integrateHit(NODE* occupancyNode) const {
updateNodeLogOdds(occupancyNode, this->prob_hit_log);
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::integrateMiss(NODE* occupancyNode) const {
updateNodeLogOdds(occupancyNode, this->prob_miss_log);
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::nodeToMaxLikelihood(NODE* occupancyNode) const{
if (this->isNodeOccupied(occupancyNode))
occupancyNode->setLogOdds(this->clamping_thres_max);
else
occupancyNode->setLogOdds(this->clamping_thres_min);
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::nodeToMaxLikelihood(NODE& occupancyNode) const{
if (this->isNodeOccupied(occupancyNode))
occupancyNode.setLogOdds(this->clamping_thres_max);
else
occupancyNode.setLogOdds(this->clamping_thres_min);
}
} // namespace
| 34,351 | 12,030 |
/**
* Copyright (C) 2021 FISCO BCOS.
* SPDX-License-Identifier: Apache-2.0
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @brief perf for bcos-crypto
* @file perf_demo.cpp
* @date 2021.04.07
* @author yujiechen
*/
#include "../encrypt/AESCrypto.h"
#include "../encrypt/SM4Crypto.h"
#include "../hash/Keccak256.h"
#include "../hash/SM3.h"
#include "../hash/Sha3.h"
#include "../signature/ed25519/Ed25519Crypto.h"
#include "../signature/secp256k1/Secp256k1Crypto.h"
#include "../signature/sm2/SM2Crypto.h"
#include <bcos-framework/libutilities/Common.h>
using namespace bcos;
using namespace bcos::crypto;
const std::string HASH_CMD = "hash";
const std::string SIGN_CMD = "sign";
const std::string ENCRYPT_CMD = "enc";
void Usage(std::string const& _appName)
{
std::cout << _appName << " [" << HASH_CMD << "/" << SIGN_CMD << "/" << ENCRYPT_CMD << "] count"
<< std::endl;
}
double getTPS(int64_t _endT, int64_t _startT, size_t _count)
{
return (1000.0 * (double)_count) / (double)(_endT - _startT);
}
void hashPerf(
Hash::Ptr _hash, std::string const& _hashName, std::string const& _inputData, size_t _count)
{
std::cout << std::endl;
std::cout << "----------- " << _hashName << " perf start -----------" << std::endl;
auto startT = utcTime();
for (size_t i = 0; i < _count; i++)
{
_hash->hash(bytesConstRef((byte const*)_inputData.c_str(), _inputData.size()));
}
std::cout << "input data size: " << (double)_inputData.size() / 1000.0
<< "KB, loops: " << _count << ", timeCost: " << utcTime() - startT << std::endl;
std::cout << "TPS of " << _hashName << ": "
<< getTPS(utcTime(), startT, _count) * (double)_inputData.size() / 1000.0 << " KB/s"
<< std::endl;
std::cout << "----------- " << _hashName << " perf end -----------" << std::endl;
std::cout << std::endl;
}
void hashPerf(size_t _count)
{
std::string inputData = "abcdwer234q4@#2424wdf";
std::string deltaData = inputData;
for (int i = 0; i < 50; i++)
{
inputData += deltaData;
}
// sha3 perf
Hash::Ptr hashImpl = std::make_shared<class Sha3>();
hashPerf(hashImpl, "SHA3", inputData, _count);
// keccak256 perf
hashImpl = std::make_shared<Keccak256>();
hashPerf(hashImpl, "Keccak256", inputData, _count);
// sm3 perf
hashImpl = std::make_shared<SM3>();
hashPerf(hashImpl, "SM3", inputData, _count);
}
void signaturePerf(SignatureCrypto::Ptr _signatureImpl, HashType const& _msgHash,
std::string const& _signatureName, size_t _count)
{
std::cout << std::endl;
std::cout << "----------- " << _signatureName << " perf test start -----------" << std::endl;
auto keyPair = _signatureImpl->generateKeyPair();
// sign
std::shared_ptr<bytes> signedData;
auto startT = utcTime();
for (size_t i = 0; i < _count; i++)
{
signedData = _signatureImpl->sign(keyPair, _msgHash, false);
}
std::cout << "TPS of " << _signatureName << " sign:" << getTPS(utcTime(), startT, _count)
<< std::endl;
// verify
startT = utcTime();
for (size_t i = 0; i < _count; i++)
{
assert(_signatureImpl->verify(keyPair->publicKey(), _msgHash, ref(*signedData)));
}
std::cout << "TPS of " << _signatureName << " verify:" << getTPS(utcTime(), startT, _count)
<< std::endl;
// recover
signedData = _signatureImpl->sign(keyPair, _msgHash, true);
startT = utcTime();
for (size_t i = 0; i < _count; i++)
{
_signatureImpl->recover(_msgHash, ref(*signedData));
}
std::cout << "TPS of " << _signatureName << " recover:" << getTPS(utcTime(), startT, _count)
<< std::endl;
std::cout << "----------- " << _signatureName << " perf test end -----------" << std::endl;
std::cout << std::endl;
}
void signaturePerf(size_t _count)
{
std::string inputData = "signature perf test";
auto msgHash = keccak256Hash(bytesConstRef((byte const*)inputData.c_str(), inputData.size()));
// secp256k1 perf
SignatureCrypto::Ptr signatureImpl = std::make_shared<Secp256k1Crypto>();
signaturePerf(signatureImpl, msgHash, "secp256k1", _count);
// sm2 perf
signatureImpl = std::make_shared<SM2Crypto>();
signaturePerf(signatureImpl, msgHash, "SM2", _count);
// ed25519 perf
signatureImpl = std::make_shared<Ed25519Crypto>();
signaturePerf(signatureImpl, msgHash, "Ed25519", _count);
}
void encryptPerf(SymmetricEncryption::Ptr _encryptor, std::string const& _inputData,
const std::string& _encryptorName, size_t _count)
{
std::cout << std::endl;
std::cout << "----------- " << _encryptorName << " perf test start -----------" << std::endl;
std::string key = "abcdefgwerelkewrwerw";
// encrypt
bytesPointer encryptedData;
auto startT = utcTime();
for (size_t i = 0; i < _count; i++)
{
encryptedData = _encryptor->symmetricEncrypt((const unsigned char*)_inputData.c_str(),
_inputData.size(), (const unsigned char*)key.c_str(), key.size());
}
std::cout << "PlainData size:" << (double)_inputData.size() / 1000.0 << " KB, loops: " << _count
<< ", timeCost: " << utcTime() - startT << " ms" << std::endl;
std::cout << "TPS of " << _encryptorName << " encrypt:"
<< (getTPS(utcTime(), startT, _count) * (double)(_inputData.size())) / 1000.0
<< "KB/s" << std::endl;
std::cout << std::endl;
// decrypt
startT = utcTime();
bytesPointer decryptedData;
for (size_t i = 0; i < _count; i++)
{
decryptedData = _encryptor->symmetricDecrypt((const unsigned char*)encryptedData->data(),
encryptedData->size(), (const unsigned char*)key.c_str(), key.size());
}
std::cout << "CiperData size:" << (double)encryptedData->size() / 1000.0
<< " KB, loops: " << _count << ", timeCost:" << utcTime() - startT << " ms"
<< std::endl;
std::cout << "TPS of " << _encryptorName << " decrypt:"
<< (getTPS(utcTime(), startT, _count) * (double)_inputData.size()) / 1000.0 << "KB/s"
<< std::endl;
bytes plainBytes(_inputData.begin(), _inputData.end());
assert(plainBytes == *decryptedData);
std::cout << "----------- " << _encryptorName << " perf test end -----------" << std::endl;
std::cout << std::endl;
}
void encryptPerf(size_t _count)
{
std::string inputData = "w3rwerk2-304swlerkjewlrjoiur4kslfjsd,fmnsdlfjlwerlwerjw;erwe;rewrew";
std::string deltaData = inputData;
for (int i = 0; i < 100; i++)
{
inputData += deltaData;
}
// AES
SymmetricEncryption::Ptr encryptor = std::make_shared<AESCrypto>();
encryptPerf(encryptor, inputData, "AES", _count);
// SM4
encryptor = std::make_shared<SM4Crypto>();
encryptPerf(encryptor, inputData, "SM4", _count);
}
int main(int argc, char* argv[])
{
if (argc < 3)
{
Usage(argv[0]);
return -1;
}
auto cmd = argv[1];
size_t count = atoi(argv[2]);
if (HASH_CMD == cmd)
{
hashPerf(count);
}
else if (SIGN_CMD == cmd)
{
signaturePerf(count);
}
else if (ENCRYPT_CMD == cmd)
{
encryptPerf(count);
}
else
{
std::cout << "Invalid subcommand \"" << cmd << "\"" << std::endl;
Usage(argv[0]);
}
return 0;
}
| 7,943 | 2,886 |
#include <bits/stdc++.h>
using namespace std;
int main()
{
int T;
cin >> T;
for(int i = 1; i <= T; i++) {
int r1, r2, c1, c2;
cin >> r1 >> c1 >> r2 >> c2;
if((r1 & 1) == (r2 & 1)) {
if((c1 & 1) != (c2 & 1)) {
printf("Case %d: impossible\n", i);
continue;
}
}
else {
if((c1 & 1) == (c2 & 1)) {
printf("Case %d: impossible\n", i);
continue;
}
}
printf("Case %d: ", i);
if(abs(r2 - r1) == abs(c2 - c1))
printf("1\n");
else
printf("2\n");
}
return 0;
}
| 683 | 256 |
// Copyright 2019 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// 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 "tink/subtle/aes_gcm_hkdf_streaming.h"
#include <sstream>
#include <string>
#include <utility>
#include "gtest/gtest.h"
#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "tink/config/tink_fips.h"
#include "tink/output_stream.h"
#include "tink/subtle/common_enums.h"
#include "tink/subtle/random.h"
#include "tink/subtle/streaming_aead_test_util.h"
#include "tink/subtle/test_util.h"
#include "tink/util/istream_input_stream.h"
#include "tink/util/ostream_output_stream.h"
#include "tink/util/status.h"
#include "tink/util/statusor.h"
#include "tink/util/test_matchers.h"
namespace crypto {
namespace tink {
namespace subtle {
namespace {
using ::crypto::tink::test::IsOk;
using ::crypto::tink::test::StatusIs;
TEST(AesGcmHkdfStreamingTest, testBasic) {
if (IsFipsModeEnabled()) {
GTEST_SKIP() << "Not supported in FIPS-only mode";
}
for (HashType hkdf_hash : {SHA1, SHA256, SHA512}) {
for (int ikm_size : {16, 32}) {
for (int derived_key_size = 16;
derived_key_size <= ikm_size;
derived_key_size += 16) {
for (int ct_segment_size : {80, 128, 200}) {
for (int ciphertext_offset : {0, 10, 16}) {
SCOPED_TRACE(absl::StrCat(
"hkdf_hash = ", EnumToString(hkdf_hash),
", ikm_size = ", ikm_size,
", derived_key_size = ", derived_key_size,
", ciphertext_segment_size = ", ct_segment_size,
", ciphertext_offset = ", ciphertext_offset));
// Create AesGcmHkdfStreaming.
AesGcmHkdfStreaming::Params params;
params.ikm = Random::GetRandomKeyBytes(ikm_size);
params.hkdf_hash = hkdf_hash;
params.derived_key_size = derived_key_size;
params.ciphertext_segment_size = ct_segment_size;
params.ciphertext_offset = ciphertext_offset;
auto result = AesGcmHkdfStreaming::New(std::move(params));
EXPECT_TRUE(result.ok()) << result.status();
auto streaming_aead = std::move(result.ValueOrDie());
// Try to get an encrypting stream to a "null" ct_destination.
std::string associated_data = "some associated data";
auto failed_result = streaming_aead->NewEncryptingStream(
nullptr, associated_data);
EXPECT_FALSE(failed_result.ok());
EXPECT_EQ(absl::StatusCode::kInvalidArgument,
failed_result.status().code());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "non-null",
std::string(failed_result.status().message()));
for (int pt_size : {0, 16, 100, 1000, 10000}) {
SCOPED_TRACE(absl::StrCat(" pt_size = ", pt_size));
std::string pt = Random::GetRandomBytes(pt_size);
EXPECT_THAT(
EncryptThenDecrypt(streaming_aead.get(), streaming_aead.get(),
pt, associated_data, ciphertext_offset),
IsOk());
}
}
}
}
}
}
}
TEST(AesGcmHkdfStreamingTest, testIkmSmallerThanDerivedKey) {
if (IsFipsModeEnabled()) {
GTEST_SKIP() << "Not supported in FIPS-only mode";
}
AesGcmHkdfStreaming::Params params;
int ikm_size = 16;
params.ikm = Random::GetRandomKeyBytes(ikm_size);
params.derived_key_size = 17;
params.ciphertext_segment_size = 100;
params.ciphertext_offset = 10;
params.hkdf_hash = SHA256;
auto result = AesGcmHkdfStreaming::New(std::move(params));
EXPECT_FALSE(result.ok());
EXPECT_EQ(absl::StatusCode::kInvalidArgument, result.status().code());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "ikm too small",
std::string(result.status().message()));
}
TEST(AesGcmHkdfStreamingTest, testIkmSize) {
if (IsFipsModeEnabled()) {
GTEST_SKIP() << "Not supported in FIPS-only mode";
}
for (int ikm_size : {5, 10, 15}) {
AesGcmHkdfStreaming::Params params;
params.ikm = Random::GetRandomKeyBytes(ikm_size);
params.derived_key_size = 17;
params.ciphertext_segment_size = 100;
params.ciphertext_offset = 0;
params.hkdf_hash = SHA256;
auto result = AesGcmHkdfStreaming::New(std::move(params));
EXPECT_FALSE(result.ok());
EXPECT_EQ(absl::StatusCode::kInvalidArgument, result.status().code());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "ikm too small",
std::string(result.status().message()));
}
}
TEST(AesGcmHkdfStreamingTest, testWrongHkdfHash) {
if (IsFipsModeEnabled()) {
GTEST_SKIP() << "Not supported in FIPS-only mode";
}
AesGcmHkdfStreaming::Params params;
int ikm_size = 16;
params.ikm = Random::GetRandomKeyBytes(ikm_size);
params.derived_key_size = 16;
params.ciphertext_segment_size = 100;
params.ciphertext_offset = 10;
params.hkdf_hash = SHA384;
auto result = AesGcmHkdfStreaming::New(std::move(params));
EXPECT_FALSE(result.ok());
EXPECT_EQ(absl::StatusCode::kInvalidArgument, result.status().code());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "unsupported hkdf_hash",
std::string(result.status().message()));
}
TEST(AesGcmHkdfStreamingTest, testWrongDerivedKeySize) {
if (IsFipsModeEnabled()) {
GTEST_SKIP() << "Not supported in FIPS-only mode";
}
AesGcmHkdfStreaming::Params params;
int ikm_size = 20;
params.ikm = Random::GetRandomKeyBytes(ikm_size);
params.derived_key_size = 20;
params.ciphertext_segment_size = 100;
params.ciphertext_offset = 10;
params.hkdf_hash = SHA256;
auto result = AesGcmHkdfStreaming::New(std::move(params));
EXPECT_FALSE(result.ok());
EXPECT_EQ(absl::StatusCode::kInvalidArgument, result.status().code());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "must be 16 or 32",
std::string(result.status().message()));
}
TEST(AesGcmHkdfStreamingTest, testWrongCiphertextOffset) {
if (IsFipsModeEnabled()) {
GTEST_SKIP() << "Not supported in FIPS-only mode";
}
AesGcmHkdfStreaming::Params params;
int ikm_size = 32;
params.ikm = Random::GetRandomKeyBytes(ikm_size);
params.derived_key_size = 32;
params.ciphertext_segment_size = 100;
params.ciphertext_offset = -5;
params.hkdf_hash = SHA256;
auto result = AesGcmHkdfStreaming::New(std::move(params));
EXPECT_FALSE(result.ok());
EXPECT_EQ(absl::StatusCode::kInvalidArgument, result.status().code());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "must be non-negative",
std::string(result.status().message()));
}
TEST(AesGcmHkdfStreamingTest, testWrongCiphertextSegmentSize) {
if (IsFipsModeEnabled()) {
GTEST_SKIP() << "Not supported in FIPS-only mode";
}
AesGcmHkdfStreaming::Params params;
int ikm_size = 32;
params.ikm = Random::GetRandomKeyBytes(ikm_size);
params.derived_key_size = 32;
params.ciphertext_segment_size = 64;
params.ciphertext_offset = 40;
params.hkdf_hash = SHA256;
auto result = AesGcmHkdfStreaming::New(std::move(params));
EXPECT_FALSE(result.ok());
EXPECT_EQ(absl::StatusCode::kInvalidArgument, result.status().code());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "ciphertext_segment_size too small",
std::string(result.status().message()));
}
// FIPS only mode tests
TEST(AesGcmHkdfStreamingTest, TestFipsOnly) {
if (!IsFipsModeEnabled()) {
GTEST_SKIP() << "Only supported in FIPS-only mode";
}
AesGcmHkdfStreaming::Params params;
int ikm_size = 32;
params.ikm = Random::GetRandomKeyBytes(ikm_size);
params.derived_key_size = 32;
params.ciphertext_segment_size = 64;
params.ciphertext_offset = 40;
params.hkdf_hash = SHA256;
EXPECT_THAT(AesGcmHkdfStreaming::New(std::move(params)).status(),
StatusIs(absl::StatusCode::kInternal));
}
} // namespace
} // namespace subtle
} // namespace tink
} // namespace crypto
| 8,583 | 3,137 |
#include <BlackBox/Renderer/Quad.hpp>
#include <BlackBox/Renderer/IGeometry.hpp>
#include <BlackBox/Renderer/OpenGL/Debug.hpp>
Quad::Quad()
{
float verts[] = {
// positions // texCoords
-1.0f, 1.0f, 0.0f, 1.0f,
-1.0f, -1.0f, 0.0f, 0.0f,
1.0f, -1.0f, 1.0f, 0.0f,
-1.0f, 1.0f, 0.0f, 1.0f,
1.0f, -1.0f, 1.0f, 0.0f,
1.0f, 1.0f, 1.0f, 1.0f
};
glGenVertexArrays(1, &id);
glBindVertexArray(id);
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(verts), &verts, GL_STATIC_DRAW);
// 3. Устанавливаем указатели на вершинные атрибуты
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), 0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)(2 * sizeof(float)));
debuger::vertex_array_label(id, "Quad");
glBindVertexArray(0);
}
Quad::~Quad()
{
glDeleteBuffers(1, &VBO);
}
void Quad::draw() {
glCheck(glBindVertexArray(id));
glCheck(glDrawArrays(GL_TRIANGLES, 0, 6));
glCheck(glBindVertexArray(0));
}
bool Quad::init()
{
return true;
} | 1,187 | 571 |
#include "error_code.h"
#include "tapplication.h"
#include <iostream>
using namespace std;
int main()
{
int ret = 0;
TApplication app;
return app.Run();
} | 168 | 61 |
/*!
* Copyright (c) 2015 by Contributors
* \file ctc_loss.cc
* \brief
* \author Sebastian Bodenstein
*/
#include "./ctc_loss-inl.h"
#include "./ctc_include/detail/cpu_ctc.h"
namespace mshadow {
template <typename DType>
ctcStatus_t compute_ctc_cost(const Tensor<cpu, 3, DType> activations,
DType *costs, DType *grads, int *labels,
int *label_lengths, int *input_lengths,
void *workspace, int train) {
int minibatch = static_cast<int>(activations.size(1));
int alphabet_size = static_cast<int>(activations.size(2));
int blank_label = 0;
CpuCTC<DType> ctc(alphabet_size, minibatch, workspace, blank_label);
if (train)
return ctc.cost_and_grad(activations.dptr_, grads, costs, labels,
label_lengths, input_lengths);
else
return ctc.score_forward(activations.dptr_, costs, labels, label_lengths,
input_lengths);
}
} // namespace mshadow
namespace mxnet {
namespace op {
template <>
Operator *CreateOp<cpu>(CTCLossParam param, int dtype) {
return new CTCLossOp<cpu>(param);
}
// DO_BIND_DISPATCH comes from operator_common.h
Operator *CTCLossProp::CreateOperatorEx(Context ctx,
std::vector<TShape> *in_shape,
std::vector<int> *in_type) const {
std::vector<TShape> out_shape, aux_shape;
std::vector<int> out_type, aux_type;
CHECK(InferType(in_type, &out_type, &aux_type));
CHECK(InferShape(in_shape, &out_shape, &aux_shape));
DO_BIND_DISPATCH(CreateOp, param_, (*in_type)[0]);
}
DMLC_REGISTER_PARAMETER(CTCLossParam);
MXNET_REGISTER_OP_PROPERTY(_contrib_CTCLoss, CTCLossProp)
.describe(R"code(Connectionist Temporal Classification Loss.
The shapes of the inputs and outputs:
- **data**: *(sequence_length, batch_size, alphabet_size + 1)*
- **label**: *(batch_size, label_sequence_length)*
- **out**: *(batch_size)*.
``label`` is a tensor of integers between 1 and *alphabet_size*. If a
sequence of labels is shorter than *label_sequence_length*, use the special
padding character 0 at the end of the sequence to conform it to the correct
length. For example, if *label_sequence_length* = 4, and one has two sequences
of labels [2, 1] and [3, 2, 2], the resulting ```label``` tensor should be
padded to be::
[[2, 1, 0, 0], [3, 2, 2, 0]]
The ``data`` tensor consists of sequences of activation vectors. The layer
applies a softmax to each vector, which then becomes a vector of probabilities
over the alphabet. Note that the 0th element of this vector is reserved for the
special blank character.
See *Connectionist Temporal Classification: Labelling Unsegmented
Sequence Data with Recurrent Neural Networks*, A. Graves *et al*. for more
information.
)code" ADD_FILELINE)
.add_argument("data", "NDArray-or-Symbol", "Input data to the ctc_loss op.")
.add_argument("label", "NDArray-or-Symbol",
"Ground-truth labels for the loss.")
.add_arguments(CTCLossParam::__FIELDS__());
NNVM_REGISTER_OP(_contrib_CTCLoss).add_alias("_contrib_ctc_loss");
} // namespace op
} // namespace mxnet
| 3,199 | 1,062 |
// Copyright (C) 2018 ETH Zurich
// Copyright (C) 2018 UT-Battelle, LLC
// All rights reserved.
//
// See LICENSE for terms of usage.
// See CITATION.md for citation guidelines, if DCA++ is used for scientific publications.
//
// Author: Peter Staar (taa@zurich.ibm.com)
//
// This file provides the particle number domain.
#ifndef DCA_PHYS_DOMAINS_QUANTUM_PARTICLE_NUMBER_DOMAIN_HPP
#define DCA_PHYS_DOMAINS_QUANTUM_PARTICLE_NUMBER_DOMAIN_HPP
#include <vector>
namespace dca {
namespace phys {
namespace domains {
// dca::phys::domains::
template <typename band_dmn_t, typename cluster_t, typename e_spin_t>
class particle_number_domain {
public:
typedef int element_type;
static int& get_size() {
static int size = band_dmn_t::dmn_size() * cluster_t::dmn_size() * e_spin_t::dmn_size() + 1;
return size;
}
static std::vector<int>& get_elements() {
static std::vector<int>& v = initialize_elements();
return v;
}
private:
static std::vector<int>& initialize_elements();
};
template <typename band_dmn_t, typename cluster_t, typename e_spin_t>
std::vector<int>& particle_number_domain<band_dmn_t, cluster_t, e_spin_t>::initialize_elements() {
static std::vector<int> v(get_size());
for (int i = 0; i < get_size(); i++)
v[i] = i;
return v;
}
} // domains
} // phys
} // dca
#endif // DCA_PHYS_DOMAINS_QUANTUM_PARTICLE_NUMBER_DOMAIN_HPP
| 1,388 | 535 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome_frame/simple_resource_loader.h"
#include <atlbase.h>
#include <algorithm>
#include "base/base_paths.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/i18n/rtl.h"
#include "base/memory/singleton.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "base/win/i18n.h"
#include "base/win/windows_version.h"
#include "chrome_frame/policy_settings.h"
#include "ui/base/resource/data_pack.h"
namespace {
const wchar_t kLocalesDirName[] = L"Locales";
bool IsInvalidTagCharacter(wchar_t tag_character) {
return !(L'-' == tag_character ||
IsAsciiDigit(tag_character) ||
IsAsciiAlpha(tag_character));
}
// A helper function object that performs a lower-case ASCII comparison between
// two strings.
class CompareInsensitiveASCII
: public std::unary_function<const std::wstring&, bool> {
public:
explicit CompareInsensitiveASCII(const std::wstring& value)
: value_lowered_(WideToASCII(value)) {
StringToLowerASCII(&value_lowered_);
}
bool operator()(const std::wstring& comparand) {
return LowerCaseEqualsASCII(comparand, value_lowered_.c_str());
}
private:
std::string value_lowered_;
};
// Returns true if the value was added.
bool PushBackIfAbsent(
const std::wstring& value,
std::vector<std::wstring>* collection) {
if (collection->end() ==
std::find_if(collection->begin(), collection->end(),
CompareInsensitiveASCII(value))) {
collection->push_back(value);
return true;
}
return false;
}
// Returns true if the collection is modified.
bool PushBackWithFallbackIfAbsent(
const std::wstring& language,
std::vector<std::wstring>* collection) {
bool modified = false;
if (!language.empty()) {
// Try adding the language itself.
modified = PushBackIfAbsent(language, collection);
// Now try adding its fallback, if it has one.
std::wstring::size_type dash_pos = language.find(L'-');
if (0 < dash_pos && language.size() - 1 > dash_pos)
modified |= PushBackIfAbsent(language.substr(0, dash_pos), collection);
}
return modified;
}
} // namespace
SimpleResourceLoader::SimpleResourceLoader()
: data_pack_(NULL),
locale_dll_handle_(NULL) {
// Find and load the resource DLL.
std::vector<std::wstring> language_tags;
// First, try the locale dictated by policy and its fallback.
PushBackWithFallbackIfAbsent(
PolicySettings::GetInstance()->ApplicationLocale(),
&language_tags);
// Next, try the thread, process, user, system languages.
GetPreferredLanguages(&language_tags);
// Finally, fall-back on "en-US" (which may already be present in the vector,
// but that's okay since we'll exit with success when the first is tried).
language_tags.push_back(L"en-US");
FilePath locales_path;
DetermineLocalesDirectory(&locales_path);
if (!LoadLocalePack(language_tags, locales_path, &locale_dll_handle_,
&data_pack_, &language_)) {
NOTREACHED() << "Failed loading any resource dll (even \"en-US\").";
}
}
SimpleResourceLoader::~SimpleResourceLoader() {
delete data_pack_;
}
// static
SimpleResourceLoader* SimpleResourceLoader::GetInstance() {
return Singleton<SimpleResourceLoader>::get();
}
// static
void SimpleResourceLoader::GetPreferredLanguages(
std::vector<std::wstring>* language_tags) {
DCHECK(language_tags);
// The full set of preferred languages and their fallbacks are given priority.
std::vector<std::wstring> languages;
if (base::win::i18n::GetThreadPreferredUILanguageList(&languages)) {
for (std::vector<std::wstring>::const_iterator scan = languages.begin(),
end = languages.end(); scan != end; ++scan) {
PushBackIfAbsent(*scan, language_tags);
}
}
// Use the base i18n routines (i.e., ICU) as a last, best hope for something
// meaningful for the user.
PushBackWithFallbackIfAbsent(ASCIIToWide(base::i18n::GetConfiguredLocale()),
language_tags);
}
// static
void SimpleResourceLoader::DetermineLocalesDirectory(FilePath* locales_path) {
DCHECK(locales_path);
FilePath module_path;
PathService::Get(base::DIR_MODULE, &module_path);
*locales_path = module_path.Append(kLocalesDirName);
// We may be residing in the "locales" directory's parent, or we might be
// in a sibling directory. Move up one and look for Locales again in the
// latter case.
if (!file_util::DirectoryExists(*locales_path)) {
*locales_path = module_path.DirName();
*locales_path = locales_path->Append(kLocalesDirName);
}
// Don't make a second check to see if the dir is in the parent. We'll notice
// and log that in LoadLocaleDll when we actually try loading DLLs.
}
// static
bool SimpleResourceLoader::IsValidLanguageTag(
const std::wstring& language_tag) {
// "[a-zA-Z]+(-[a-zA-Z0-9]+)*" is a simplification, but better than nothing.
// Rather than pick up the weight of a regex processor, just search for a
// character that isn't in the above set. This will at least weed out
// attempts at "../../EvilBinary".
return language_tag.end() == std::find_if(language_tag.begin(),
language_tag.end(),
&IsInvalidTagCharacter);
}
// static
bool SimpleResourceLoader::LoadLocalePack(
const std::vector<std::wstring>& language_tags,
const FilePath& locales_path,
HMODULE* dll_handle,
ui::DataPack** data_pack,
std::wstring* language) {
DCHECK(language);
// The dll should only have resources, not executable code.
const DWORD load_flags =
(base::win::GetVersion() >= base::win::VERSION_VISTA ?
LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE | LOAD_LIBRARY_AS_IMAGE_RESOURCE :
DONT_RESOLVE_DLL_REFERENCES);
const std::wstring dll_suffix(L".dll");
const std::wstring pack_suffix(L".pak");
bool found_pack = false;
for (std::vector<std::wstring>::const_iterator scan = language_tags.begin(),
end = language_tags.end();
scan != end;
++scan) {
if (!IsValidLanguageTag(*scan)) {
LOG(WARNING) << "Invalid language tag supplied while locating resources:"
" \"" << *scan << "\"";
continue;
}
// Attempt to load both the resource pack and the dll. We return success
// only we load both.
FilePath resource_pack_path = locales_path.Append(*scan + pack_suffix);
FilePath dll_path = locales_path.Append(*scan + dll_suffix);
if (file_util::PathExists(resource_pack_path) &&
file_util::PathExists(dll_path)) {
scoped_ptr<ui::DataPack> cur_data_pack(
new ui::DataPack(ui::SCALE_FACTOR_100P));
if (!cur_data_pack->LoadFromPath(resource_pack_path))
continue;
HMODULE locale_dll_handle = LoadLibraryEx(dll_path.value().c_str(), NULL,
load_flags);
if (locale_dll_handle) {
*dll_handle = locale_dll_handle;
*language = dll_path.BaseName().RemoveExtension().value();
*data_pack = cur_data_pack.release();
found_pack = true;
break;
} else {
*data_pack = NULL;
}
}
}
DCHECK(found_pack || file_util::DirectoryExists(locales_path))
<< "Could not locate locales DLL directory.";
return found_pack;
}
std::wstring SimpleResourceLoader::GetLocalizedResource(int message_id) {
if (!data_pack_) {
DLOG(ERROR) << "locale resources are not loaded";
return std::wstring();
}
DCHECK(IS_INTRESOURCE(message_id));
base::StringPiece data;
if (!data_pack_->GetStringPiece(message_id, &data)) {
DLOG(ERROR) << "Unable to find string for resource id:" << message_id;
return std::wstring();
}
// Data pack encodes strings as either UTF8 or UTF16.
string16 msg;
if (data_pack_->GetTextEncodingType() == ui::DataPack::UTF16) {
msg = string16(reinterpret_cast<const char16*>(data.data()),
data.length() / 2);
} else if (data_pack_->GetTextEncodingType() == ui::DataPack::UTF8) {
msg = UTF8ToUTF16(data);
}
return msg;
}
// static
std::wstring SimpleResourceLoader::GetLanguage() {
return SimpleResourceLoader::GetInstance()->language_;
}
// static
std::wstring SimpleResourceLoader::Get(int message_id) {
SimpleResourceLoader* loader = SimpleResourceLoader::GetInstance();
return loader->GetLocalizedResource(message_id);
}
HMODULE SimpleResourceLoader::GetResourceModuleHandle() {
return locale_dll_handle_;
}
| 8,763 | 2,821 |
/*
Copyright (C) 2016 Quaternion Risk Management Ltd
All rights reserved.
This file is part of ORE, a free-software/open-source library
for transparent pricing and risk analysis - http://opensourcerisk.org
ORE is free software: you can redistribute it and/or modify it
under the terms of the Modified BSD License. You should have received a
copy of the license along with this program.
The license is also available online at <http://opensourcerisk.org>
This program is distributed on the basis that it will form a useful
contribution to risk analytics and model standardisation, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/
#include <ored/portfolio/builders/cms.hpp>
#include <ored/utilities/log.hpp>
#include <ored/utilities/parsers.hpp>
#include <boost/make_shared.hpp>
using namespace QuantLib;
namespace ore {
namespace data {
namespace {
Real parseCcyReversion(const std::map<string, string>& p, const std::string& ccy) {
// either we have a ccy specific reversion or require a ccy independent reversion parameter
if (p.find("MeanReversion_" + ccy) != p.end())
return parseReal(p.at("MeanReversion_" + ccy));
else
return parseReal(p.at("MeanReversion"));
}
} // namespace
GFunctionFactory::YieldCurveModel ycmFromString(const string& s) {
if (s == "Standard")
return GFunctionFactory::Standard;
else if (s == "ExactYield")
return GFunctionFactory::ExactYield;
else if (s == "ParallelShifts")
return GFunctionFactory::ParallelShifts;
else if (s == "NonParallelShifts")
return GFunctionFactory::NonParallelShifts;
else
QL_FAIL("unknown string for YieldCurveModel");
}
boost::shared_ptr<FloatingRateCouponPricer> AnalyticHaganCmsCouponPricerBuilder::engineImpl(const Currency& ccy) {
const string& ccyCode = ccy.code();
Real rev = parseCcyReversion(engineParameters_, ccyCode);
string ycmstr = engineParameter("YieldCurveModel");
GFunctionFactory::YieldCurveModel ycm = ycmFromString(ycmstr);
Handle<Quote> revQuote(boost::shared_ptr<Quote>(new SimpleQuote(rev)));
Handle<SwaptionVolatilityStructure> vol = market_->swaptionVol(ccyCode, configuration(MarketContext::pricing));
boost::shared_ptr<FloatingRateCouponPricer> pricer = boost::make_shared<AnalyticHaganPricer>(vol, ycm, revQuote);
// Return the cached pricer
return pricer;
}
boost::shared_ptr<FloatingRateCouponPricer> NumericalHaganCmsCouponPricerBuilder::engineImpl(const Currency& ccy) {
const string& ccyCode = ccy.code();
Real rev = parseCcyReversion(engineParameters_, ccyCode);
string ycmstr = engineParameter("YieldCurveModel");
GFunctionFactory::YieldCurveModel ycm = ycmFromString(ycmstr);
Rate llim = parseReal(engineParameter("LowerLimit"));
Rate ulim = parseReal(engineParameter("UpperLimit"));
Real prec = parseReal(engineParameter("Precision"));
Handle<Quote> revQuote(boost::shared_ptr<Quote>(new SimpleQuote(rev)));
Handle<SwaptionVolatilityStructure> vol = market_->swaptionVol(ccyCode, configuration(MarketContext::pricing));
boost::shared_ptr<FloatingRateCouponPricer> pricer =
boost::make_shared<NumericHaganPricer>(vol, ycm, revQuote, llim, ulim, prec);
// Return the cached pricer
return pricer;
}
boost::shared_ptr<FloatingRateCouponPricer> LinearTSRCmsCouponPricerBuilder::engineImpl(const Currency& ccy) {
const string& ccyCode = ccy.code();
Real rev = parseCcyReversion(engineParameters_, ccyCode);
string policy = engineParameter("Policy");
Handle<Quote> revQuote(boost::shared_ptr<Quote>(new SimpleQuote(rev)));
Handle<SwaptionVolatilityStructure> vol = market_->swaptionVol(ccyCode, configuration(MarketContext::pricing));
Handle<YieldTermStructure> yts = market_->discountCurve(ccyCode, configuration(MarketContext::pricing));
string lowerBoundStr =
(vol->volatilityType() == ShiftedLognormal) ? "LowerRateBoundLogNormal" : "LowerRateBoundNormal";
string upperBoundStr =
(vol->volatilityType() == ShiftedLognormal) ? "UpperRateBoundLogNormal" : "UpperRateBoundNormal";
LinearTsrPricer::Settings settings;
if (policy == "RateBound") {
Real lower = parseReal(engineParameter(lowerBoundStr));
Real upper = parseReal(engineParameter(upperBoundStr));
settings.withRateBound(lower, upper);
} else if (policy == "VegaRatio") {
Real lower = parseReal(engineParameter(lowerBoundStr));
Real upper = parseReal(engineParameter(upperBoundStr));
Real vega = parseReal(engineParameter("VegaRatio"));
settings.withVegaRatio(vega, lower, upper);
} else if (policy == "PriceThreshold") {
Real lower = parseReal(engineParameter(lowerBoundStr));
Real upper = parseReal(engineParameter(upperBoundStr));
Real threshold = parseReal(engineParameter("PriceThreshold"));
settings.withPriceThreshold(threshold, lower, upper);
} else if (policy == "BsStdDev") {
Real lower = parseReal(engineParameter(lowerBoundStr));
Real upper = parseReal(engineParameter(upperBoundStr));
Real stddevs = parseReal(engineParameter("BSStdDevs"));
settings.withPriceThreshold(stddevs, lower, upper);
} else
QL_FAIL("unknown string for policy parameter");
boost::shared_ptr<FloatingRateCouponPricer> pricer =
boost::make_shared<LinearTsrPricer>(vol, revQuote, yts, settings);
// Return the cached pricer
return pricer;
}
} // namespace data
} // namespace ore
| 5,655 | 1,754 |
#pragma once
#include <voxel/structure.hpp>
#include <mutex>
#include <thread>
namespace VOXEL_NAMESPACE
{
template<class T = Sector>
class AsyncStructure : public Structure<T>
{
protected:
bool isRunning;
std::mutex updateMutex;
std::thread updateThread;
inline void update(const Registry& registry)
{
std::chrono::steady_clock::time_point lastTime;
while (isRunning)
{
updateMutex.lock();
const auto time = std::chrono::high_resolution_clock::now();
const auto deltaTime = std::chrono::duration_cast<
std::chrono::duration<time_t>>(time - lastTime);
lastTime = time;
Structure<T>::update(registry, deltaTime.count());
if (sleepDelay > 0)
std::this_thread::sleep_for(std::chrono::milliseconds(sleepDelay));
updateMutex.unlock();
}
}
public:
int sleepDelay;
AsyncStructure(const size3_t& size,
const structure_pos_t& position,
const std::shared_ptr<T> sector,
const int _sleepDelay = 1) :
Structure<T>(size, position, sector),
sleepDelay(_sleepDelay),
isRunning(false),
updateMutex(),
updateThread()
{}
virtual ~AsyncStructure()
{
if (isRunning)
stopUpdate();
}
AsyncStructure(const AsyncStructure<T>&) = delete;
inline void lockUpdate() noexcept
{
updateMutex.lock();
}
inline void unlockUpdate() noexcept
{
updateMutex.unlock();
}
inline void startUpdate(const Registry& registry)
{
if (isRunning)
throw std::runtime_error("Thread is already running");
isRunning = true;
updateThread = std::thread(&AsyncStructure<T>::update, this, registry);
}
inline void stopUpdate()
{
if (!isRunning)
throw std::runtime_error("Thread is not running");
isRunning = false;
if (updateThread.get_id() != std::this_thread::get_id() &&
updateThread.joinable())
updateThread.join();
}
};
}
| 1,863 | 751 |
//
// Created by yangtao on 20-5-29.
//
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
using namespace std;
struct Node {
Node *left, *right;
int no;
};
map<int, Node*> s;
int n,m;
Node *h , *p;
int main() {
cin >> n;
h = new Node;
Node *t = new Node;
t->no = 1;
h->right = t;
t->left = h;
s[1] = t;
for(int i = 2; i <= n; i++) {
Node *node = new Node;
node->no = i;
int k, q;
scanf("%d%d", &k, &q);
p = h->right;
s[i] = node;
p = s[k];
if(q == 0) {
node->left = p->left;
node->right = p;
p->left->right = node;
p->left = node;
} else {
node->right = p->right;
node->left = p;
p->right = node;
if(node->right)
node->right->left = node;
}
}
cin >> m;
for(int i = 0 ; i < m; i++) {
int q;
scanf("%d", &q);
if(s.find(q) == s.end()) continue;
p = s[q];
s.erase(q);
p->left->right = p->right;
if(p->right) {
p->right->left = p->left;
}
}
p = h->right;
while(p) {
printf("%d ", p->no);
p = p->right;
}
return 0;
} | 1,316 | 509 |
/**
* Copyright (c) 2018 Cornell University.
*
* Author: Ted Yin <tederminant@gmail.com>
*
* 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 <cstdio>
#include <string>
#include <functional>
#include <thread>
#include <signal.h>
/* disable SHA256 checksum */
#define SALTICIDAE_NOCHECKSUM
#include "salticidae/msg.h"
#include "salticidae/event.h"
#include "salticidae/network.h"
#include "salticidae/stream.h"
using salticidae::NetAddr;
using salticidae::DataStream;
using salticidae::MsgNetwork;
using salticidae::htole;
using salticidae::letoh;
using salticidae::bytearray_t;
using salticidae::TimerEvent;
using salticidae::ThreadCall;
using std::placeholders::_1;
using std::placeholders::_2;
using opcode_t = uint8_t;
struct MsgBytes {
static const opcode_t opcode = 0xa;
DataStream serialized;
bytearray_t bytes;
MsgBytes(size_t size) {
bytes.resize(size);
serialized << htole((uint32_t)size) << bytes;
}
MsgBytes(DataStream &&s) {
uint32_t len;
s >> len;
len = letoh(len);
auto base = s.get_data_inplace(len);
bytes = bytearray_t(base, base + len);
}
};
const opcode_t MsgBytes::opcode;
using MsgNetworkByteOp = MsgNetwork<opcode_t>;
struct MyNet: public MsgNetworkByteOp {
const std::string name;
TimerEvent ev_period_stat;
ThreadCall tcall;
size_t nrecv;
std::function<void(ThreadCall::Handle &)> trigger;
MyNet(const salticidae::EventContext &ec,
const std::string name,
double stat_timeout = -1):
MsgNetworkByteOp(ec, MsgNetworkByteOp::Config(
ConnPool::Config()
.max_send_buff_size(65536)
).burst_size(1000)),
name(name),
ev_period_stat(ec, [this, stat_timeout](TimerEvent &) {
SALTICIDAE_LOG_INFO("%.2f mps", nrecv / (double)stat_timeout);
fflush(stderr);
nrecv = 0;
ev_period_stat.add(stat_timeout);
}),
tcall(ec),
nrecv(0) {
/* message handler could be a bound method */
reg_handler(salticidae::generic_bind(&MyNet::on_receive_bytes, this, _1, _2));
if (stat_timeout > 0)
ev_period_stat.add(0);
reg_conn_handler([this, ec](const ConnPool::conn_t &conn, bool connected) {
if (connected)
{
if (conn->get_mode() == MyNet::Conn::ACTIVE)
{
printf("[%s] connected, sending bytes.\n", this->name.c_str());
/* send the first message through this connection */
trigger = [this, conn](ThreadCall::Handle &) {
send_msg(MsgBytes(256), salticidae::static_pointer_cast<Conn>(conn));
if (!conn->is_terminated())
tcall.async_call(trigger);
};
tcall.async_call(trigger);
}
else
printf("[%s] passively connected, waiting for bytes.\n", this->name.c_str());
}
else
{
printf("[%s] disconnected, retrying.\n", this->name.c_str());
/* try to reconnect to the same address */
connect(conn->get_addr());
}
return true;
});
}
void on_receive_bytes(MsgBytes &&msg, const conn_t &conn) { nrecv++; }
};
salticidae::EventContext ec;
NetAddr alice_addr("127.0.0.1:1234");
NetAddr bob_addr("127.0.0.1:1235");
void masksigs() {
sigset_t mask;
sigemptyset(&mask);
sigfillset(&mask);
pthread_sigmask(SIG_BLOCK, &mask, NULL);
}
int main() {
salticidae::BoxObj<MyNet> alice = new MyNet(ec, "Alice", 10);
alice->start();
alice->listen(alice_addr);
salticidae::EventContext tec;
MyNet bob(tec, "Bob");
std::thread bob_thread([&]() {
masksigs();
bob.start();
bob.connect(alice_addr);
tec.dispatch();
});
auto shutdown = [&](int) {
bob.tcall.async_call([&](salticidae::ThreadCall::Handle &) {
tec.stop();
});
ec.stop();
bob_thread.join();
};
salticidae::SigEvent ev_sigint(ec, shutdown);
salticidae::SigEvent ev_sigterm(ec, shutdown);
ev_sigint.add(SIGINT);
ev_sigterm.add(SIGTERM);
ec.dispatch();
return 0;
}
| 5,453 | 1,806 |
//=========================================================================
// Copyright (C) 2018 The C++ Component Model(CCM) 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.
//=========================================================================
#include "ccmrt/system/SocketTagger.h"
#include "ccm.io.IFileDescriptor.h"
#include <ccmlogger.h>
using ccm::io::IFileDescriptor;
namespace ccmrt {
namespace system {
CCM_INTERFACE_IMPL_1(SocketTagger, SyncObject, ISocketTagger);
AutoPtr<ISocketTagger> SocketTagger::GetOrSet(
/* [in] */ ISocketTagger* tagger)
{
class _SocketTagger
: public SocketTagger
{
public:
ECode Tag(
/* [in] */ IFileDescriptor* socketDescriptor) override
{
return NOERROR;
}
ECode Untag(
/* [in] */ IFileDescriptor* socketDescriptor) override
{
return NOERROR;
}
};
static AutoPtr<ISocketTagger> sTagger = new _SocketTagger();
if (tagger != nullptr) {
sTagger = tagger;
}
return sTagger;
}
ECode SocketTagger::Tag(
/* [in] */ ISocket* socket)
{
Boolean closed;
if (socket->IsClosed(&closed), !closed) {
AutoPtr<IFileDescriptor> fd;
socket->GetFileDescriptor(&fd);
return Tag(fd);
}
return NOERROR;
}
ECode SocketTagger::Untag(
/* [in] */ ISocket* socket)
{
Boolean closed;
if (socket->IsClosed(&closed), !closed) {
AutoPtr<IFileDescriptor> fd;
socket->GetFileDescriptor(&fd);
return Untag(fd);
}
return NOERROR;
}
ECode SocketTagger::Tag(
/* [in] */ IDatagramSocket* socket)
{
Boolean closed;
if (socket->IsClosed(&closed), !closed) {
AutoPtr<IFileDescriptor> fd;
socket->GetFileDescriptor(&fd);
return Tag(fd);
}
return NOERROR;
}
ECode SocketTagger::Untag(
/* [in] */ IDatagramSocket* socket)
{
Boolean closed;
if (socket->IsClosed(&closed), !closed) {
AutoPtr<IFileDescriptor> fd;
socket->GetFileDescriptor(&fd);
return Untag(fd);
}
return NOERROR;
}
ECode SocketTagger::Set(
/* [in] */ ISocketTagger* tagger)
{
if (tagger == nullptr) {
Logger::E("SocketTagger", "tagger == null");
return ccm::core::E_NULL_POINTER_EXCEPTION;
}
GetOrSet(tagger);
return NOERROR;
}
}
}
| 2,902 | 923 |
#include "coefficients.hpp"
#include "bias.hpp"
#include <cstddef>
enum direction
{
DOWN,
UP,
UNKNOWN
};
std::tuple<uint64_t, std::array<uint32_t, 3>, counters>
coefficient_search(const eval_t<uint64_t, const std::array<uint32_t, 3> &> &eval,
const std::array<bool, 3> &negated,
const std::array<uint32_t, 3> &initial)
{
counters count;
uint64_t bias;
std::array<uint32_t, 3> coefficients = initial;
const auto bias_eval = [&coefficients, &eval](uint64_t bias) -> counters
{
return eval(bias, coefficients);
};
std::array<direction, 3> directions = {UNKNOWN, UNKNOWN, UNKNOWN};
while (true)
{
std::tie(bias, count) = bias_search(bias_eval);
if (count.regions() == 0u)
break;
if (count.regions() > 3u)
break;
std::size_t edit = count.regions() - 1u;
direction dir = (count.last() == counters::NEGATIVE) ? UP : DOWN;
if (negated[edit])
dir = (dir == DOWN) ? UP : DOWN;
if (directions[edit] == UNKNOWN)
{
directions[edit] = dir;
}
else if (directions[edit] != dir)
{
if (++edit > 2u)
break;
}
if (directions[edit] == DOWN)
coefficients[edit]--;
else
coefficients[edit]++; // UP is arbitrary for UNKNOWN case
for (std::size_t i = 0; i < edit; i++)
{
directions[i] = UNKNOWN;
}
}
return std::make_tuple(bias, coefficients, count);
}
| 1,595 | 579 |
#include "Aphelion/Renderer/Renderer.h"
#include <glm/gtc/type_ptr.hpp>
#include "Aphelion/Renderer/RenderCommand.h"
#include "Aphelion/Renderer/Renderer2D.h"
namespace ap {
struct RendererData {
// PerspectiveCamera camera;
glm::mat4 view;
glm::mat4 projection;
};
static RendererData data;
void Renderer::Init() {
RenderCommand::Init();
Renderer2D::Init();
}
void Renderer::Deinit() { Renderer2D::Deinit(); }
void Renderer::OnWindowResize(uint32_t width, uint32_t height) {
RenderCommand::SetViewport(0, 0, width, height);
}
void Renderer::BeginScene(const PerspectiveCamera& camera) {
data.view = camera.GetViewMatrix();
data.projection = camera.GetProjectionMatrix();
}
void Renderer::EndScene() {}
void Renderer::Submit(const ShaderRef& shader,
const VertexArrayRef& vertexArray,
const glm::mat4& transform) {
// shader->Bind();
shader->SetMat4("aTransform", glm::value_ptr(transform));
shader->SetMat4("aVP", glm::value_ptr(data.projection * data.view));
vertexArray->Bind();
RenderCommand::DrawIndexed(vertexArray,
vertexArray->GetIndexBuffer()->GetCount());
}
} // namespace ap | 1,197 | 401 |
/******************************************************************************/
/* Mednafen NEC PC-FX Emulation Module */
/******************************************************************************/
/* mouse.cpp:
** Copyright (C) 2007-2016 Mednafen Team
**
** This program is free software; you can redistribute it and/or
** modify it under the terms of the GNU General Public License
** as published by the Free Software Foundation; either version 2
** of the License, or (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software Foundation, Inc.,
** 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "../pcfx.h"
#include "../input.h"
#include "mouse.h"
namespace MDFN_IEN_PCFX
{
class PCFX_Input_Mouse : public PCFX_Input_Device
{
public:
PCFX_Input_Mouse(int which)
{
dx = 0;
dy = 0;
button = 0;
}
virtual ~PCFX_Input_Mouse() override
{
}
virtual uint32 ReadTransferTime(void) override
{
return (1536);
}
virtual uint32 WriteTransferTime(void) override
{
return (1536);
}
virtual uint32 Read(void) override
{
return FX_SIG_MOUSE << 28 | button << 16 | dx << 8 | dy;
}
virtual void Write(uint32 data) override
{
}
virtual void Power(void) override
{
button = 0;
dx = 0;
dy = 0;
}
virtual void Frame(uint32_t data) override
{
dx = data;
dy = data >> 8;
button = data >> 16 & 3;
}
private:
int8 dx, dy;
// 76543210
// ......RL
uint8 button;
};
PCFX_Input_Device *PCFXINPUT_MakeMouse(int which)
{
return new PCFX_Input_Mouse(which);
}
}
| 1,937 | 704 |
#include "xbt/xcc_z.h"
#include <cstdio>
#include <string.h>
#include <zlib.h>
#include "stream_int.h"
shared_data xcc_z::gunzip(data_ref s)
{
if (s.size() < 18)
return shared_data();
shared_data d(read_int_le(4, s.end() - 4));
z_stream stream;
stream.zalloc = NULL;
stream.zfree = NULL;
stream.opaque = NULL;
stream.next_in = const_cast<unsigned char*>(s.begin()) + 10;
stream.avail_in = s.size() - 18;
stream.next_out = d.data();
stream.avail_out = d.size();
return stream.next_out
&& Z_OK == inflateInit2(&stream, -MAX_WBITS)
&& Z_STREAM_END == inflate(&stream, Z_FINISH)
&& Z_OK == inflateEnd(&stream)
? d
: shared_data();
}
shared_data xcc_z::gzip(data_ref s)
{
unsigned long cb_d = s.size() + (s.size() + 999) / 1000 + 12;
shared_data d(10 + cb_d + 8);
unsigned char* w = d.data();
*w++ = 0x1f;
*w++ = 0x8b;
*w++ = Z_DEFLATED;
*w++ = 0;
*w++ = 0;
*w++ = 0;
*w++ = 0;
*w++ = 0;
*w++ = 0;
*w++ = 3;
{
z_stream stream;
stream.zalloc = NULL;
stream.zfree = NULL;
stream.opaque = NULL;
deflateInit2(&stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, -MAX_WBITS, MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY);
stream.next_in = const_cast<unsigned char*>(s.begin());
stream.avail_in = s.size();
stream.next_out = w;
stream.avail_out = cb_d;
deflate(&stream, Z_FINISH);
deflateEnd(&stream);
w = stream.next_out;
}
w = write_int_le(4, w, crc32(crc32(0, NULL, 0), s.data(), s.size()));
w = write_int_le(4, w, s.size());
return d.substr(0, w - d.data());
}
/*
void xcc_z::gzip_out(data_ref s)
{
gzFile f = gzdopen(fileno(stdout), "wb");
gzwrite(f, s.data(), s.size());
gzflush(f, Z_FINISH);
}
*/
| 1,646 | 823 |
// Created on: 1994-08-26
// Created by: Frederic MAUPAS
// Copyright (c) 1994-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _GeomToStep_MakeAxis2Placement2d_HeaderFile
#define _GeomToStep_MakeAxis2Placement2d_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <GeomToStep_Root.hxx>
class StepGeom_Axis2Placement2d;
class gp_Ax2;
class gp_Ax22d;
//! This class implements the mapping between classes
//! Axis2Placement from Geom and Ax2, Ax22d from gp, and the class
//! Axis2Placement2d from StepGeom which describes an
//! axis2_placement_2d from Prostep.
class GeomToStep_MakeAxis2Placement2d : public GeomToStep_Root
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT GeomToStep_MakeAxis2Placement2d(const gp_Ax2& A);
Standard_EXPORT GeomToStep_MakeAxis2Placement2d(const gp_Ax22d& A);
Standard_EXPORT const Handle(StepGeom_Axis2Placement2d)& Value() const;
protected:
private:
Handle(StepGeom_Axis2Placement2d) theAxis2Placement2d;
};
#endif // _GeomToStep_MakeAxis2Placement2d_HeaderFile
| 1,724 | 635 |
//
// This file is part of the aMule Project.
//
// Copyright (c) 2004-2011 Angel Vidal ( kry@amule.org )
// Copyright (c) 2004-2011 aMule Team ( admin@amule.org / http://www.amule.org )
// Copyright (c) 2003-2011 Barry Dunne (http://www.emule-project.net)
//
// Any parts of this program derived from the xMule, lMule or eMule project,
// or contributed by third-party developers are copyrighted by their
// respective authors.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
//
// Note To Mods //
/*
Please do not change anything here and release it..
There is going to be a new forum created just for the Kademlia side of the client..
If you feel there is an error or a way to improve something, please
post it in the forum first and let us look at it.. If it is a real improvement,
it will be added to the offical client.. Changing something without knowing
what all it does can cause great harm to the network if released in mass form..
Any mod that changes anything within the Kademlia side will not be allowed to advertise
there client on the eMule forum..
*/
#include "Indexed.h"
#include <protocol/Protocols.h>
#include <protocol/ed2k/Constants.h>
#include <protocol/kad/Constants.h>
#include <protocol/kad/Client2Client/UDP.h>
#include <protocol/kad2/Client2Client/UDP.h>
#include <common/Macros.h>
#include <tags/FileTags.h>
#include "../routing/Contact.h"
#include "../net/KademliaUDPListener.h"
#include "../utils/KadUDPKey.h"
#include "../../CFile.h"
#include "../../MemFile.h"
#include "../../Preferences.h"
#include "../../Logger.h"
////////////////////////////////////////
using namespace Kademlia;
////////////////////////////////////////
wxString CIndexed::m_kfilename;
wxString CIndexed::m_sfilename;
wxString CIndexed::m_loadfilename;
CIndexed::CIndexed()
{
m_sfilename = thePrefs::GetConfigDir() + wxT("src_index.dat");
m_kfilename = thePrefs::GetConfigDir() + wxT("key_index.dat");
m_loadfilename = thePrefs::GetConfigDir() + wxT("load_index.dat");
m_lastClean = time(NULL) + (60*30);
m_totalIndexSource = 0;
m_totalIndexKeyword = 0;
m_totalIndexNotes = 0;
m_totalIndexLoad = 0;
ReadFile();
}
void CIndexed::ReadFile()
{
try {
uint32_t totalLoad = 0;
uint32_t totalSource = 0;
uint32_t totalKeyword = 0;
CFile load_file;
if (CPath::FileExists(m_loadfilename) && load_file.Open(m_loadfilename, CFile::read)) {
uint32_t version = load_file.ReadUInt32();
if (version < 2) {
/*time_t savetime =*/ load_file.ReadUInt32(); // Savetime is unused now
uint32_t numLoad = load_file.ReadUInt32();
while (numLoad) {
CUInt128 keyID = load_file.ReadUInt128();
if (AddLoad(keyID, load_file.ReadUInt32())) {
totalLoad++;
}
numLoad--;
}
}
load_file.Close();
}
CFile k_file;
if (CPath::FileExists(m_kfilename) && k_file.Open(m_kfilename, CFile::read)) {
uint32_t version = k_file.ReadUInt32();
if (version < 4) {
time_t savetime = k_file.ReadUInt32();
if (savetime > time(NULL)) {
CUInt128 id = k_file.ReadUInt128();
if (Kademlia::CKademlia::GetPrefs()->GetKadID() == id) {
uint32_t numKeys = k_file.ReadUInt32();
while (numKeys) {
CUInt128 keyID = k_file.ReadUInt128();
uint32_t numSource = k_file.ReadUInt32();
while (numSource) {
CUInt128 sourceID = k_file.ReadUInt128();
uint32_t numName = k_file.ReadUInt32();
while (numName) {
Kademlia::CKeyEntry* toAdd = new Kademlia::CKeyEntry();
toAdd->m_uKeyID = keyID;
toAdd->m_uSourceID = sourceID;
toAdd->m_bSource = false;
toAdd->m_tLifeTime = k_file.ReadUInt32();
if (version >= 3) {
toAdd->ReadPublishTrackingDataFromFile(&k_file);
}
uint32_t tagList = k_file.ReadUInt8();
while (tagList) {
CTag* tag = k_file.ReadTag();
if (tag) {
if (!tag->GetName().Cmp(TAG_FILENAME)) {
if (toAdd->GetCommonFileName().IsEmpty()) {
toAdd->SetFileName(tag->GetStr());
}
delete tag;
} else if (!tag->GetName().Cmp(TAG_FILESIZE)) {
if (tag->IsBsob() && (tag->GetBsobSize() == 8)) {
// We've previously wrongly saved BSOB uint64s to key_index.dat,
// so we'll have to handle those here as well. Too bad ...
toAdd->m_uSize = PeekUInt64(tag->GetBsob());
} else {
toAdd->m_uSize = tag->GetInt();
}
delete tag;
} else if (!tag->GetName().Cmp(TAG_SOURCEIP)) {
toAdd->m_uIP = tag->GetInt();
toAdd->AddTag(tag);
} else if (!tag->GetName().Cmp(TAG_SOURCEPORT)) {
toAdd->m_uTCPport = tag->GetInt();
toAdd->AddTag(tag);
} else if (!tag->GetName().Cmp(TAG_SOURCEUPORT)) {
toAdd->m_uUDPport = tag->GetInt();
toAdd->AddTag(tag);
} else {
toAdd->AddTag(tag);
}
}
tagList--;
}
uint8_t load;
if (AddKeyword(keyID, sourceID, toAdd, load)) {
totalKeyword++;
} else {
delete toAdd;
}
numName--;
}
numSource--;
}
numKeys--;
}
}
}
}
k_file.Close();
}
CFile s_file;
if (CPath::FileExists(m_sfilename) && s_file.Open(m_sfilename, CFile::read)) {
uint32_t version = s_file.ReadUInt32();
if (version < 3) {
time_t savetime = s_file.ReadUInt32();
if (savetime > time(NULL)) {
uint32_t numKeys = s_file.ReadUInt32();
while (numKeys) {
CUInt128 keyID = s_file.ReadUInt128();
uint32_t numSource = s_file.ReadUInt32();
while (numSource) {
CUInt128 sourceID = s_file.ReadUInt128();
uint32_t numName = s_file.ReadUInt32();
while (numName) {
Kademlia::CEntry* toAdd = new Kademlia::CEntry();
toAdd->m_bSource = true;
toAdd->m_tLifeTime = s_file.ReadUInt32();
uint32_t tagList = s_file.ReadUInt8();
while (tagList) {
CTag* tag = s_file.ReadTag();
if (tag) {
if (!tag->GetName().Cmp(TAG_SOURCEIP)) {
toAdd->m_uIP = tag->GetInt();
toAdd->AddTag(tag);
} else if (!tag->GetName().Cmp(TAG_SOURCEPORT)) {
toAdd->m_uTCPport = tag->GetInt();
toAdd->AddTag(tag);
} else if (!tag->GetName().Cmp(TAG_SOURCEUPORT)) {
toAdd->m_uUDPport = tag->GetInt();
toAdd->AddTag(tag);
} else {
toAdd->AddTag(tag);
}
}
tagList--;
}
toAdd->m_uKeyID = keyID;
toAdd->m_uSourceID = sourceID;
uint8_t load;
if (AddSources(keyID, sourceID, toAdd, load)) {
totalSource++;
} else {
delete toAdd;
}
numName--;
}
numSource--;
}
numKeys--;
}
}
}
s_file.Close();
}
m_totalIndexSource = totalSource;
m_totalIndexKeyword = totalKeyword;
m_totalIndexLoad = totalLoad;
AddDebugLogLineN(logKadIndex, CFormat(wxT("Read %u source, %u keyword, and %u load entries")) % totalSource % totalKeyword % totalLoad);
} catch (const CSafeIOException& err) {
AddDebugLogLineC(logKadIndex, wxT("CSafeIOException in CIndexed::readFile: ") + err.what());
} catch (const CInvalidPacket& err) {
AddDebugLogLineC(logKadIndex, wxT("CInvalidPacket Exception in CIndexed::readFile: ") + err.what());
} catch (const wxString& e) {
AddDebugLogLineC(logKadIndex, wxT("Exception in CIndexed::readFile: ") + e);
}
}
CIndexed::~CIndexed()
{
try
{
time_t now = time(NULL);
uint32_t s_total = 0;
uint32_t k_total = 0;
uint32_t l_total = 0;
CFile load_file;
if (load_file.Open(m_loadfilename, CFile::write)) {
load_file.WriteUInt32(1); // version
load_file.WriteUInt32(now);
wxASSERT(m_Load_map.size() < 0xFFFFFFFF);
load_file.WriteUInt32((uint32_t)m_Load_map.size());
for (LoadMap::iterator it = m_Load_map.begin(); it != m_Load_map.end(); ++it ) {
Load* load = it->second;
wxASSERT(load);
if (load) {
load_file.WriteUInt128(load->keyID);
load_file.WriteUInt32(load->time);
l_total++;
delete load;
}
}
load_file.Close();
}
CFile s_file;
if (s_file.Open(m_sfilename, CFile::write)) {
s_file.WriteUInt32(2); // version
s_file.WriteUInt32(now + KADEMLIAREPUBLISHTIMES);
wxASSERT(m_Sources_map.size() < 0xFFFFFFFF);
s_file.WriteUInt32((uint32_t)m_Sources_map.size());
for (SrcHashMap::iterator itSrcHash = m_Sources_map.begin(); itSrcHash != m_Sources_map.end(); ++itSrcHash ) {
SrcHash* currSrcHash = itSrcHash->second;
s_file.WriteUInt128(currSrcHash->keyID);
CKadSourcePtrList& KeyHashSrcMap = currSrcHash->m_Source_map;
wxASSERT(KeyHashSrcMap.size() < 0xFFFFFFFF);
s_file.WriteUInt32((uint32_t)KeyHashSrcMap.size());
for (CKadSourcePtrList::iterator itSource = KeyHashSrcMap.begin(); itSource != KeyHashSrcMap.end(); ++itSource) {
Source* currSource = *itSource;
s_file.WriteUInt128(currSource->sourceID);
CKadEntryPtrList& SrcEntryList = currSource->entryList;
wxASSERT(SrcEntryList.size() < 0xFFFFFFFF);
s_file.WriteUInt32((uint32_t)SrcEntryList.size());
for (CKadEntryPtrList::iterator itEntry = SrcEntryList.begin(); itEntry != SrcEntryList.end(); ++itEntry) {
Kademlia::CEntry* currName = *itEntry;
s_file.WriteUInt32(currName->m_tLifeTime);
currName->WriteTagList(&s_file);
delete currName;
s_total++;
}
delete currSource;
}
delete currSrcHash;
}
s_file.Close();
}
CFile k_file;
if (k_file.Open(m_kfilename, CFile::write)) {
k_file.WriteUInt32(3); // version
k_file.WriteUInt32(now + KADEMLIAREPUBLISHTIMEK);
k_file.WriteUInt128(Kademlia::CKademlia::GetPrefs()->GetKadID());
wxASSERT(m_Keyword_map.size() < 0xFFFFFFFF);
k_file.WriteUInt32((uint32_t)m_Keyword_map.size());
for (KeyHashMap::iterator itKeyHash = m_Keyword_map.begin(); itKeyHash != m_Keyword_map.end(); ++itKeyHash ) {
KeyHash* currKeyHash = itKeyHash->second;
k_file.WriteUInt128(currKeyHash->keyID);
CSourceKeyMap& KeyHashSrcMap = currKeyHash->m_Source_map;
wxASSERT(KeyHashSrcMap.size() < 0xFFFFFFFF);
k_file.WriteUInt32((uint32_t)KeyHashSrcMap.size());
for (CSourceKeyMap::iterator itSource = KeyHashSrcMap.begin(); itSource != KeyHashSrcMap.end(); ++itSource ) {
Source* currSource = itSource->second;
k_file.WriteUInt128(currSource->sourceID);
CKadEntryPtrList& SrcEntryList = currSource->entryList;
wxASSERT(SrcEntryList.size() < 0xFFFFFFFF);
k_file.WriteUInt32((uint32_t)SrcEntryList.size());
for (CKadEntryPtrList::iterator itEntry = SrcEntryList.begin(); itEntry != SrcEntryList.end(); ++itEntry) {
Kademlia::CKeyEntry* currName = static_cast<Kademlia::CKeyEntry*>(*itEntry);
wxASSERT(currName->IsKeyEntry());
k_file.WriteUInt32(currName->m_tLifeTime);
currName->WritePublishTrackingDataToFile(&k_file);
currName->WriteTagList(&k_file);
currName->DirtyDeletePublishData();
delete currName;
k_total++;
}
delete currSource;
}
CKeyEntry::ResetGlobalTrackingMap();
delete currKeyHash;
}
k_file.Close();
}
AddDebugLogLineN(logKadIndex, CFormat(wxT("Wrote %u source, %u keyword, and %u load entries")) % s_total % k_total % l_total);
for (SrcHashMap::iterator itNoteHash = m_Notes_map.begin(); itNoteHash != m_Notes_map.end(); ++itNoteHash) {
SrcHash* currNoteHash = itNoteHash->second;
CKadSourcePtrList& KeyHashNoteMap = currNoteHash->m_Source_map;
for (CKadSourcePtrList::iterator itNote = KeyHashNoteMap.begin(); itNote != KeyHashNoteMap.end(); ++itNote) {
Source* currNote = *itNote;
CKadEntryPtrList& NoteEntryList = currNote->entryList;
for (CKadEntryPtrList::iterator itNoteEntry = NoteEntryList.begin(); itNoteEntry != NoteEntryList.end(); ++itNoteEntry) {
delete *itNoteEntry;
}
delete currNote;
}
delete currNoteHash;
}
m_Notes_map.clear();
} catch (const CSafeIOException& err) {
AddDebugLogLineC(logKadIndex, wxT("CSafeIOException in CIndexed::~CIndexed: ") + err.what());
} catch (const CInvalidPacket& err) {
AddDebugLogLineC(logKadIndex, wxT("CInvalidPacket Exception in CIndexed::~CIndexed: ") + err.what());
} catch (const wxString& e) {
AddDebugLogLineC(logKadIndex, wxT("Exception in CIndexed::~CIndexed: ") + e);
}
}
void CIndexed::Clean()
{
time_t tNow = time(NULL);
if (m_lastClean > tNow) {
return;
}
uint32_t k_Removed = 0;
uint32_t s_Removed = 0;
uint32_t s_Total = 0;
uint32_t k_Total = 0;
KeyHashMap::iterator itKeyHash = m_Keyword_map.begin();
while (itKeyHash != m_Keyword_map.end()) {
KeyHashMap::iterator curr_itKeyHash = itKeyHash++; // Don't change this to a ++it!
KeyHash* currKeyHash = curr_itKeyHash->second;
for (CSourceKeyMap::iterator itSource = currKeyHash->m_Source_map.begin(); itSource != currKeyHash->m_Source_map.end(); ) {
CSourceKeyMap::iterator curr_itSource = itSource++; // Don't change this to a ++it!
Source* currSource = curr_itSource->second;
CKadEntryPtrList::iterator itEntry = currSource->entryList.begin();
while (itEntry != currSource->entryList.end()) {
k_Total++;
Kademlia::CKeyEntry* currName = static_cast<Kademlia::CKeyEntry*>(*itEntry);
wxASSERT(currName->IsKeyEntry());
if (!currName->m_bSource && currName->m_tLifeTime < tNow) {
k_Removed++;
itEntry = currSource->entryList.erase(itEntry);
delete currName;
continue;
} else if (currName->m_bSource) {
wxFAIL;
} else {
currName->CleanUpTrackedPublishers(); // intern cleanup
}
++itEntry;
}
if (currSource->entryList.empty()) {
currKeyHash->m_Source_map.erase(curr_itSource);
delete currSource;
}
}
if (currKeyHash->m_Source_map.empty()) {
m_Keyword_map.erase(curr_itKeyHash);
delete currKeyHash;
}
}
SrcHashMap::iterator itSrcHash = m_Sources_map.begin();
while (itSrcHash != m_Sources_map.end()) {
SrcHashMap::iterator curr_itSrcHash = itSrcHash++; // Don't change this to a ++it!
SrcHash* currSrcHash = curr_itSrcHash->second;
CKadSourcePtrList::iterator itSource = currSrcHash->m_Source_map.begin();
while (itSource != currSrcHash->m_Source_map.end()) {
Source* currSource = *itSource;
CKadEntryPtrList::iterator itEntry = currSource->entryList.begin();
while (itEntry != currSource->entryList.end()) {
s_Total++;
Kademlia::CEntry* currName = *itEntry;
if (currName->m_tLifeTime < tNow) {
s_Removed++;
itEntry = currSource->entryList.erase(itEntry);
delete currName;
} else {
++itEntry;
}
}
if (currSource->entryList.empty()) {
itSource = currSrcHash->m_Source_map.erase(itSource);
delete currSource;
} else {
++itSource;
}
}
if (currSrcHash->m_Source_map.empty()) {
m_Sources_map.erase(curr_itSrcHash);
delete currSrcHash;
}
}
m_totalIndexSource = s_Total - s_Removed;
m_totalIndexKeyword = k_Total - k_Removed;
AddDebugLogLineN(logKadIndex, CFormat(wxT("Removed %u keyword out of %u and %u source out of %u")) % k_Removed % k_Total % s_Removed % s_Total);
m_lastClean = tNow + MIN2S(30);
}
bool CIndexed::AddKeyword(const CUInt128& keyID, const CUInt128& sourceID, Kademlia::CKeyEntry* entry, uint8_t& load)
{
if (!entry) {
return false;
}
wxCHECK(entry->IsKeyEntry(), false);
if (m_totalIndexKeyword > KADEMLIAMAXENTRIES) {
load = 100;
return false;
}
if (entry->m_uSize == 0 || entry->GetCommonFileName().IsEmpty() || entry->GetTagCount() == 0 || entry->m_tLifeTime < time(NULL)) {
return false;
}
KeyHashMap::iterator itKeyHash = m_Keyword_map.find(keyID);
KeyHash* currKeyHash = NULL;
if (itKeyHash == m_Keyword_map.end()) {
Source* currSource = new Source;
currSource->sourceID = sourceID;
entry->MergeIPsAndFilenames(NULL); // IpTracking init
currSource->entryList.push_front(entry);
currKeyHash = new KeyHash;
currKeyHash->keyID = keyID;
currKeyHash->m_Source_map[currSource->sourceID] = currSource;
m_Keyword_map[currKeyHash->keyID] = currKeyHash;
load = 1;
m_totalIndexKeyword++;
return true;
} else {
currKeyHash = itKeyHash->second;
size_t indexTotal = currKeyHash->m_Source_map.size();
if (indexTotal > KADEMLIAMAXINDEX) {
load = 100;
//Too many entries for this Keyword..
return false;
}
Source* currSource = NULL;
CSourceKeyMap::iterator itSource = currKeyHash->m_Source_map.find(sourceID);
if (itSource != currKeyHash->m_Source_map.end()) {
currSource = itSource->second;
if (!currSource->entryList.empty()) {
if (indexTotal > KADEMLIAMAXINDEX - 5000) {
load = 100;
//We are in a hot node.. If we continued to update all the publishes
//while this index is full, popular files will be the only thing you index.
return false;
}
// also check for size match
CKeyEntry *oldEntry = NULL;
for (CKadEntryPtrList::iterator itEntry = currSource->entryList.begin(); itEntry != currSource->entryList.end(); ++itEntry) {
CKeyEntry *currEntry = static_cast<Kademlia::CKeyEntry*>(*itEntry);
wxASSERT(currEntry->IsKeyEntry());
if (currEntry->m_uSize == entry->m_uSize) {
oldEntry = currEntry;
currSource->entryList.erase(itEntry);
break;
}
}
entry->MergeIPsAndFilenames(oldEntry); // oldEntry can be NULL, that's ok and we still need to do this call in this case
if (oldEntry == NULL) {
m_totalIndexKeyword++;
AddDebugLogLineN(logKadIndex, wxT("Multiple sizes published for file ") + entry->m_uSourceID.ToHexString());
}
delete oldEntry;
oldEntry = NULL;
} else {
m_totalIndexKeyword++;
entry->MergeIPsAndFilenames(NULL); // IpTracking init
}
load = (uint8_t)((indexTotal * 100) / KADEMLIAMAXINDEX);
currSource->entryList.push_front(entry);
return true;
} else {
currSource = new Source;
currSource->sourceID = sourceID;
entry->MergeIPsAndFilenames(NULL); // IpTracking init
currSource->entryList.push_front(entry);
currKeyHash->m_Source_map[currSource->sourceID] = currSource;
m_totalIndexKeyword++;
load = (indexTotal * 100) / KADEMLIAMAXINDEX;
return true;
}
}
}
bool CIndexed::AddSources(const CUInt128& keyID, const CUInt128& sourceID, Kademlia::CEntry* entry, uint8_t& load)
{
if (!entry) {
return false;
}
if( entry->m_uIP == 0 || entry->m_uTCPport == 0 || entry->m_uUDPport == 0 || entry->GetTagCount() == 0 || entry->m_tLifeTime < time(NULL)) {
return false;
}
SrcHash* currSrcHash = NULL;
SrcHashMap::iterator itSrcHash = m_Sources_map.find(keyID);
if (itSrcHash == m_Sources_map.end()) {
Source* currSource = new Source;
currSource->sourceID = sourceID;
currSource->entryList.push_front(entry);
currSrcHash = new SrcHash;
currSrcHash->keyID = keyID;
currSrcHash->m_Source_map.push_front(currSource);
m_Sources_map[currSrcHash->keyID] = currSrcHash;
m_totalIndexSource++;
load = 1;
return true;
} else {
currSrcHash = itSrcHash->second;
size_t size = currSrcHash->m_Source_map.size();
for (CKadSourcePtrList::iterator itSource = currSrcHash->m_Source_map.begin(); itSource != currSrcHash->m_Source_map.end(); ++itSource) {
Source* currSource = *itSource;
if (!currSource->entryList.empty()) {
CEntry* currEntry = currSource->entryList.front();
wxASSERT(currEntry != NULL);
if (currEntry->m_uIP == entry->m_uIP && (currEntry->m_uTCPport == entry->m_uTCPport || currEntry->m_uUDPport == entry->m_uUDPport)) {
CEntry* currName = currSource->entryList.front();
currSource->entryList.pop_front();
delete currName;
currSource->entryList.push_front(entry);
load = (size * 100) / KADEMLIAMAXSOURCEPERFILE;
return true;
}
} else {
//This should never happen!
currSource->entryList.push_front(entry);
wxFAIL;
load = (size * 100) / KADEMLIAMAXSOURCEPERFILE;
return true;
}
}
if (size > KADEMLIAMAXSOURCEPERFILE) {
Source* currSource = currSrcHash->m_Source_map.back();
currSrcHash->m_Source_map.pop_back();
wxASSERT(currSource != NULL);
Kademlia::CEntry* currName = currSource->entryList.back();
currSource->entryList.pop_back();
wxASSERT(currName != NULL);
delete currName;
currSource->sourceID = sourceID;
currSource->entryList.push_front(entry);
currSrcHash->m_Source_map.push_front(currSource);
load = 100;
return true;
} else {
Source* currSource = new Source;
currSource->sourceID = sourceID;
currSource->entryList.push_front(entry);
currSrcHash->m_Source_map.push_front(currSource);
m_totalIndexSource++;
load = (size * 100) / KADEMLIAMAXSOURCEPERFILE;
return true;
}
}
return false;
}
bool CIndexed::AddNotes(const CUInt128& keyID, const CUInt128& sourceID, Kademlia::CEntry* entry, uint8_t& load)
{
if (!entry) {
return false;
}
if (entry->m_uIP == 0 || entry->GetTagCount() == 0) {
return false;
}
SrcHash* currNoteHash = NULL;
SrcHashMap::iterator itNoteHash = m_Notes_map.find(keyID);
if (itNoteHash == m_Notes_map.end()) {
Source* currNote = new Source;
currNote->sourceID = sourceID;
currNote->entryList.push_front(entry);
currNoteHash = new SrcHash;
currNoteHash->keyID = keyID;
currNoteHash->m_Source_map.push_front(currNote);
m_Notes_map[currNoteHash->keyID] = currNoteHash;
load = 1;
m_totalIndexNotes++;
return true;
} else {
currNoteHash = itNoteHash->second;
size_t size = currNoteHash->m_Source_map.size();
for (CKadSourcePtrList::iterator itSource = currNoteHash->m_Source_map.begin(); itSource != currNoteHash->m_Source_map.end(); ++itSource) {
Source* currNote = *itSource;
if (!currNote->entryList.empty()) {
CEntry* currEntry = currNote->entryList.front();
wxASSERT(currEntry!=NULL);
if (currEntry->m_uIP == entry->m_uIP || currEntry->m_uSourceID == entry->m_uSourceID) {
CEntry* currName = currNote->entryList.front();
currNote->entryList.pop_front();
delete currName;
currNote->entryList.push_front(entry);
load = (size * 100) / KADEMLIAMAXNOTESPERFILE;
return true;
}
} else {
//This should never happen!
currNote->entryList.push_front(entry);
wxFAIL;
load = (size * 100) / KADEMLIAMAXNOTESPERFILE;
m_totalIndexNotes++;
return true;
}
}
if (size > KADEMLIAMAXNOTESPERFILE) {
Source* currNote = currNoteHash->m_Source_map.back();
currNoteHash->m_Source_map.pop_back();
wxASSERT(currNote != NULL);
CEntry* currName = currNote->entryList.back();
currNote->entryList.pop_back();
wxASSERT(currName != NULL);
delete currName;
currNote->sourceID = sourceID;
currNote->entryList.push_front(entry);
currNoteHash->m_Source_map.push_front(currNote);
load = 100;
return true;
} else {
Source* currNote = new Source;
currNote->sourceID = sourceID;
currNote->entryList.push_front(entry);
currNoteHash->m_Source_map.push_front(currNote);
load = (size * 100) / KADEMLIAMAXNOTESPERFILE;
m_totalIndexNotes++;
return true;
}
}
}
bool CIndexed::AddLoad(const CUInt128& keyID, uint32_t timet)
{
Load* load = NULL;
if ((uint32_t)time(NULL) > timet) {
return false;
}
LoadMap::iterator it = m_Load_map.find(keyID);
if (it != m_Load_map.end()) {
wxFAIL;
return false;
}
load = new Load();
load->keyID = keyID;
load->time = timet;
m_Load_map[load->keyID] = load;
m_totalIndexLoad++;
return true;
}
void CIndexed::SendValidKeywordResult(const CUInt128& keyID, const SSearchTerm* pSearchTerms, uint32_t ip, uint16_t port, bool oldClient, uint16_t startPosition, const CKadUDPKey& senderKey)
{
KeyHash* currKeyHash = NULL;
KeyHashMap::iterator itKeyHash = m_Keyword_map.find(keyID);
if (itKeyHash != m_Keyword_map.end()) {
currKeyHash = itKeyHash->second;
CMemFile packetdata(1024 * 50);
packetdata.WriteUInt128(Kademlia::CKademlia::GetPrefs()->GetKadID());
packetdata.WriteUInt128(keyID);
packetdata.WriteUInt16(50);
const uint16_t maxResults = 300;
int count = 0 - startPosition;
// we do 2 loops: In the first one we ignore all results which have a trustvalue below 1
// in the second one we then also consider those. That way we make sure our 300 max results are not full
// of spam entries. We could also sort by trustvalue, but we would risk to only send popular files this way
// on very hot keywords
bool onlyTrusted = true;
DEBUG_ONLY( uint32_t dbgResultsTrusted = 0; )
DEBUG_ONLY( uint32_t dbgResultsUntrusted = 0; )
do {
for (CSourceKeyMap::iterator itSource = currKeyHash->m_Source_map.begin(); itSource != currKeyHash->m_Source_map.end(); ++itSource) {
Source* currSource = itSource->second;
for (CKadEntryPtrList::iterator itEntry = currSource->entryList.begin(); itEntry != currSource->entryList.end(); ++itEntry) {
Kademlia::CKeyEntry* currName = static_cast<Kademlia::CKeyEntry*>(*itEntry);
wxASSERT(currName->IsKeyEntry());
if ((onlyTrusted ^ (currName->GetTrustValue() < 1.0)) && (!pSearchTerms || currName->SearchTermsMatch(pSearchTerms))) {
if (count < 0) {
count++;
} else if ((uint16_t)count < maxResults) {
if (!oldClient || currName->m_uSize <= OLD_MAX_FILE_SIZE) {
count++;
#ifdef __DEBUG__
if (onlyTrusted) {
dbgResultsTrusted++;
} else {
dbgResultsUntrusted++;
}
#endif
packetdata.WriteUInt128(currName->m_uSourceID);
currName->WriteTagListWithPublishInfo(&packetdata);
if (count % 50 == 0) {
DebugSend(Kad2SearchRes, ip, port);
CKademlia::GetUDPListener()->SendPacket(packetdata, KADEMLIA2_SEARCH_RES, ip, port, senderKey, NULL);
// Reset the packet, keeping the header (Kad id, key id, number of entries)
packetdata.SetLength(16 + 16 + 2);
}
}
} else {
itSource = currKeyHash->m_Source_map.end();
--itSource;
break;
}
}
}
}
if (onlyTrusted && count < (int)maxResults) {
onlyTrusted = false;
} else {
break;
}
} while (!onlyTrusted);
AddDebugLogLineN(logKadIndex, CFormat(wxT("Kad keyword search result request: Sent %u trusted and %u untrusted results")) % dbgResultsTrusted % dbgResultsUntrusted);
if (count > 0) {
uint16_t countLeft = (uint16_t)count % 50;
if (countLeft) {
packetdata.Seek(16 + 16);
packetdata.WriteUInt16(countLeft);
DebugSend(Kad2SearchRes, ip, port);
CKademlia::GetUDPListener()->SendPacket(packetdata, KADEMLIA2_SEARCH_RES, ip, port, senderKey, NULL);
}
}
}
Clean();
}
void CIndexed::SendValidSourceResult(const CUInt128& keyID, uint32_t ip, uint16_t port, uint16_t startPosition, uint64_t fileSize, const CKadUDPKey& senderKey)
{
SrcHash* currSrcHash = NULL;
SrcHashMap::iterator itSrcHash = m_Sources_map.find(keyID);
if (itSrcHash != m_Sources_map.end()) {
currSrcHash = itSrcHash->second;
CMemFile packetdata(1024*50);
packetdata.WriteUInt128(Kademlia::CKademlia::GetPrefs()->GetKadID());
packetdata.WriteUInt128(keyID);
packetdata.WriteUInt16(50);
uint16_t maxResults = 300;
int count = 0 - startPosition;
for (CKadSourcePtrList::iterator itSource = currSrcHash->m_Source_map.begin(); itSource != currSrcHash->m_Source_map.end(); ++itSource) {
Source* currSource = *itSource;
if (!currSource->entryList.empty()) {
Kademlia::CEntry* currName = currSource->entryList.front();
if (count < 0) {
count++;
} else if (count < maxResults) {
if (!fileSize || !currName->m_uSize || currName->m_uSize == fileSize) {
packetdata.WriteUInt128(currName->m_uSourceID);
currName->WriteTagList(&packetdata);
count++;
if (count % 50 == 0) {
DebugSend(Kad2SearchRes, ip, port);
CKademlia::GetUDPListener()->SendPacket(packetdata, KADEMLIA2_SEARCH_RES, ip, port, senderKey, NULL);
// Reset the packet, keeping the header (Kad id, key id, number of entries)
packetdata.SetLength(16 + 16 + 2);
}
}
} else {
break;
}
}
}
if (count > 0) {
uint16_t countLeft = (uint16_t)count % 50;
if (countLeft) {
packetdata.Seek(16 + 16);
packetdata.WriteUInt16(countLeft);
DebugSend(Kad2SearchRes, ip, port);
CKademlia::GetUDPListener()->SendPacket(packetdata, KADEMLIA2_SEARCH_RES, ip, port, senderKey, NULL);
}
}
}
Clean();
}
void CIndexed::SendValidNoteResult(const CUInt128& keyID, uint32_t ip, uint16_t port, uint64_t fileSize, const CKadUDPKey& senderKey)
{
SrcHash* currNoteHash = NULL;
SrcHashMap::iterator itNote = m_Notes_map.find(keyID);
if (itNote != m_Notes_map.end()) {
currNoteHash = itNote->second;
CMemFile packetdata(1024*50);
packetdata.WriteUInt128(Kademlia::CKademlia::GetPrefs()->GetKadID());
packetdata.WriteUInt128(keyID);
packetdata.WriteUInt16(50);
uint16_t maxResults = 150;
uint16_t count = 0;
for (CKadSourcePtrList::iterator itSource = currNoteHash->m_Source_map.begin(); itSource != currNoteHash->m_Source_map.end(); ++itSource ) {
Source* currNote = *itSource;
if (!currNote->entryList.empty()) {
Kademlia::CEntry* currName = currNote->entryList.front();
if (count < maxResults) {
if (!fileSize || !currName->m_uSize || fileSize == currName->m_uSize) {
packetdata.WriteUInt128(currName->m_uSourceID);
currName->WriteTagList(&packetdata);
count++;
if (count % 50 == 0) {
DebugSend(Kad2SearchRes, ip, port);
CKademlia::GetUDPListener()->SendPacket(packetdata, KADEMLIA2_SEARCH_RES, ip, port, senderKey, NULL);
// Reset the packet, keeping the header (Kad id, key id, number of entries)
packetdata.SetLength(16 + 16 + 2);
}
}
} else {
break;
}
}
}
uint16_t countLeft = count % 50;
if (countLeft) {
packetdata.Seek(16 + 16);
packetdata.WriteUInt16(countLeft);
DebugSend(Kad2SearchRes, ip, port);
CKademlia::GetUDPListener()->SendPacket(packetdata, KADEMLIA2_SEARCH_RES, ip, port, senderKey, NULL);
}
}
}
bool CIndexed::SendStoreRequest(const CUInt128& keyID)
{
Load* load = NULL;
LoadMap::iterator it = m_Load_map.find(keyID);
if (it != m_Load_map.end()) {
load = it->second;
if (load->time < (uint32_t)time(NULL)) {
m_Load_map.erase(it);
m_totalIndexLoad--;
delete load;
return true;
}
return false;
}
return true;
}
SSearchTerm::SSearchTerm()
: type(AND),
tag(NULL),
astr(NULL),
left(NULL),
right(NULL)
{}
SSearchTerm::~SSearchTerm()
{
if (type == String) {
delete astr;
}
delete tag;
}
// File_checked_for_headers
| 31,390 | 13,988 |
#include <bits/stdc++.h>
#ifdef LOCAL
#include "code/formatting.hpp"
#else
#define debug(...) (void)0
#endif
using namespace std;
template <typename Node>
struct segtree {
vector<Node> node;
vector<array<int, 2>> range;
vector<int> where;
segtree() = default;
segtree(int L, int R, Node init) { assign(L, R, init); }
template <typename T>
segtree(int L, int R, const vector<T>& arr, int s = 0) {
assign(L, R, arr, s);
}
void assign(int L, int R, Node init) {
int N = R - L;
node.assign(2 * N, init);
range.resize(2 * N);
where.resize(N);
int Q = 1 << (N > 1 ? 8 * sizeof(N) - __builtin_clz(N - 1) : 0);
for (int i = 0; i < N; i++) {
range[i + N] = {L + i, L + i + 1};
}
rotate(begin(range) + N, begin(range) + (3 * N - Q), end(range));
for (int i = 0; i < N; i++) {
where[range[i + N][0] - L] = i + N;
}
for (int u = N - 1; u >= 1; u--) {
range[u] = {range[u << 1][0], range[u << 1 | 1][1]};
pushup(u);
}
}
template <typename T>
void assign(int L, int R, const vector<T>& arr, int s = 0) {
int N = R - L;
node.resize(2 * N);
range.resize(2 * N);
where.resize(N);
int Q = 1 << (N > 1 ? 8 * sizeof(N) - __builtin_clz(N - 1) : 0);
for (int i = 0; i < N; i++) {
range[i + N] = {L + i, L + i + 1};
node[i + N] = Node(arr[L + i - s]);
}
rotate(begin(range) + N, begin(range) + (3 * N - Q), end(range));
rotate(begin(node) + N, begin(node) + (3 * N - Q), end(node));
for (int i = 0; i < N; i++) {
where[range[i + N][0] - L] = i + N;
}
for (int u = N - 1; u >= 1; u--) {
range[u] = {range[u << 1][0], range[u << 1 | 1][1]};
pushup(u);
}
}
auto query_point(int i) const {
assert(range[1][0] <= i && i < range[1][1]);
int u = where[i - range[1][0]];
return node[u];
}
template <typename Update>
void update_point(int i, Update&& update) {
assert(range[1][0] <= i && i < range[1][1]);
int u = where[i - range[1][0]];
apply(u, update);
while ((u >>= 1) >= 1) {
pushup(u);
}
}
auto query_range(int L, int R) const {
assert(range[1][0] <= L && R <= range[1][1]);
return query_range(1, L, R);
}
auto query_all() const { return node[1]; }
// Find first i>=k such that fn([L,i]) holds, or R otherwise
// Fn is F F F F T T T T ...
template <typename Fn>
int prefix_binary_search(int k, Fn&& fn) {
auto [L, R] = range[1];
Node ans;
int i = 1, N = R - L;
while (i < N) {
Node v = combine(ans, node[i << 1]);
if (range[i << 1][1] <= k || !fn(v)) {
ans = move(v);
i = i << 1 | 1;
} else {
i = i << 1;
}
}
Node v = combine(ans, node[i]);
return range[i][0] + !fn(v);
}
// Find last i<=k such that fn([i,R)) holds, or L-1 otherwise
// Fn is T T T T F F F F ...
template <typename Fn>
int suffix_binary_search(int k, Fn&& fn) {
auto [L, R] = range[1];
Node ans;
int i = 1, N = R - L;
while (i < N) {
Node v = combine(node[i << 1 | 1], ans);
if (k < range[i << 1][1] || !fn(v)) {
ans = move(v);
i = i << 1;
} else {
i = i << 1 | 1;
}
}
Node v = combine(ans, node[i]);
return range[i][0] - !fn(v);
}
template <typename Fn>
int prefix_binary_search(Fn&& fn) {
return prefix_binary_search(range[1][0], forward<Fn>(fn));
}
template <typename Fn>
int suffix_binary_search(Fn&& fn) {
return suffix_binary_search(range[1][1] - 1, forward<Fn>(fn));
}
private:
static Node combine(const Node& x, const Node& y) {
Node ans;
ans.pushup(x, y);
return ans;
}
template <typename Update>
void apply(int u, Update&& update) {
if constexpr (Node::RANGES) {
node[u].apply(update, 1);
} else {
node[u].apply(update);
}
}
void pushup(int u) {
node[u].pushup(node[u << 1], node[u << 1 | 1]); //
}
auto query_range(int u, int L, int R) const {
if (L <= range[u][0] && range[u][1] <= R) {
return node[u];
}
int m = range[u << 1][1];
if (R <= m) {
return query_range(u << 1, L, R);
} else if (m <= L) {
return query_range(u << 1 | 1, L, R);
} else {
return combine(query_range(u << 1, L, m), query_range(u << 1 | 1, m, R));
}
}
};
struct segnode {
static constexpr bool LAZY = false, RANGES = false, REVERSE = false;
int side = 0; // +1 for (, -1 for )
int minprefix = 0; // should be 0
segnode() = default;
segnode(int side) : side(side), minprefix(side) { assert(side == +1 || side == -1); }
void pushup(const segnode& lhs, const segnode& rhs) {
side = lhs.side + rhs.side;
minprefix = min(lhs.minprefix, lhs.side + rhs.minprefix);
}
void apply(int set) { side = minprefix = set; }
};
int main() {
ios::sync_with_stdio(false), cin.tie(nullptr);
int N, Q;
cin >> N >> Q;
string s;
cin >> s;
vector<int> side(N);
for (int i = 0; i < N; i++) {
side[i] = s[i] == '(' ? +1 : -1;
}
segtree<segnode> st(0, N, side);
while (Q--) {
int type, l, r;
cin >> type >> l >> r, l--, r--;
if (type == 1 && side[l] != side[r]) {
st.update_point(l, side[r]);
st.update_point(r, side[l]);
swap(side[l], side[r]);
} else if (type == 2) {
auto ans = st.query_range(l, r + 1);
if (ans.side == 0 && ans.minprefix == 0) {
cout << "Yes\n";
} else {
cout << "No\n";
}
}
}
return 0;
}
| 6,197 | 2,327 |
#include<iostream>
#include<cmath>
using namespace std;
//avoids the space complexity of O(n) by directly extracting the digits from the input.
bool IsPalindromeNumber(int x) {
if (x <= 0) {
return x == 0;
}
const int num_digits = static_cast<int>(floor(log10(x))) + 1;
int msd_mask = static_cast<int>(pow(10, num_digits - 1));
for (int i = 0; i < (num_digits / 2); ++i) {
if (x / msd_mask != x % 10) { //checks MSB != LSB returns false
return false;
}
x %= msd_mask; // Remove the most significant digit of x.
x /= 10; // Remove the least significant digit of x.
msd_mask /= 100;
}
return true;
}
int main(int argc, char const *argv[]) {
int n;
cin>>n;
if(IsPalindromeNumber(n)) cout<<"Palindrome";
else cout<<"Not Palindrome";
return 0;
}
| 808 | 320 |
/* Copyright 2001, 2019 IBM Corporation
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef DATARECEIVERSNAPSHOTDUMPER_HPP
#define DATARECEIVERSNAPSHOTDUMPER_HPP
#include <ostream>
#include <fstream>
#include <BlueMatter/DataReceiver.hpp>
#include <BlueMatter/ExternalDatagram.hpp>
// #define STEADY_SHOT
using namespace std;
struct XYZShort{
unsigned short mX;
unsigned short mY;
unsigned short mZ;
};
class DataReceiverSnapshotDumper : public DataReceiver
{
public:
ofstream mStream;
FILE *mFile;
char mBMTFileName[256];
char mPDBFileName[256];
int mNNonWaterAtoms;
int mNWaters;
int mDoAppend;
int mStartIndex;
int mEndIndex;
int mNoWaters;
#ifdef STEADY_SHOT
XYZ FirstOrigin;
int FirstFrame;
#endif
XYZShort *mpShortPos;
void setParams(char *BMTFileName, char *PDBFileName, int NNonWaterAtoms, int NWaters, int DoAppend=0, int NoWaters=0)
{
strcpy(mBMTFileName, BMTFileName);
strcpy(mPDBFileName, PDBFileName);
mNNonWaterAtoms = NNonWaterAtoms;
mNWaters = NWaters;
mDoAppend = DoAppend;
mNoWaters = NoWaters;
mStartIndex = 0;
mEndIndex = NNonWaterAtoms + 3 * NWaters - 1;
if (NoWaters)
mEndIndex = NNonWaterAtoms - 1;
}
virtual void init()
{
char buff[1024];
mpShortPos = NULL;
if (!mDoAppend) {
mStream.open(mBMTFileName);
if (!mStream.is_open()) {
cerr << "SSD output file " << mBMTFileName << " could not be open." << endl;
exit(-1);
}
mStream << "SSD" << endl;
mStream << "VERSION 1.00" << endl;
mStream << "STRUCTURE " << mPDBFileName << endl;
mStream << "BONDS NULL" << endl;
mStream << "NUMNONWATERATOMS " << mNNonWaterAtoms << endl;
mStream << "NUMWATERS " << mNWaters << endl;
mStream << "NOWATERS " << mNoWaters << endl;
mStream << "STARTINDEX " << mStartIndex << endl;
mStream << "ENDINDEX " << mEndIndex << endl;
mStream << "SNAPSHOTFORMAT nsites* double px,py,pz,vx,vy,vz" << endl;
mStream.close();
}
mFile = fopen(mBMTFileName, "ab");
if (!mFile) {
cerr << "BMT output file " << mBMTFileName << " could not be open for binary write/append." << endl;
exit(-1);
}
}
virtual void final()
{
if (fclose(mFile)) {
cerr << "Error on closing " << mBMTFileName << endl;
}
if (mpShortPos)
delete [] mpShortPos;
}
void FrameCenter(tSiteData *full_ps, int Start, int End, XYZ &cen)
{
tSiteData *ps = &full_ps[Start];
cen.Zero();
for (int i=Start; i<=End; i++) {
XYZ s = ps->mPosition;
cen = cen + s;
ps++;
}
double N = 1.0 / (Start - End);
cen = N * cen;
return;
}
void findBox(tSiteData *full_ps, int Start, int End, XYZ &origin, XYZ &span, double &MaxSpan)
{
XYZ LL, UR;
tSiteData *ps = &full_ps[Start];
LL.mX = LL.mY = LL.mZ = 1.0E20;
UR.mX = UR.mY = UR.mZ = -1.0E20;
for (int i=Start; i<=End; i++) {
XYZ s = ps->mPosition;
if (s.mX < LL.mX) LL.mX = s.mX;
if (s.mX > UR.mX) UR.mX = s.mX;
if (s.mY < LL.mY) LL.mY = s.mY;
if (s.mY > UR.mY) UR.mY = s.mY;
if (s.mZ < LL.mZ) LL.mZ = s.mZ;
if (s.mZ > UR.mZ) UR.mZ = s.mZ;
ps++;
}
origin = LL;
span = UR - LL;
MaxSpan = span.mX;
if (span.mY > MaxSpan) MaxSpan = span.mY;
if (span.mZ > MaxSpan) MaxSpan = span.mZ;
}
void simplifySites(tSiteData *full_ps, XYZShort *psp, int Start, int End, XYZ &origin, double factor)
{
tSiteData *ps = &full_ps[Start];
for (int i=Start; i<=End; i++) {
XYZ p = ps->mPosition;
p -= origin;
psp->mX = p.mX*factor;
psp->mY = p.mY*factor;
psp->mZ = p.mZ*factor;
ps++;
psp++;
}
}
virtual void sites(Frame *f)
{
static char fname[512];
int NumToWrite;
int NumWritten;
unsigned CurrentStep = f->mOuterTimeStep;
tSiteData *ps= f->mSiteData.getArray();
int NSites = f->mSiteData.getSize();
XYZ cen;
// CenterFrame(ps,mStartIndex,mEndIndex);
#if 1
for (int i=0; i<NSites; i++)
{
int site = i+1;
fwrite(&CurrentStep, sizeof(int), 1, mFile);
fwrite(&site, sizeof(int), 1, mFile);
fwrite(&ps->mPosition, sizeof(double), 3, mFile);
fwrite(&ps->mVelocity, sizeof(double), 3, mFile);
ps++;
}
#endif
#if 0
for (int i=0; i<NSites; i++)
{
XYZ &p = ps->mPosition;
XYZ &v = ps->mVelocity;
fprintf(mFile,"%10d %6d %12.8f %12.8f %12.8f %12.8f %12.8 %12.8 /n",
CurrentStep,i+1,p.mX,p.mY,p.mZ,v.mX,v.mY,v.mZ);
ps++;
}
#endif
}
#if 0
virtual void udfs(Frame *f)
{
tEnergySumAccumulator *pesa = &f->mEnergyInfo.mEnergySumAccumulator;
pesa->mBondEnergy =
f->mUDFs[ UDF_Binding::StdHarmonicBondForce_Code ].getSum();
pesa->mAngleEnergy =
f->mUDFs[ UDF_Binding::StdHarmonicAngleForce_Code ].getSum();
pesa->mUBEnergy =
f->mUDFs[ UDF_Binding::UreyBradleyForce_Code ].getSum();
pesa->mTorsionEnergy =
f->mUDFs[ UDF_Binding::SwopeTorsionForce_Code ].getSum() +
f->mUDFs[ UDF_Binding::OPLSTorsionForce_Code ].getSum();
pesa->mImproperEnergy =
f->mUDFs[ UDF_Binding::OPLSImproperForce_Code ].getSum() +
f->mUDFs[ UDF_Binding::ImproperDihedralForce_Code ].getSum() ;
pesa->mChargeEnergy =
f->mUDFs[ UDF_Binding::StdChargeForce_Code ].getSum();
pesa->mLennardJonesEnergy =
f->mUDFs[ UDF_Binding::LennardJonesForce_Code ].getSum();
pesa->mKineticEnergy =
f->mUDFs[ UDF_Binding::KineticEnergy_Code ].getSum();
pesa->mWaterEnergy =
f->mUDFs[ UDF_Binding::TIP3PForce_Code ].getSum();
f->mEnergyInfo.mEnergySums.mIntraE =
pesa->mBondEnergy +
pesa->mAngleEnergy +
pesa->mUBEnergy +
pesa->mTorsionEnergy +
pesa->mImproperEnergy +
pesa->mWaterEnergy;
f->mEnergyInfo.mEnergySums.mInterE =
pesa->mChargeEnergy +
pesa->mLennardJonesEnergy;
if (f->mNSites > 0)
f->mEnergyInfo.mEnergySums.mTemp = f->mEnergyInfo.mEnergySumAccumulator.mKineticEnergy/1.5/f->mNSites/SciConst::KBoltzmann_IU;
else
f->mEnergyInfo.mEnergySums.mTemp = 0;
f->mEnergyInfo.mEnergySums.mTotalE = f->mEnergyInfo.mEnergySums.mInterE + f->mEnergyInfo.mEnergySums.mIntraE + pesa->mKineticEnergy;
pesa->mFullTimeStep = f->mFullTimeStep;
ReportTotalEnergy(&f->mEnergyInfo);
}
#endif
};
#endif
| 8,407 | 3,290 |
// 2021.01.22 - Copyright Victor Dods - Licensed under Apache 2.0
#pragma once
#include "lvd/read_bin_type.hpp"
#include "lvd/sst/SV_t.hpp"
namespace lvd {
template <typename S_, typename C_, auto... Params_>
struct ReadInPlace_t<sst::SV_t<S_,C_>,BinEncoding_t<Params_...>> {
template <typename CharT_, typename Traits_>
std::basic_istream<CharT_,Traits_> &operator() (std::basic_istream<CharT_,Traits_> &in, BinEncoding_t<Params_...> const &enc, sst::SV_t<S_,C_> &dest_val) const {
if constexpr (enc.type_encoding() == TypeEncoding::INCLUDED)
in >> enc.with_demoted_type_encoding().in(type_of(dest_val)); // This will throw if the type doesn't match.
// The type is already known at this point.
auto inner_enc = enc.with_demoted_type_encoding();
// Use assign-move so that the validity check is done automatically.
dest_val = inner_enc.template read<C_>(in);
return in;
}
};
// SV_t<S_,C_> is not in general default-constructible, so ReadValue_t has to be specialized.
template <typename S_, typename C_, typename Encoding_>
struct ReadValue_t<sst::SV_t<S_,C_>,Encoding_> {
template <typename CharT_, typename Traits_>
sst::SV_t<S_,C_> operator() (std::basic_istream<CharT_,Traits_> &in, Encoding_ const &enc) const {
if constexpr (enc.type_encoding() == TypeEncoding::INCLUDED)
in >> enc.with_demoted_type_encoding().in(ty<sst::SV_t<S_,C_>>); // This will throw if the type doesn't match.
// The type is already known at this point.
auto inner_enc = enc.with_demoted_type_encoding();
auto retval = sst::SV_t<S_,C_>{sst::no_check};
retval = inner_enc.template read<C_>(in);
return retval;
// auto retval = sst::SV_t<S_,C_>{sst::no_check, inner_enc.template read<C_>(in)};
// retval->template check<check_policy_for__ctor_move_C(S_{})>();
// return retval;
// return sst::SV_t<S_,C_>{inner_enc.template read<C_>(in)};
}
};
} // end namespace lvd
| 2,032 | 726 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY!
#include "config.h"
#include "V8RsaKeyAlgorithm.h"
#include "bindings/v8/ExceptionState.h"
#include "bindings/v8/V8DOMConfiguration.h"
#include "bindings/v8/V8HiddenValue.h"
#include "bindings/v8/V8ObjectConstructor.h"
#include "bindings/v8/custom/V8Uint8ArrayCustom.h"
#include "core/dom/ContextFeatures.h"
#include "core/dom/Document.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/TraceEvent.h"
#include "wtf/GetPtr.h"
#include "wtf/RefPtr.h"
namespace WebCore {
static void initializeScriptWrappableForInterface(RsaKeyAlgorithm* object)
{
if (ScriptWrappable::wrapperCanBeStoredInObject(object))
ScriptWrappable::fromObject(object)->setTypeInfo(&V8RsaKeyAlgorithm::wrapperTypeInfo);
else
ASSERT_NOT_REACHED();
}
} // namespace WebCore
void webCoreInitializeScriptWrappableForInterface(WebCore::RsaKeyAlgorithm* object)
{
WebCore::initializeScriptWrappableForInterface(object);
}
namespace WebCore {
const WrapperTypeInfo V8RsaKeyAlgorithm::wrapperTypeInfo = { gin::kEmbedderBlink, V8RsaKeyAlgorithm::domTemplate, V8RsaKeyAlgorithm::derefObject, 0, 0, 0, V8RsaKeyAlgorithm::installPerContextEnabledMethods, &V8KeyAlgorithm::wrapperTypeInfo, WrapperTypeObjectPrototype, GarbageCollectedObject };
namespace RsaKeyAlgorithmV8Internal {
template <typename T> void V8_USE(T) { }
static void modulusLengthAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
RsaKeyAlgorithm* impl = V8RsaKeyAlgorithm::toNative(holder);
v8SetReturnValueUnsigned(info, impl->modulusLength());
}
static void modulusLengthAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
RsaKeyAlgorithmV8Internal::modulusLengthAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void publicExponentAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
RsaKeyAlgorithm* impl = V8RsaKeyAlgorithm::toNative(holder);
RefPtr<Uint8Array> result(impl->publicExponent());
if (result && DOMDataStore::setReturnValueFromWrapper<V8Uint8Array>(info.GetReturnValue(), result.get()))
return;
v8::Handle<v8::Value> wrapper = toV8(result.get(), holder, info.GetIsolate());
if (!wrapper.IsEmpty()) {
V8HiddenValue::setHiddenValue(info.GetIsolate(), holder, v8AtomicString(info.GetIsolate(), "publicExponent"), wrapper);
v8SetReturnValue(info, wrapper);
}
}
static void publicExponentAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
RsaKeyAlgorithmV8Internal::publicExponentAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
} // namespace RsaKeyAlgorithmV8Internal
static const V8DOMConfiguration::AttributeConfiguration V8RsaKeyAlgorithmAttributes[] = {
{"modulusLength", RsaKeyAlgorithmV8Internal::modulusLengthAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */},
{"publicExponent", RsaKeyAlgorithmV8Internal::publicExponentAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */},
};
static void configureV8RsaKeyAlgorithmTemplate(v8::Handle<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate)
{
functionTemplate->ReadOnlyPrototype();
v8::Local<v8::Signature> defaultSignature;
defaultSignature = V8DOMConfiguration::installDOMClassTemplate(functionTemplate, "RsaKeyAlgorithm", V8KeyAlgorithm::domTemplate(isolate), V8RsaKeyAlgorithm::internalFieldCount,
V8RsaKeyAlgorithmAttributes, WTF_ARRAY_LENGTH(V8RsaKeyAlgorithmAttributes),
0, 0,
0, 0,
isolate);
v8::Local<v8::ObjectTemplate> instanceTemplate ALLOW_UNUSED = functionTemplate->InstanceTemplate();
v8::Local<v8::ObjectTemplate> prototypeTemplate ALLOW_UNUSED = functionTemplate->PrototypeTemplate();
// Custom toString template
functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::from(isolate)->toStringTemplate());
}
v8::Handle<v8::FunctionTemplate> V8RsaKeyAlgorithm::domTemplate(v8::Isolate* isolate)
{
return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), configureV8RsaKeyAlgorithmTemplate);
}
bool V8RsaKeyAlgorithm::hasInstance(v8::Handle<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value);
}
v8::Handle<v8::Object> V8RsaKeyAlgorithm::findInstanceInPrototypeChain(v8::Handle<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value);
}
RsaKeyAlgorithm* V8RsaKeyAlgorithm::toNativeWithTypeCheck(v8::Isolate* isolate, v8::Handle<v8::Value> value)
{
return hasInstance(value, isolate) ? fromInternalPointer(v8::Handle<v8::Object>::Cast(value)->GetAlignedPointerFromInternalField(v8DOMWrapperObjectIndex)) : 0;
}
v8::Handle<v8::Object> wrap(RsaKeyAlgorithm* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
ASSERT(impl);
ASSERT(!DOMDataStore::containsWrapper<V8RsaKeyAlgorithm>(impl, isolate));
return V8RsaKeyAlgorithm::createWrapper(impl, creationContext, isolate);
}
v8::Handle<v8::Object> V8RsaKeyAlgorithm::createWrapper(RawPtr<RsaKeyAlgorithm> impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
ASSERT(impl);
ASSERT(!DOMDataStore::containsWrapper<V8RsaKeyAlgorithm>(impl.get(), isolate));
if (ScriptWrappable::wrapperCanBeStoredInObject(impl.get())) {
const WrapperTypeInfo* actualInfo = ScriptWrappable::fromObject(impl.get())->typeInfo();
// Might be a XXXConstructor::wrapperTypeInfo instead of an XXX::wrapperTypeInfo. These will both have
// the same object de-ref functions, though, so use that as the basis of the check.
RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(actualInfo->derefObjectFunction == wrapperTypeInfo.derefObjectFunction);
}
v8::Handle<v8::Object> wrapper = V8DOMWrapper::createWrapper(creationContext, &wrapperTypeInfo, toInternalPointer(impl.get()), isolate);
if (UNLIKELY(wrapper.IsEmpty()))
return wrapper;
installPerContextEnabledProperties(wrapper, impl.get(), isolate);
V8DOMWrapper::associateObjectWithWrapper<V8RsaKeyAlgorithm>(impl, &wrapperTypeInfo, wrapper, isolate, WrapperConfiguration::Independent);
return wrapper;
}
void V8RsaKeyAlgorithm::derefObject(void* object)
{
}
template<>
v8::Handle<v8::Value> toV8NoInline(RsaKeyAlgorithm* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
return toV8(impl, creationContext, isolate);
}
} // namespace WebCore
| 7,254 | 2,434 |
#include <gtest/gtest.h>
#include <fastad_bits/util/value.hpp>
namespace ad {
namespace util {
struct value_fixture : ::testing::Test
{
protected:
};
TEST_F(value_fixture, ones_scl)
{
double x = 0.;
ones(x);
EXPECT_DOUBLE_EQ(x, 1.);
}
} // namespace util
} // namespace ad
| 289 | 119 |
/*
* Copyright 2019 pixiv Inc. All Rights Reserved.
*
* Use of this source code is governed by a license that can be
* found in the LICENSE.pixiv file in the root of the source tree.
*/
#include "api/create_peerconnection_factory.h"
#include "api/video_codecs/video_decoder_factory.h"
#include "api/video_codecs/video_encoder_factory.h"
#include "sdk/c/api/create_peerconnection_factory.h"
extern "C" WebrtcPeerConnectionFactoryInterface*
webrtcCreatePeerConnectionFactory(
RtcThread* network_thread,
RtcThread* worker_thread,
RtcThread* signaling_thread,
WebrtcAudioDeviceModule* default_adm,
WebrtcAudioEncoderFactory* audio_encoder_factory,
WebrtcAudioDecoderFactory* audio_decoder_factory,
WebrtcVideoEncoderFactory* video_encoder_factory,
WebrtcVideoDecoderFactory* video_decoder_factory,
WebrtcAudioMixer* audio_mixer,
WebrtcAudioProcessing* audio_processing) {
return rtc::ToC(
webrtc::CreatePeerConnectionFactory(
rtc::ToCplusplus(network_thread), rtc::ToCplusplus(worker_thread),
rtc::ToCplusplus(signaling_thread), rtc::ToCplusplus(default_adm),
rtc::ToCplusplus(audio_encoder_factory),
rtc::ToCplusplus(audio_decoder_factory),
std::unique_ptr<webrtc::VideoEncoderFactory>(
rtc::ToCplusplus(video_encoder_factory)),
std::unique_ptr<webrtc::VideoDecoderFactory>(
rtc::ToCplusplus(video_decoder_factory)),
rtc::ToCplusplus(audio_mixer), rtc::ToCplusplus(audio_processing))
.release());
}
| 1,562 | 522 |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XX XX
XX emitRISC.cpp XX
XX XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/
#include "jitpch.h"
#pragma hdrstop
#include "alloc.h"
#include "instr.h"
#include "target.h"
#include "emit.h"
/*****************************************************************************/
#if TGT_RISC
/*****************************************************************************
*
* Call the specified function pointer for each epilog block in the current
* method with the epilog's relative code offset. Returns the sum of the
* values returned by the callback.
*/
#if TRACK_GC_REFS
size_t emitter::emitGenEpilogLst(size_t (*fp)(void *, unsigned),
void *cp)
{
#error GC ref tracking NYI for RISC targets
}
#endif
/*****************************************************************************/
#if EMIT_USE_LIT_POOLS
/*****************************************************************************
*
* Allocate an instruction descriptor for an instruction that references
* a literal pool entry.
*/
emitter::instrDesc* emitter::emitNewInstrLPR(size_t size,
gtCallTypes typ,
void * hnd)
{
instrDescLPR * ld = emitAllocInstrLPR(size);
/* Fill in the instruction descriptor */
ld->idInsFmt = IF_RWR_LIT;
ld->idIns = LIT_POOL_LOAD_INS;
ld->idAddr.iiaMembHnd = hnd;
ld->idInfo.idSmallCns = typ;
/* Make sure the type was stored properly */
assert(emitGetInsLPRtyp(ld) == typ);
/* Record the instruction's IG and offset within it */
ld->idlIG = emitCurIG;
ld->idlOffs = emitCurIGsize;
/* Assume this is not a direct call sequence for now */
#if SMALL_DIRECT_CALLS
ld->idlCall = NULL;
#endif
/* Add the instruction to this IG's litpool ref list */
ld->idlNext = emitLPRlistIG;
emitLPRlistIG = ld;
return ld;
}
/*****************************************************************************
*
* When we're finished creating an instruction group, this routine is called
* to perform any literal pool-related work for the current IG.
*/
void emitter::emitRecIGlitPoolRefs(insGroup *ig)
{
/* Update the total estimate of literal pool entries */
emitEstLPwords += emitCurIG->igLPuseCntW;
emitEstLPlongs += emitCurIG->igLPuseCntL;
emitEstLPaddrs += emitCurIG->igLPuseCntA;
/* Does this IG have any instructions referencing the literal pool? */
if (emitLPRlistIG)
{
/* Move all LP referencing instructions to a global list */
instrDescLPR * list = NULL;
instrDescLPR * last = NULL;
do
{
size_t offs;
instrDescLPR * oldI;
instrDescLPR * newI;
/* Grab the next instruction and remove it from the list */
oldI = emitLPRlistIG; emitLPRlistIG = oldI->idlNext;
/* Figure out the address of where the instruction got copied */
offs = (BYTE*)oldI - emitCurIGfreeBase;
newI = (instrDescLPR*)(ig->igData + offs);
#if USE_LCL_EMIT_BUFF
assert((oldI == newI) == emitLclBuffDst);
#endif
assert(newI->idlIG == ig);
assert(newI->idIns == oldI->idIns);
assert(newI->idlNext == oldI->idlNext);
/* Update the "call" field if non-NULL */
if (newI->idlCall)
{
unsigned diff = (BYTE*)newI->idlCall - emitCurIGfreeBase;
newI->idlCall = (instrDescLPR*)(ig->igData + diff);
}
/* Append the new instruction to the list */
newI->idlNext = list;
list = newI;
if (!last)
last = newI;
}
while (emitLPRlistIG);
/* Add the instruction(s) from this IG to the global list */
if (emitCurIG == emitPrologIG)
{
/* We're in the prolog, insert in front of the list */
last->idlNext = emitLPRlist;
emitLPRlist = list;
if (!emitLPRlast)
emitLPRlast = last;
}
else
{
/* Append at the end of the current list */
if (emitLPRlist)
emitLPRlast->idlNext = list;
else
emitLPRlist = list;
last->idlNext = NULL;
emitLPRlast = last;
}
}
assert(emitLPRlistIG == NULL);
}
/*****************************************************************************
*
* Append a literal pool after the specified instruction group. Return its
* estimated size.
*/
size_t emitter::emitAddLitPool(insGroup * ig,
bool skip,
unsigned wordCnt,
short * * nxtLPptrW,
unsigned longCnt,
long * * nxtLPptrL,
unsigned addrCnt,
LPaddrDesc**nxtAPptrL)
{
litPool * lp;
size_t sz;
/* Allocate a pool descriptor and append it to the list */
lp = (litPool*)emitGetMem(sizeof(*lp));
if (emitLitPoolLast)
emitLitPoolLast->lpNext = lp;
else
emitLitPoolList = lp;
emitLitPoolLast = lp;
lp->lpNext = 0;
emitTotLPcount++;
#ifdef DEBUG
lp->lpNum = emitTotLPcount;
#endif
/* If there are longs/addrs, we need at least one word for alignment */
/* but only for sh3? */
#if !TGT_ARM
if ((longCnt || addrCnt) && !wordCnt)
wordCnt++;
#endif // TGT_ARM
/* Remember which group the pool belongs to */
lp->lpIG = ig;
/* There are no references yet */
#if SCHEDULER
lp->lpRefs = NULL;
#endif
/* Conservative size estimate: assume the pool will be completely filled */
sz = wordCnt * 2 +
longCnt * 4 +
addrCnt * 4;
/* Do we need to jump over the literal pool? */
lp->lpJumpIt = skip;
if (skip)
{
size_t jmpSize;
/* Estimate what size jump we'll have to use */
#if JMP_SIZE_MIDDL
lp->lpJumpMedium = false;
#endif
if (sz < JMP_DIST_SMALL_MAX_POS)
{
lp->lpJumpSmall = true; jmpSize = JMP_SIZE_SMALL;
}
#if JMP_SIZE_MIDDL
else if (sz < JMP_DIST_MIDDL_MAX_POS)
{
lp->lpJumpMedium = true; jmpSize = JMP_SIZE_MIDDL;
}
#endif
else
{
lp->lpJumpSmall = false; jmpSize = JMP_SIZE_LARGE;
/* This one really hurts - the jump will need to use the LP */
longCnt++; sz += 4;
}
/* Add the jump size to the total size estimate */
sz += jmpSize;
}
/* Grab the appropriate space in the tables */
lp->lpWordTab =
lp->lpWordNxt = *nxtLPptrW; *nxtLPptrW += wordCnt;
#ifdef DEBUG
lp->lpWordMax = wordCnt;
#endif
lp->lpWordCnt = 0;
lp->lpLongTab =
lp->lpLongNxt = *nxtLPptrL; *nxtLPptrL += longCnt;
#ifdef DEBUG
lp->lpLongMax = longCnt;
#endif
lp->lpLongCnt = 0;
lp->lpAddrTab =
lp->lpAddrNxt = *nxtAPptrL; *nxtAPptrL += addrCnt;
#ifdef DEBUG
lp->lpAddrMax = addrCnt;
#endif
lp->lpAddrCnt = 0;
/* Record the size estimate and add it to the group's size */
lp->lpSize = 0;
lp->lpSizeEst = sz;
ig->igSize += sz;
return sz;
}
/*****************************************************************************
*
* Find an existing literal pool entry that matches the given one. Returns
* the offset of the entry (or -1 in case one wasn't found).
*/
int emitter::emitGetLitPoolEntry(void * table,
unsigned count,
void * value,
size_t size)
{
BYTE * entry = (BYTE*)table;
/* ISSUE: Using linear search here - brilliant!!! */
while (count--)
{
if (!memcmp(entry, value, size))
{
/* Match found, return offset from base of table */
return (BYTE *)entry - (BYTE*)table;
}
entry += size;
}
return -1;
}
/*****************************************************************************
*
* Add an entry for the instruction's operand to the specified literal pool;
* if 'issue' is non-zero, the actual final offset of the entry (relative
* to the method beginning) is returned.
*/
size_t emitter::emitAddLitPoolEntry(litPool *lp,
instrDesc *id, bool issue)
{
int offs;
unsigned base;
int val;
size_t size = emitDecodeSize(id->idOpSize); assert(size == 2 || size == 4);
assert(lp);
assert(id->idInsFmt == IF_RWR_LIT);
/* Get the base offset of the pool (valid only when 'issue' is true) */
base = lp->lpOffs;
/* Try to reuse an existing entry */
if (emitGetInsLPRtyp(id) == CT_INTCNS)
{
int val = id->idAddr.iiaCns;
//printf ("adding lit pool %d with issue %d\n", val, issue);
if (size == 2)
{
/* Search the word table for a match */
offs = emitGetLitPoolEntry(lp->lpWordTab,
lp->lpWordCnt, &val, size);
if (offs != -1)
{
if (issue)
{
/* Do we have any padding? */
if (lp->lpPadding)
{
/* We must be using the first word for padding */
assert(lp->lpPadFake == false);
/* Have we matched the padding word itself? */
if (!offs)
return base;
}
/* Add the long and address sections sizes to the offset */
return base + offs + lp->lpLongCnt * sizeof(int) + lp->lpAddrCnt * sizeof(void*);
}
return 0;
}
/* Search the long table for a match as well */
offs = emitGetLitPoolEntry(lp->lpLongTab,
lp->lpLongCnt*2, &val, size);
if (offs != -1)
goto FOUND_LONG;
/* No match among the existing entries, append a new entry */
#ifdef DEBUG
assert(lp->lpWordCnt < lp->lpWordMax);
#endif
*lp->lpWordNxt++ = (short)val;
lp->lpWordCnt++;
}
else
{
/* Search the long table for a match */
offs = emitGetLitPoolEntry(lp->lpLongTab,
lp->lpLongCnt, &val, size);
if (offs != -1)
{
if (issue)
{
FOUND_LONG:
/* Add padding, if necessary */
if (lp->lpPadding)
base += 2;
/* long/addr entries must always be aligned */
assert(((base + offs) & 3) == 0 || issue == false || size < sizeof(int));
/* Return the offset of the entry */
return base + offs;
}
return 0;
}
/* No match among the existing entries, append a new entry */
#ifdef DEBUG
assert(lp->lpLongCnt < lp->lpLongMax);
#endif
*lp->lpLongNxt++ = val;
lp->lpLongCnt++;
}
}
else
{
LPaddrDesc val;
/* Create an entry for the lookup */
memset(&val, 0, sizeof(val));
val.lpaTyp = emitGetInsLPRtyp(id);
val.lpaHnd = id->idAddr.iiaMethHnd;
// printf("Adding [%d] addr entry [%02X,%08X]\n", issue+1, val.lpaTyp, val.lpaHnd);
/* Search both the addr table for a match */
offs = emitGetLitPoolEntry(lp->lpAddrTab,
lp->lpAddrCnt , &val, sizeof(val));
if (offs != -1)
{
if (issue)
{
/* Add padding, if necessary */
if (base & 3)
{
assert(lp->lpPadding);
base += 2;
}
else
{
assert(lp->lpPadding == false &&
lp->lpPadFake == false);
}
// the offs returned is the offset into the address table, which
// is not the same as the offset into the litpool, since the
// address table contains structures, not simple 32-bit addresses
offs = offs * sizeof(void*) / sizeof(val);
/* Return the offset of the entry */
//return base + offs + lp->lpLongCnt * sizeof(int) + lp->lpAddrCnt * sizeof(void*);
return base + lp->lpLongCnt * sizeof(long) + offs;
}
return 0;
}
/* No match among the existing entries, append a new entry */
#ifdef DEBUG
assert(lp->lpAddrCnt < lp->lpAddrMax);
#endif
*lp->lpAddrNxt++ = val;
lp->lpAddrCnt++;
}
/*
If we get here it means that we've just added a new entry
to the pool. We better not be issuing an instruction since
all entries are supposed to have been added by that time.
*/
assert(issue == false);
return 0;
}
/*****************************************************************************
*
* Compute a conservative estimate of the size of each literal pool.
*/
void emitter::emitEstimateLitPools()
{
emitTotLPcount = 0;
#ifdef DEBUG
unsigned words = 0;
unsigned longs = 0;
unsigned addrs = 0;
#endif
/* Does it look like we might need to create a constant pool? */
if (emitEstLPwords || emitEstLPlongs || emitEstLPaddrs)
{
size_t curOffs;
insGroup * tempIG;
insGroup * nextIG;
insGroup * lastIG = NULL;
insGroup * bestIG = NULL;
unsigned bestWc = 0;
unsigned bestLc = 0;
unsigned bestAc = 0;
unsigned bestSz;
unsigned prevWc = 0;
unsigned prevLc = 0;
unsigned prevAc = 0;
unsigned prevSz;
unsigned bestMx = UINT_MAX;
unsigned need_bestmx = false;
unsigned need_bestmxw = false;
unsigned begOfsW = 0;
unsigned begOfsL = 0;
unsigned wordCnt = 0;
unsigned longCnt = 0;
unsigned addrCnt = 0;
unsigned litSize = 0;
unsigned endOffs;
unsigned maxOffs = UINT_MAX;
bool doneIG = false;
bool skipIG = false;
short * LPtabW = NULL;
short * LPnxtW = NULL;
long * LPtabL = NULL;
long * LPnxtL = NULL;
LPaddrDesc * LPtabA = NULL;
LPaddrDesc * LPnxtA = NULL;
/*
If the total estimated size of the entire method is less
than the max. distance for "medium" jumps, decrement the
"long" literal pool use counts for each jump marked as
long.
*/
#if !TGT_ARM
if (emitCurCodeOffset < -min(JMP_DIST_SMALL_MAX_NEG,
JCC_DIST_MIDDL_MAX_NEG) &&
emitCurCodeOffset < min(JMP_DIST_SMALL_MAX_POS,
JCC_DIST_MIDDL_MAX_POS))
{
instrDescJmp * jmp;
for (jmp = emitJumpList; jmp; jmp = jmp->idjNext)
{
insGroup * jmpIG;
if (jmp->idInsFmt == IF_JMP_TAB)
continue;
#if TGT_MIPSFP
assert( (jmp->idInsFmt == IF_LABEL) || (jmp->idInsFmt == IF_JR) || (jmp->idInsFmt == IF_JR_R) ||
(jmp->idInsFmt == IF_RR_O) || (jmp->idInsFmt == IF_R_O) || (jmp->idInsFmt == IF_O));
#elif TGT_MIPS32
assert( (jmp->idInsFmt == IF_LABEL) || (jmp->idInsFmt == IF_JR) || (jmp->idInsFmt == IF_JR_R) ||
(jmp->idInsFmt == IF_RR_O) || (jmp->idInsFmt == IF_R_O));
#else
assert(jmp->idInsFmt == IF_LABEL);
#endif
/* Get the group the jump is in */
jmpIG = jmp->idjIG;
/* Decrease the "long" litpool count of the group */
assert(jmpIG->igLPuseCntL > 0);
jmpIG->igLPuseCntL--;
emitEstLPlongs--;
}
#if TGT_SH3
all_jumps_shortened = 1;
#endif
/* Are there any litpool users left? */
if (!emitEstLPwords && !emitEstLPlongs && !emitEstLPaddrs)
goto DONE_LP;
}
else
{
#if TGT_SH3
all_jumps_shortened = 0;
#endif
}
#endif //TGT_ARM
#ifdef DEBUG
if (verbose)
{
printf("\nInstruction list before literal pools are added:\n\n");
emitDispIGlist(false);
}
/* Make sure our estimates were accurate */
unsigned wordChk;
unsigned longChk;
unsigned addrChk;
for (wordChk =
longChk =
addrChk = 0, tempIG = emitIGlist; tempIG; tempIG = tempIG->igNext)
{
wordChk += tempIG->igLPuseCntW;
longChk += tempIG->igLPuseCntL;
addrChk += tempIG->igLPuseCntA;
emitEstLPwords+=2;
emitEstLPlongs+=2;
// @TODO [REVISIT] [04/16/01] []:
// any lit pool can add a word for alignment.
// also can add a long for a jump over the litpool.
// here we pray there is not an avg of more than two lit pool per instr group.
}
assert(wordChk <= emitEstLPwords);
assert(longChk <= emitEstLPlongs);
assert(addrChk <= emitEstLPaddrs);
#else
for (tempIG = emitIGlist; tempIG; tempIG = tempIG->igNext)
{
emitEstLPwords+=2;
emitEstLPlongs+=2;
}
#endif
/* Allocate the arrays of the literal pool word/long entries */
LPtabW = LPnxtW = (short *)emitGetMem(roundUp(emitEstLPwords * sizeof(*LPtabW)));
LPtabL = LPnxtL = (long *)emitGetMem( emitEstLPlongs * sizeof(*LPtabL) );
LPtabA = LPnxtA = (LPaddrDesc*)emitGetMem( emitEstLPaddrs * sizeof(*LPtabA) );
/* We have not created any actual lit pools yet */
emitLitPoolList =
emitLitPoolLast = NULL;
/* Walk the group list, looking for lit pool use */
for (tempIG = emitIGlist, curOffs = litSize = bestSz = 0;;)
{
assert(lastIG == NULL || lastIG->igNext == tempIG);
/* Record the (possibly) updated group offset */
tempIG->igOffs = curOffs;
/* Get hold of the next group */
nextIG = tempIG->igNext;
/* Compute the offset of the group's end */
endOffs = tempIG->igOffs + tempIG->igSize;
//printf("\nConsider IG #%02u at %04X\n", tempIG->igNum, tempIG->igOffs);
//printf("bestsz is %x\n", bestSz);
/* Is the end of this group too far? */
int nextLitSize =
tempIG->igLPuseCntW * 2 + tempIG->igLPuseCntL * sizeof(int ) + tempIG->igLPuseCntA * sizeof(void*);
if (endOffs + litSize + nextLitSize > maxOffs)
//if (endOffs + litSize > maxOffs)
{
size_t offsAdj;
/* We must place a literal pool before this group */
if (!bestIG)
{
// Ouch - we'll have to jump over the literal pool
// since we have to place it here and there were
// no good places to put earlier. For now, we'll
// just set a flag on the liter pool (and bump its
// size), and we'll issue the jump just before we
// write out the literal pool contents.
skipIG = true;
bestIG = lastIG;
ALL_LP:
bestWc = wordCnt;
bestLc = longCnt;
bestAc = addrCnt;
bestSz = litSize;
bestMx = UINT_MAX;
//printf ("had to split %d %d %d %x!\n", bestWc, bestLc, bestAc, litSize);
}
assert(bestIG && ((bestIG->igFlags & IGF_END_NOREACH) || skipIG));
/* Append an LP right after "bestIG" */
//printf("lit placed after IG #%02u at %04X uses : WLA %d %d %d : maxOffs was %X\n", bestIG->igNum, bestIG->igOffs, bestWc, bestLc, bestAc, maxOffs);
//printf("lit size (bestsz) was %x, litsize+endoffs = %x endoffs = %x\n", bestSz, bestSz+bestIG->igOffs+bestIG->igSize, bestIG->igOffs+bestIG->igSize);
//printf("lit uses lpnxtW : %x\t lpnxtL : %x\t lpnxtA : %x\n", LPnxtW, LPnxtL, LPnxtA);
offsAdj = emitAddLitPool(bestIG,
skipIG, bestWc, &LPnxtW,
bestLc, &LPnxtL,
bestAc, &LPnxtA);
// Do we need to skip over the literal pool?
if (skipIG)
{
/* Reset the flag */
skipIG = false;
/* Update this group's and the current offset */
tempIG->igOffs += offsAdj;
}
else
{
/* Update the intervening group offsets */
while (bestIG != tempIG)
{
bestIG = bestIG->igNext;
bestIG->igOffs += offsAdj;
}
}
/* Update the total code size */
emitCurCodeOffset += offsAdj;
/* Update the current offset */
curOffs += offsAdj;
/* Update the outstanding/"best" LP ref values */
wordCnt -= bestWc; bestWc = 0;
longCnt -= bestLc; bestLc = 0;
addrCnt -= bestAc; bestAc = 0;
litSize -= bestSz; bestSz = 0;
/* if we've unloaded some litpool entries on bestIG but still */
/* need to put more before the current IG, then need a skip and loop back */
if (endOffs + litSize + nextLitSize > bestMx)
{
skipIG = true;
bestIG = lastIG;
goto ALL_LP;
}
maxOffs = bestMx; bestMx = UINT_MAX;
/* We've used up our "best" IG */
bestIG = NULL;
if (doneIG) goto DONE_LP;
}
#ifdef DEBUG
//printf("IG #%02u at %04X uses : WLA %d %d %d words %d longs %d\n", tempIG->igNum, tempIG->igOffs, tempIG->igLPuseCntW, tempIG->igLPuseCntL, tempIG->igLPuseCntA, wordCnt, longCnt);
//printf("IG #%02u at %04X uses : WLA %d %d %d maxoffs %x bestMx %x\n", tempIG->igNum, tempIG->igOffs, tempIG->igLPuseCntW, tempIG->igLPuseCntL, tempIG->igLPuseCntA, maxOffs, bestMx);
//printf("litsize : %x\n", litSize);
words += tempIG->igLPuseCntW;
longs += tempIG->igLPuseCntL;
addrs += tempIG->igLPuseCntA;
#endif
/* Does this group need any LP entries? */
prevWc = wordCnt;
prevLc = longCnt;
prevAc = addrCnt;
prevSz = litSize;
if (tempIG->igLPuseCntW)
{
if (!wordCnt || !bestWc || need_bestmx || need_bestmxw)
{
unsigned tmpOffs;
/* This is the first "word" LP use */
tmpOffs = tempIG->igOffs;
#if SCHEDULER
if (!emitComp->opts.compSchedCode)
#endif
tmpOffs += tempIG->igLPuse1stW;
/* Figure out the farthest acceptable offset */
tmpOffs += LIT_POOL_MAX_OFFS_WORD - 2*INSTRUCTION_SIZE;
/* Update the max. offset */
if (!wordCnt)
{
if (maxOffs > tmpOffs)
maxOffs = tmpOffs;
}
if (need_bestmx || need_bestmxw)
//else
{
if (bestMx > tmpOffs)
bestMx = tmpOffs;
need_bestmx = false;
need_bestmxw = false;
}
}
wordCnt += tempIG->igLPuseCntW;
litSize += tempIG->igLPuseCntW * 2;
//bestSz += tempIG->igLPuseCntW * 2;
}
if (tempIG->igLPuseCntL || tempIG->igLPuseCntA)
{
if ((!longCnt && !addrCnt) || (!bestLc && !bestAc) || need_bestmx)
{
unsigned tmpOffs;
/* This is the first long/addr LP use */
tmpOffs = tempIG->igOffs;
int firstuse = INT_MAX;
if (tempIG->igLPuseCntL)
firstuse = tempIG->igLPuse1stL;
if (tempIG->igLPuseCntA)
firstuse = min (firstuse, tempIG->igLPuse1stA);
#if SCHEDULER
if (!emitComp->opts.compSchedCode)
#endif
tmpOffs += firstuse;
/* Figure out the farthest acceptable offset */
tmpOffs += LIT_POOL_MAX_OFFS_LONG - 2*INSTRUCTION_SIZE;
/* Update the max. offset */
if (!longCnt && !addrCnt)
{
if (maxOffs > tmpOffs)
maxOffs = tmpOffs;
}
if (need_bestmx)
{
if (bestMx > tmpOffs)
bestMx = tmpOffs;
need_bestmx = false;
}
}
longCnt += tempIG->igLPuseCntL;
litSize += tempIG->igLPuseCntL * sizeof(int );
//bestSz += tempIG->igLPuseCntL * sizeof(int );
addrCnt += tempIG->igLPuseCntA;
litSize += tempIG->igLPuseCntA * sizeof(void*);
//bestSz += tempIG->igLPuseCntA * sizeof(void*);
}
/* Is the end of this group unreachable? */
if (tempIG->igFlags & IGF_END_NOREACH)
{
/* Looks like the best candidate so far */
bestIG = tempIG;
/* Remember how much we can cram into the best candidate */
bestWc = wordCnt;
bestLc = longCnt;
bestAc = addrCnt;
//bestSz = 0;
bestSz = litSize;
bestMx = UINT_MAX;
need_bestmx = true;
need_bestmxw = true;
}
/* Is this the last group? */
//printf("IG #%02u at %04X uses : WLA %d %d %d maxoffs %x bestMx %x\n", tempIG->igNum, tempIG->igOffs, tempIG->igLPuseCntW, tempIG->igLPuseCntL, tempIG->igLPuseCntA, maxOffs, bestMx);
if (!nextIG)
{
assert(bestIG == tempIG);
/* Is there any need for a literal pool? */
if (wordCnt || longCnt || addrCnt)
{
/* Prevent endless looping */
if (doneIG)
break;
doneIG = true;
bestWc = wordCnt;
bestLc = longCnt;
bestAc = addrCnt;
bestSz = litSize;
goto ALL_LP;
}
/* We're all done */
break;
}
/* Update the current offset and continue with the next group */
curOffs += tempIG->igSize;
lastIG = tempIG;
tempIG = nextIG;
}
DONE_LP:;
#ifdef DEBUG
if (verbose)
{
printf("Est word need = %3u, alloc = %3u, used = %3u\n", emitEstLPwords, words, LPnxtW - LPtabW);
printf("Est long need = %3u, alloc = %3u, used = %3u\n", emitEstLPlongs, longs, LPnxtL - LPtabL);
printf("Est addr need = %3u, alloc = %3u, used = %3u\n", emitEstLPaddrs, addrs, LPnxtA - LPtabA);
}
#endif
#ifdef DEBUG
if (verbose)
{
printf("\nInstruction list after literal pools have been added:\n\n");
emitDispIGlist(false);
}
assert(words <= emitEstLPwords && emitEstLPwords + LPtabW >= LPnxtW);
assert(longs <= emitEstLPlongs && emitEstLPlongs + LPtabL >= LPnxtL);
assert(addrs <= emitEstLPaddrs && emitEstLPaddrs + LPtabA >= LPnxtA);
#endif
}
/* Make sure all the IG offsets are up-to-date */
emitCheckIGoffsets();
}
/*****************************************************************************
*
* Finalize the size and contents of each literal pool.
*/
void emitter::emitFinalizeLitPools()
{
litPool * curLP;
insGroup * litIG;
instrDescLPR* lprID;
insGroup * thisIG;
size_t offsIG;
/* Do we have any literal pools? */
if (!emitTotLPcount)
return;
#ifdef DEBUG
if (verbose)
{
printf("\nInstruction list before final literal pool allocation:\n\n");
emitDispIGlist(false);
}
emitCheckIGoffsets();
#endif
#if SMALL_DIRECT_CALLS
/* Do we already know where the code for this method will end up? */
if (emitLPmethodAddr)
emitShrinkShortCalls();
#endif
/* Get hold of the first literal pool and its group */
curLP = emitLitPoolList; assert(curLP);
litIG = curLP->lpIG;
lprID = emitLPRlist;
/* Walk the instruction groups to create the literal pool contents */
for (thisIG = emitIGlist, offsIG = 0;
thisIG;
thisIG = thisIG->igNext)
{
thisIG->igOffs = offsIG;
/* Does this group have any lit pool entries? */
if (thisIG->igLPuseCntW ||
thisIG->igLPuseCntL ||
thisIG->igLPuseCntA)
{
/* Walk the list of instructions that reference the literal pool */
#ifdef DEBUG
unsigned wc = 0;
unsigned lc = 0;
unsigned ac = 0;
#endif
do
{
#if TGT_SH3
#ifdef DEBUG
emitDispIns(lprID, false, true, false, 0);
#endif
// maybe this was because of a jmp instruction
if (lprID->idlIG != thisIG)
{
unsigned cnt = thisIG->igInsCnt;
BYTE * ins = thisIG->igData;
instrDesc* id;
#ifdef DEBUG
_flushall();
#endif
do
{
instrDesc * id = (instrDesc *)ins;
//emitDispIns(id, false, true, false, 0);
if (id->idInsFmt == IF_LABEL)
{
/* Is the jump "very long" ? */
if (((instrDescJmp*)lprID)->idjShort == false &&
((instrDescJmp*)lprID)->idjMiddle == false)
{
/* Add a label entry to the current LP */
#ifdef DEBUG
lc++;
#endif
}
}
ins += emitSizeOfInsDsc(id);
}
while (--cnt);
break;
thisIG = thisIG->igNext;
while (!(thisIG->igLPuseCntW || thisIG->igLPuseCntL || thisIG->igLPuseCntA))
thisIG = thisIG->igNext;
continue;
}
#endif
assert(lprID && lprID->idlIG == thisIG);
switch (lprID->idInsFmt)
{
case IF_RWR_LIT:
#ifdef DEBUG
/* Just to make sure the counts agree */
if (emitGetInsLPRtyp(lprID) == CT_INTCNS)
{
if (emitDecodeSize(lprID->idOpSize) == 2)
wc++;
else
lc++;
}
else
{
ac++;
}
#endif
#if SMALL_DIRECT_CALLS
/* Ignore calls that have been made direct */
if (lprID->idIns == DIRECT_CALL_INS)
break;
#endif
/* Add an entry for the operand to the current LP */
emitAddLitPoolEntry(curLP, lprID, false);
break;
case IF_LABEL:
/* Is the jump "very long" ? */
if (((instrDescJmp*)lprID)->idjShort == false &&
((instrDescJmp*)lprID)->idjMiddle == false)
{
/* Add a label entry to the current LP */
#ifdef DEBUG
lc++;
#endif
assert(!"add long jump label address to litpool");
}
break;
#ifdef DEBUG
default:
assert(!"unexpected instruction in LP list");
#endif
}
lprID = lprID->idlNext;
}
while (lprID && lprID->idlIG == thisIG);
#ifdef DEBUG
assert(thisIG->igLPuseCntW == wc);
//assert(thisIG->igLPuseCntL == lc);
assert(thisIG->igLPuseCntA == ac);
#endif
}
/* Is the current literal pool supposed to go after this group? */
if (litIG == thisIG)
{
unsigned begOffs;
unsigned jmpSize;
unsigned wordCnt;
unsigned longCnt;
unsigned addrCnt;
assert(curLP && curLP->lpIG == thisIG);
/* Subtract the estimated pool size from the group's size */
thisIG->igSize -= curLP->lpSizeEst; assert((int)thisIG->igSize >= 0);
/* Compute the starting offset of the pool */
begOffs = offsIG + thisIG->igSize;
/* Adjust by the size of the "skip over LP" jump, if present */
jmpSize = 0;
if (curLP->lpJumpIt)
{
jmpSize = emitLPjumpOverSize(curLP);
begOffs += jmpSize;
}
/* Get hold of the counts */
wordCnt = curLP->lpWordCnt;
longCnt = curLP->lpLongCnt;
addrCnt = curLP->lpAddrCnt;
/* Do we need to align the first long/addr? */
curLP->lpPadding =
curLP->lpPadFake = false;
if ((begOffs & 3) && (longCnt || addrCnt))
{
/* We'll definitely need one word of padding */
curLP->lpPadding = true;
/* Do we have any word-sized entries? */
if (!wordCnt)
{
/* No, we'll have to pad by adding a "fake" word */
curLP->lpPadFake = true;
wordCnt++;
}
}
/* Compute the final (accurate) size */
curLP->lpSize = wordCnt * 2 +
longCnt * 4 +
addrCnt * 4;
/* Make sure the original estimate wasn't too low */
assert(curLP->lpSize <= curLP->lpSizeEst);
/* Record the pool's offset within the method */
curLP->lpOffs = begOffs;
/* Add the actual size to the group's size */
thisIG->igSize += curLP->lpSize + jmpSize;
/* Move to the next literal pool, if any */
curLP = curLP->lpNext;
litIG = curLP ? curLP->lpIG : NULL;
}
offsIG += thisIG->igSize;
}
/* We should have processed all the literal pools */
assert(curLP == NULL);
assert(litIG == NULL);
assert(lprID == NULL);
/* Update the total code size of the method */
emitTotalCodeSize = offsIG;
/* Make sure all the IG offsets are up-to-date */
emitCheckIGoffsets();
}
/*****************************************************************************/
#if SMALL_DIRECT_CALLS
/*****************************************************************************
*
* Convert as many calls as possible into the direct pc-relative variety.
*/
void emitter::emitShrinkShortCalls()
{
litPool * curLP;
insGroup * litIG;
unsigned litIN;
instrDescLPR* lprID;
size_t ofAdj;
bool shrnk;
bool swapf;
/* Do we have any candidate calls at all? */
#ifndef TGT_SH3
if (!emitTotDCcount)
return;
#endif
/* This is to make recursive calls find their target address */
emitCodeBlock = emitLPmethodAddr;
/* Get hold of the first literal pool and the group it belongs to */
curLP = emitLitPoolList; assert(curLP);
litIG = curLP->lpIG;
litIN = litIG->igNum;
/* Remember whether we shrank any calls at all */
shrnk = false;
/* Remember whether to swap any calls to fill branch-delay slots */
swapf = false;
#if TGT_SH3
shrnk = true; // always need to do delay slots on sh3
swapf = true;
#endif
/* Walk the list of instructions that reference the literal pool */
for (lprID = emitLPRlist; lprID; lprID = lprID->idlNext)
{
instrDesc * nxtID;
BYTE * srcAddr;
BYTE * dstAddr;
int difAddr;
/* Does this instruction reference a new literal pool? */
while (lprID->idlIG->igNum > litIN)
{
/* Move to the next literal pool */
curLP = curLP->lpNext; assert(curLP);
litIG = curLP->lpIG;
litIN = litIG->igNum;
}
/* We're only interested in direct-via-register call sequences */
if (lprID->idInsFmt != IF_RWR_LIT)
continue;
if (lprID->idIns != LIT_POOL_LOAD_INS)
continue;
if (lprID->idlCall == NULL)
continue;
switch (emitGetInsLPRtyp(lprID))
{
case CT_DESCR:
#if defined(BIRCH_SP2) && TGT_SH3
case CT_RELOCP:
#endif
case CT_USER_FUNC:
break;
default:
continue;
}
/* Here we have a direct call via a register */
nxtID = lprID->idlCall;
assert(nxtID->idIns == INDIRECT_CALL_INS);
assert(nxtID->idRegGet() == lprID->idRegGet());
/* Assume the call will not be short */
lprID->idlCall = NULL;
/* Compute the address from where the call will originate */
srcAddr = emitDirectCallBase(emitCodeBlock + litIG-> igOffs
+ lprID->idlOffs);
/* Ask for the address of the target and see how far it is */
#if defined(BIRCH_SP2) && TGT_SH3
if (~0 != (unsigned) nxtID->idAddr.iiaMethHnd)
{
OptPEReader *oper = &((OptJitInfo*)emitComp->info.compCompHnd)->m_PER;
dstAddr = (BYTE *)oper->m_rgFtnInfo[(unsigned)nxtID->idAddr.iiaMethHnd].m_pNative;
}
else
dstAddr = 0;
#else
# ifdef BIRCH_SP2
assert (0); // you need to guarantee iiaMethHnd if you want this to work <tanj>
# endif
dstAddr = emitMethodAddr(lprID);
#endif
/* If the target address isn't known, there isn't much we can do */
if (!dstAddr)
continue;
// printf("Direct call: %08X -> %08X , dist = %d\n", srcAddr, dstAddr, dstAddr - srcAddr);
/* Compute the distance and see if it's in range */
difAddr = dstAddr - srcAddr;
if (difAddr < CALL_DIST_MAX_NEG)
continue;
if (difAddr > CALL_DIST_MAX_POS)
continue;
/* The call can be made short */
lprID->idlCall = nxtID;
/* Change the load-address instruction to a direct call */
lprID->idIns = DIRECT_CALL_INS;
/* The indirect call instruction won't generate any code */
nxtID->idIns = INS_ignore;
/* Update the group's size [ISSUE: may have to use nxtID's group] */
lprID->idlIG->igSize -= INSTRUCTION_SIZE;
/* Remember that we've shrunk at least one call */
shrnk = true;
/* Is there a "nop" filling the branch-delay slot? */
if (Compiler::instBranchDelay(DIRECT_CALL_INS))
{
instrDesc * nopID;
/* Get hold of the instruction that follows the call */
nopID = (instrDesc*)((BYTE*)nxtID + emitSizeOfInsDsc(nxtID));
/* Do we have a (branch-delay) nop? */
if (nopID->idIns == INS_nop)
{
/* We'll get rid of the nop later (see next loop below) */
lprID->idSwap = true;
swapf = true;
}
}
}
/* We should have processed all the literal pools */
// maybe there are lit pools after this that are now empty
// (could have been used by jumps that are now long)
//assert(curLP->lpNext == NULL);
//assert(lprID == NULL);
/* Did we manage to shrink any calls? */
if (shrnk)
{
insGroup * thisIG;
size_t offsIG;
for (thisIG = emitIGlist, offsIG = 0;
thisIG;
thisIG = thisIG->igNext)
{
instrDesc * id;
int cnt;
/* Update the group's offset */
thisIG->igOffs = offsIG;
/* Does this group have any address entries? */
if (!thisIG->igLPuseCntA)
goto NXT_IG;
/* Did we find any branch-delay slots that can be eliminated? */
if (!swapf)
goto NXT_IG;
/*
Walk the instructions of the group, looking for
the following sequence:
<any_ins>
direct_call
nop
If we find it, we swap the first instruction
with the call and zap the nop.
*/
id = (instrDesc *)thisIG->igData;
cnt = thisIG->igInsCnt - 2;
while (cnt > 0)
{
instrDesc * nd;
/* Get hold of the instruction that follows */
nd = (instrDesc*)((BYTE*)id + emitSizeOfInsDsc(id));
/* Is the following instruction a direct call? */
if (nd->idIns == DIRECT_CALL_INS && nd->idSwap)
{
instrDesc * n1;
instrDesc * n2;
/* Skip over the indirect call */
n1 = (instrDesc*)((BYTE*)nd + emitSizeOfInsDsc(nd));
assert(n1->idIns == INS_ignore);
/* Get hold of the "nop" that is known to follow */
n2 = (instrDesc*)((BYTE*)n1 + emitSizeOfInsDsc(n1));
assert(n2->idIns == INS_nop);
/* The call was marked as "swapped" only temporarily */
nd->idSwap = false;
/* Are we scheduling "for real" ? */
#if SCHEDULER
if (emitComp->opts.compSchedCode)
{
/* Move the "nop" into the branch-delay slot */
n1->idIns = INS_nop;
n2->idIns = INS_ignore;
}
else
#endif
{
if (!emitInsDepends(nd, id))
{
/* Swap the call with the previous instruction */
id->idSwap = true;
/* Zap the branch-delay slot (the "nop") */
n2->idIns = INS_ignore;
/* Update the group's size */
thisIG->igSize -= INSTRUCTION_SIZE;
}
}
}
#if TGT_SH3
else if (nd->idIns == INS_jsr)
{
instrDesc * nop;
nop = (instrDesc*)((BYTE*)nd + emitSizeOfInsDsc(nd));
assert(nop->idIns == INS_nop);
if (!emitInsDepends(nd, id))
{
/* Swap the call with the previous instruction */
id->idSwap = true;
/* Zap the branch-delay slot (the "nop") */
nop->idIns = INS_ignore;
/* Update the group's size */
thisIG->igSize -= INSTRUCTION_SIZE;
}
}
#endif
/* Continue with the next instruction */
id = nd;
cnt--;
}
NXT_IG:
/* Update the running offset */
offsIG += thisIG->igSize;
}
assert(emitTotalCodeSize); emitTotalCodeSize = offsIG;
}
/* Make sure all the IG offsets are up-to-date */
emitCheckIGoffsets();
}
/*****************************************************************************/
#endif//SMALL_DIRECT_CALLS
/*****************************************************************************
*
* Output the contents of the next literal pool.
*/
BYTE * emitter::emitOutputLitPool(litPool *lp, BYTE *cp)
{
unsigned wordCnt = lp->lpWordCnt;
short * wordPtr = lp->lpWordTab;
unsigned longCnt = lp->lpLongCnt;
long * longPtr = lp->lpLongTab;
unsigned addrCnt = lp->lpAddrCnt;
LPaddrDesc * addrPtr = lp->lpAddrTab;
size_t curOffs;
/* Bail of no entry ended up being used in this pool */
if ((wordCnt|longCnt|addrCnt) == 0)
return cp;
/* Compute the current code offset */
curOffs = emitCurCodeOffs(cp);
/* Do we need to jump over the literal pool? */
if (lp->lpJumpIt)
{
/* Reserve space for the jump over the pool */
curOffs += emitLPjumpOverSize(lp);
}
#if SCHEDULER
bool addPad = false;
/* Has the offset of this LP changed? */
if (lp->lpOffs != curOffs)
{
LPcrefDesc * ref;
size_t oldOffs = lp->lpOffs;
size_t tmpOffs = curOffs;
assert(emitComp->opts.compSchedCode);
/* Has the literal pool moved by an unaligned amount? */
if ((curOffs - oldOffs) & 2)
{
/* Did we originally think we would need padding? */
if (lp->lpPadding)
{
/*
OK, we thought we'd need padding but with the new LP
position that's not the case any more. If the padding
value is an unused one, simply get rid of it; if it
contains a real word entry, we'll have to add padding
in front of the LP to keep things aligned, as moving
the initial word entry is too difficult at this point.
*/
if (lp->lpPadFake)
{
/* Padding no longer needed, just get rid of it */
lp->lpPadding =
lp->lpPadFake = false;
}
else
{
/*
This is the unfortunate scenario described above;
we thought we'd need padding and we achieved this
by sticking the first word entry in front of all
the dword entries. It's simply too hard to move
that initial word someplace else at this point,
so instead we just add another pad word. Sigh.
*/
ADD_PAD:
/* Come here to add a pad word in front of the LP */
addPad = true; lp->lpSize += 2;
/* Update the offset and see if it's still different */
curOffs += 2;
if (curOffs == oldOffs)
goto DONE_MOVE;
}
}
else
{
/*
There is currently no padding. If there are any
entries that need to be aligned, we'll have to
add padding now, lest they end up mis-aligned.
*/
assert((oldOffs & 2) == 0);
assert((curOffs & 2) != 0);
if (longCnt || addrCnt)
{
lp->lpPadding =
lp->lpPadFake = true;
/* Does the padding take up all the savings? */
if (oldOffs == curOffs + sizeof(short))
{
/* Nothing really changed, no need to patch */
goto NO_PATCH;
}
tmpOffs += sizeof(short);
}
}
}
/* Patch all issued instructions that reference this LP */
for (ref = lp->lpRefs; ref; ref = ref->lpcNext)
emitPatchLPref(ref->lpcAddr, oldOffs, tmpOffs);
NO_PATCH:
/* Update the offset of the LP */
lp->lpOffs = curOffs; assert(oldOffs != curOffs);
}
DONE_MOVE:
#else
assert(lp->lpOffs == curOffs);
#endif
/* Do we need to jump over the literal pool? */
if (lp->lpJumpIt)
{
#ifdef DEBUG
/* Remember the code offset so that we can verify the jump size */
unsigned jo = emitCurCodeOffs(cp);
#endif
/* Skip over the literal pool */
#ifdef DEBUG
emitDispIG = lp->lpIG->igNext; // for instruction display purposes
#endif
#if TGT_SH3
if (lp->lpJumpSmall)
{
cp += emitOutputWord(cp, 0x0009);
}
#endif
cp = emitOutputFwdJmp(cp, lp->lpSize, lp->lpJumpSmall,
lp->lpJumpMedium);
/* Make sure the issued jump had the expected size */
#ifdef DEBUG
assert(jo + emitLPjumpOverSize(lp) == emitCurCodeOffs(cp));
#endif
}
#ifdef DEBUG
if (disAsm) printf("\n; Literal pool %02u:\n", lp->lpNum);
#endif
#ifdef DEBUG
unsigned lpBaseOffs = emitCurCodeOffs(cp);
#endif
#if SCHEDULER
/* Do we need to insert additional padding? */
if (addPad)
{
/* This can only happen when the scheduler is enabled */
assert(emitComp->opts.compSchedCode);
#ifdef DEBUG
if (disAsm)
{
emitDispInsOffs(emitCurCodeOffs(cp), dspGCtbls);
printf(EMIT_DSP_INS_NAME "0 ; pool alignment (due to scheduling)\n", ".data.w");
}
#endif
cp += emitOutputWord(cp, 0);
}
#endif
/* Output the contents of the literal pool */
if (lp->lpPadding)
{
#ifdef DEBUG
if (disAsm) emitDispInsOffs(emitCurCodeOffs(cp), dspGCtbls);
#endif
/* Are we padding with the first word entry? */
if (lp->lpPadFake)
{
#if ! SCHEDULER
assert(wordCnt == 0);
#endif
#ifdef DEBUG
if (disAsm) printf(EMIT_DSP_INS_NAME "0 ; pool alignment\n", ".data.w");
#endif
cp += emitOutputWord(cp, 0);
}
else
{
assert(wordCnt != 0);
#ifdef DEBUG
if (disAsm) printf(EMIT_DSP_INS_NAME "%d\n", ".data.w", *wordPtr);
#endif
cp += emitOutputWord(cp, *wordPtr);
wordPtr++;
wordCnt--;
}
}
/* Output any long entries */
while (longCnt)
{
int val = *longPtr;
#ifdef DEBUG
if (disAsm)
{
emitDispInsOffs(emitCurCodeOffs(cp), dspGCtbls);
printf(EMIT_DSP_INS_NAME "%d\n", ".data.l", val);
}
#endif
assert(longPtr < lp->lpLongNxt);
cp += emitOutputLong(cp, val);
longPtr++;
longCnt--;
}
/* Output any addr entries */
while (addrCnt)
{
gtCallTypes addrTyp = addrPtr->lpaTyp;
void * addrHnd = addrPtr->lpaHnd;
void * addr;
/* What kind of an address do we have here? */
switch (addrTyp)
{
InfoAccessType accessType = IAT_VALUE;
#ifdef BIRCH_SP2
case CT_RELOCP:
addr = (BYTE*)addrHnd;
// record that this addr must be in the .reloc section
emitCmpHandle->recordRelocation((void**)cp, IMAGE_REL_BASED_HIGHLOW);
break;
#endif
case CT_CLSVAR:
addr = (BYTE *)emitComp->eeGetFieldAddress(addrHnd);
if (!addr)
NO_WAY("could not obtain address of static field");
break;
case CT_HELPER:
assert(!"ToDo");
break;
case CT_DESCR:
addr = (BYTE*)emitComp->eeGetMethodEntryPoint((CORINFO_METHOD_HANDLE)addrHnd, &accessType);
assert(accessType == IAT_PVALUE);
break;
case CT_INDIRECT:
assert(!"this should never happen");
case CT_USER_FUNC:
if (emitComp->eeIsOurMethod((CORINFO_METHOD_HANDLE)addrHnd))
{
/* Directly recursive call */
addr = emitCodeBlock;
}
else
{
addr = (BYTE*)emitComp->eeGetMethodPointer((CORINFO_METHOD_HANDLE)addrHnd, &accessType);
assert(accessType == IAT_VALUE);
}
break;
default:
assert(!"unexpected call type");
}
#ifdef DEBUG
if (disAsm)
{
emitDispInsOffs(emitCurCodeOffs(cp), dspGCtbls);
printf(EMIT_DSP_INS_NAME, ".data.l");
printf("0x%08X ; ", addr);
if (addrTyp == CT_CLSVAR)
{
printf("&");
emitDispClsVar((CORINFO_FIELD_HANDLE) addrHnd, 0);
}
else
{
const char * methodName;
const char * className;
printf("&");
methodName = emitComp->eeGetMethodName((CORINFO_METHOD_HANDLE) addrHnd, &className);
if (className == NULL)
printf("'%s'", methodName);
else
printf("'%s.%s'", className, methodName);
}
printf("\n");
}
#endif
assert(addrPtr < lp->lpAddrNxt);
cp += emitOutputLong(cp, (int)addr);
addrPtr++;
addrCnt--;
}
/* Output any word entries that may remain */
while (wordCnt)
{
int val = *wordPtr;
#ifdef DEBUG
if (disAsm)
{
emitDispInsOffs(emitCurCodeOffs(cp), dspGCtbls);
printf(EMIT_DSP_INS_NAME "%d\n", ".data.w", val);
}
#endif
assert(wordPtr < lp->lpWordNxt);
cp += emitOutputWord(cp, val);
wordPtr++;
wordCnt--;
}
/* Make sure we've generated the exact right number of entries */
assert(wordPtr == lp->lpWordNxt);
assert(longPtr == lp->lpLongNxt);
assert(addrPtr == lp->lpAddrNxt);
/* Make sure the size matches our expectations */
assert(lpBaseOffs + lp->lpSize == emitCurCodeOffs(cp));
return cp;
}
/*****************************************************************************/
#if SCHEDULER
/*****************************************************************************
*
* Record a reference to a literal pool entry so that the distance can be
* updated if the literal pool moves due to scheduling.
*/
struct LPcrefDesc
{
LPcrefDesc * lpcNext; // next ref to this literal pool
void * lpcAddr; // address of reference
};
void emitter::emitRecordLPref(litPool *lp, BYTE *dst)
{
LPcrefDesc * ref;
assert(emitComp->opts.compSchedCode);
/* Allocate a reference descriptor and add it to the list */
ref = (LPcrefDesc *)emitGetMem(sizeof(*ref));
ref->lpcAddr = dst;
ref->lpcNext = lp->lpRefs;
lp->lpRefs = ref;
}
/*****************************************************************************/
#endif//SCHEDULER
/*****************************************************************************/
#endif//EMIT_USE_LIT_POOLS
/*****************************************************************************/
/*****************************************************************************
*
* Return the allocated size (in bytes) of the given instruction descriptor.
*/
size_t emitter::emitSizeOfInsDsc(instrDesc *id)
{
if (emitIsTinyInsDsc(id))
return TINY_IDSC_SIZE;
if (emitIsScnsInsDsc(id))
{
return id->idInfo.idLargeCns ? sizeof(instrBaseCns)
: SCNS_IDSC_SIZE;
}
assert((unsigned)id->idInsFmt < emitFmtCount);
switch (emitFmtToOps[id->idInsFmt])
{
case ID_OP_NONE:
break;
case ID_OP_JMP:
return sizeof(instrDescJmp);
case ID_OP_CNS:
return emitSizeOfInsDsc((instrDescCns *)id);
case ID_OP_DSP:
return emitSizeOfInsDsc((instrDescDsp *)id);
case ID_OP_DC:
return emitSizeOfInsDsc((instrDescDspCns*)id);
case ID_OP_SCNS:
break;
case ID_OP_CALL:
if (id->idInfo.idLargeCall)
{
/* Must be a "fat" indirect call descriptor */
return sizeof(instrDescCIGCA);
}
assert(id->idInfo.idLargeCns == false);
assert(id->idInfo.idLargeDsp == false);
break;
case ID_OP_SPEC:
#if EMIT_USE_LIT_POOLS
switch (id->idInsFmt)
{
case IF_RWR_LIT:
return sizeof(instrDescLPR);
}
#endif // EMIT_USE_LIT_POOLS
assert(!"unexpected 'special' format");
default:
assert(!"unexpected instruction descriptor format");
}
return sizeof(instrDesc);
}
/*****************************************************************************/
#ifdef DEBUG
/*****************************************************************************
*
* Return a string that represents the given register.
*/
const char * emitter::emitRegName(emitRegs reg, int size, bool varName)
{
static
char rb[128];
assert(reg < SR_COUNT);
// CONSIDER: Make the following work just using a code offset
const char * rn = emitComp->compRegVarName((regNumber)reg, varName);
// assert(size == EA_GCREF || size == EA_BYREF || size == EA_4BYTE);
return rn;
}
/*****************************************************************************
*
* Display a static data member reference.
*/
void emitter::emitDispClsVar(CORINFO_FIELD_HANDLE hand, int offs, bool reloc)
{
if (varNames)
{
const char * clsn;
const char * memn;
memn = emitComp->eeGetFieldName(hand, &clsn);
printf("'%s.%s", clsn, memn);
if (offs) printf("%+d", offs);
printf("'");
}
else
{
printf("classVar[%08X]", hand);
}
}
/*****************************************************************************
*
* Display a stack frame reference.
*/
void emitter::emitDispFrameRef(int varx, int offs, int disp, bool asmfm)
{
int addr;
bool bEBP;
assert(emitComp->lvaDoneFrameLayout);
addr = emitComp->lvaFrameAddress(varx, &bEBP) + disp; assert((int)addr >= 0);
printf("@(%u,%s)", addr, bEBP ? "fp" : "sp");
if (varx >= 0 && varNames)
{
Compiler::LclVarDsc*varDsc;
const char * varName;
assert((unsigned)varx < emitComp->lvaCount);
varDsc = emitComp->lvaTable + varx;
varName = emitComp->compLocalVarName(varx, offs);
if (varName)
{
printf("'%s", varName);
if (disp < 0)
printf("-%d", -disp);
else if (disp > 0)
printf("+%d", +disp);
printf("'");
}
}
}
/*****************************************************************************
*
* Display an indirection (possibly auto-inc/dec).
*/
void emitter::emitDispIndAddr(emitRegs base,
bool dest,
bool autox,
int disp)
{
if (dest)
{
printf("@%s%s", autox ? "-" : "", emitRegName(base));
}
else
{
printf("@%s%s", emitRegName(base), autox ? "+" : "");
}
}
#endif // DEBUG
#endif//TGT_RISC
/*****************************************************************************/
| 65,787 | 20,266 |
#include <cmath>
#include "src/core/hpcp.h"
#include "src/core/test/gtest_extras.h"
using namespace musher::core;
/**
* @brief Test Zero inputs
*
*/
TEST(HPCP, TestZeros) {
std::vector<double> actual_hpcp;
std::vector<double> frequencies(10);
std::vector<double> magnitudes(10);
actual_hpcp = HPCP(frequencies, magnitudes);
std::vector<double> expected_hpcp(12);
EXPECT_VEC_EQ(actual_hpcp, expected_hpcp);
}
/**
* @brief Test submediant position
* @details Make sure that the submediant of a key based on 440 is in the
* correct location (submediant was randomly selected from all the tones)
*
*/
TEST(HPCP, SubmediantPosition) {
std::vector<double> actual_hpcp;
int tonic = 440;
double submediant = tonic * std::pow(2, (9. / 12.));
std::vector<double> submediant_freqs = { submediant };
std::vector<double> magnitudes = { 1 };
actual_hpcp = HPCP(submediant_freqs, magnitudes);
std::vector<double> expected_hpcp = { 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0. };
EXPECT_VEC_EQ(actual_hpcp, expected_hpcp);
}
/**
* @brief Test harmonics
*
*/
TEST(HPCP, Harmonics) {
std::vector<double> actual_hpcp;
double tone = 100.;
std::vector<double> frequencies = { tone, tone * 2, tone * 3, tone * 4 };
std::vector<double> magnitudes(4, 1.);
int harmonics = 3;
bool band_preset = false;
double min_frequency = 50.0;
double max_frequency = 500.0;
actual_hpcp = HPCP(frequencies, magnitudes, 12, 440.0, harmonics, band_preset, 500.0, min_frequency, max_frequency,
"squared cosine", 1.0, false);
std::vector<double> expected_hpcp = { 0., 0., 0., 0.1340538263, 0., 0.2476127148, 0., 0., 0., 0., 1., 0. };
EXPECT_VEC_NEAR(actual_hpcp, expected_hpcp, 1e-4);
}
/**
* @brief Test max shifted
* @details Tests whether a HPCP reading with only the dominant semitone
* activated is correctly shifted so that the dominant is at the position 0
*
*/
TEST(HPCP, MaxShifted) {
std::vector<double> actual_hpcp;
int tonic = 440;
double dominant = tonic * std::pow(2, (7. / 12.));
std::vector<double> dominant_freqs = { dominant };
std::vector<double> magnitudes = { 1 };
bool max_shifted = true;
actual_hpcp =
HPCP(dominant_freqs, magnitudes, 12, 440.0, 0, true, 500.0, 40.0, 5000.0, "squared cosine", 1.0, max_shifted);
std::vector<double> expected_hpcp = { 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0. };
EXPECT_VEC_EQ(actual_hpcp, expected_hpcp);
}
/**
* @brief Test low frequency
*
*/
TEST(HPCP, LowFrequency) {
std::vector<double> actual_hpcp;
std::vector<double> frequencies = { 99 };
std::vector<double> magnitudes = { 1 };
double min_frequency = 100.0;
double max_frequency = 1000.0;
actual_hpcp = HPCP(frequencies, magnitudes, 12, 440.0, 0, true, 500.0, min_frequency, max_frequency, "squared cosine",
1.0, false);
std::vector<double> expected_hpcp = { 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0. };
EXPECT_VEC_EQ(actual_hpcp, expected_hpcp);
}
/**
* @brief Test high frequency
*
*/
TEST(HPCP, HighFrequency) {
std::vector<double> actual_hpcp;
std::vector<double> frequencies = { 1001 };
std::vector<double> magnitudes = { 1 };
double min_frequency = 100.0;
double max_frequency = 1000.0;
actual_hpcp = HPCP(frequencies, magnitudes, 12, 440.0, 0, true, 500.0, min_frequency, max_frequency, "squared cosine",
1.0, false);
std::vector<double> expected_hpcp = { 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0. };
EXPECT_VEC_EQ(actual_hpcp, expected_hpcp);
}
/**
* @brief Test too small min range error
*
*/
TEST(HPCP, TooSmallMinRangeError) {
std::vector<double> actual_hpcp;
std::vector<double> frequencies = {};
std::vector<double> magnitudes = {};
double band_split_frequency = 200.0;
double min_frequency = 1.0;
EXPECT_THROW(
{
try {
actual_hpcp = HPCP(frequencies, magnitudes, 12, 440.0, 0, true, band_split_frequency, min_frequency, 1000.0,
"squared cosine", 1.0, false);
} catch (const std::runtime_error& e) {
/* This tests if the error message is equal */
EXPECT_STREQ("HPCP: Low band frequency range too small", e.what());
throw;
}
},
std::runtime_error);
}
/**
* @brief Test too small max range error
*
*/
TEST(HPCP, TooSmallMaxRangeError) {
std::vector<double> actual_hpcp;
std::vector<double> frequencies = {};
std::vector<double> magnitudes = {};
double band_split_frequency = 1000.0;
double max_frequency = 1199.0;
EXPECT_THROW(
{
try {
actual_hpcp = HPCP(frequencies, magnitudes, 12, 440.0, 0, true, band_split_frequency, 40.0, max_frequency,
"squared cosine", 1.0, false);
} catch (const std::runtime_error& e) {
/* This tests if the error message is equal */
EXPECT_STREQ("HPCP: High band frequency range too small", e.what());
throw;
}
},
std::runtime_error);
}
/**
* @brief Test too close min max range error
*
*/
TEST(HPCP, TooCloseMinMaxRange) {
std::vector<double> actual_hpcp;
std::vector<double> frequencies = {};
std::vector<double> magnitudes = {};
bool band_present = false;
double min_frequency = 1.0;
double max_frequency = 200.0;
EXPECT_THROW(
{
try {
actual_hpcp = HPCP(frequencies, magnitudes, 12, 440.0, 0, band_present, 1000.0, min_frequency, max_frequency,
"squared cosine", 1.0, false);
} catch (const std::runtime_error& e) {
/* This tests if the error message is equal */
EXPECT_STREQ("HPCP: Minimum and maximum frequencies are too close", e.what());
throw;
}
},
std::runtime_error);
}
/**
* @brief Test size not a multiple of 12.
*
*/
TEST(HPCP, SizeNotMultipleOf12) {
std::vector<double> actual_hpcp;
std::vector<double> frequencies = {};
std::vector<double> magnitudes = {};
int size = 13;
EXPECT_THROW(
{
try {
actual_hpcp =
HPCP(frequencies, magnitudes, size, 440.0, 0, true, 500.0, 40.0, 5000.0, "squared cosine", 1.0, false);
} catch (const std::runtime_error& e) {
/* This tests if the error message is equal */
EXPECT_STREQ("HPCP: The size parameter is not a multiple of 12.", e.what());
throw;
}
},
std::runtime_error);
}
| 6,453 | 2,592 |
#include "Util/FFT.h"
size_t FFT::getGoodSize(size_t size)
{
//check if size is a power of 2
size_t mod = size % 2;
if(mod == 0) return size;
//get the next bigger power of 2
size_t potens = 0;
while(size > 0)
{
size = size/2;
potens++;
}
return pow(2,potens);
}
Tensorcd FFT::reverseOrder(const Tensorcd& in)
{
//get the next best size for fft
const TensorShape& dim = in.shape();
size_t size = dim.lastBefore();
size_t states = dim.lastDimension();
size_t N = getGoodSize(size);
//build the output tensor withe the new sizes
vector<size_t> d;
d.push_back(N);
d.push_back(dim.lastDimension());
TensorShape newdim(d);
Tensorcd out(newdim);
for(size_t n = 0; n < states; n++)
for(size_t i = 0; i < size; i++)
out[n*size + i] = in[n*size + i];
complex<double> tmp;
//reverse the order
for(size_t n = 0; n < states; n++)
{
size_t j = 1;
for(size_t i = 1; i <= size; i++)
{
if(j > i)
{
tmp = out[n*size + j-1];
out[n*size + j-1] = out[n*size + i-1];
out[n*size + i-1] = tmp;
}
size_t m = size/2;
while((m >= 2) && (j > m))
{
j -= m;
m /= 2;
}
j += m;
}
}
return out;
}
Tensorcd FFT::generalFFT(const Tensorcd& in, const int sign)
{
//get sizes for fft
const TensorShape& dim = in.shape();
size_t size = dim.lastBefore();
size_t states = dim.lastDimension();
//get primefactors
vector<size_t> primefactors = primeFactorization(size);
size_t numberOfFactors = primefactors.size();
//make a factor 2 fft if possible
if(primefactors[numberOfFactors-1] == 2)
return factor2FFT(in, sign);
//otherwise perform dft
return dft(in, sign);
}
Tensorcd FFT::dft(const Tensorcd& in, const int sign)
{
//get sizes for dft
const TensorShape& dim = in.shape();
size_t size = dim.lastBefore();
size_t states = dim.lastDimension();
//otherwise perform dft
vector<size_t> d;
d.push_back(size);
d.push_back(states);
TensorShape newdim(d);
Tensorcd out(newdim);
for(size_t k = 0; k < states; k++)
{
for(size_t i = 0; i < size; i++)
{
double angle = (2.*M_PI*i*sign)/(1.*size);
complex<double> factor(cos(angle),sin(angle));
complex<double> w(1/sqrt(1.*size),0.);
for(size_t j = 0; j < size; j++)
{
out[k*size + i] += w*in[k*size + j];
w *= factor;
}
}
}
return out;
}
Tensorcd FFT::factor2FFT(const Tensorcd& in, const int sign)
{
Tensorcd out = reverseOrder(in);
danielsonLanczosAlgorithm(out, sign);
return out;
}
void FFT::danielsonLanczosAlgorithm(Tensorcd& in, const int sign)
{
//get sizes for fft
const TensorShape& dim = in.shape();
size_t size = dim.lastBefore();
size_t states = dim.lastDimension();
//save some intermediat results
complex<double> tmp(0., 0.);
//Transform each vector seperadly
for(size_t n = 0; n < states; n++)
{
//Recursion
size_t mmax = 1;
while(mmax < size)
{
size_t j = 0;
size_t step = 2*mmax;
//prefector for exponent
double angle = M_PI/(1.*sign*mmax);
complex<double> factor(-2.*pow(sin(0.5*angle),2), sin(angle));
//transformation factor
complex<double> w(1., 0.);
//go throug all partitions of the vector
for(size_t m = 0; m < mmax; m++)
{
for(size_t i = m; i < size; i += step)
{
//Davidson-Lanczos-Formula
j = i + mmax;
tmp = w*in[n*size + j];
in[n*size + j] = in[n*size + i] - tmp;
in[n*size + i] = in[n*size + i] + tmp;
}
w = w*factor + w;
}
mmax = step;
}
}
in *= 1./sqrt(size);
}
vector<size_t> FFT::primeFactorization(size_t number) const
{
vector<size_t> primefactors;
if(number == 1)
primefactors.push_back(1);
size_t inter = number;
for(size_t i = 2; i <= number; i++)
{
while(inter % i == 0)
{
inter /= i;
primefactors.push_back(i);
}
if(inter == 1) break;
}
return primefactors;
}
| 3,829 | 1,807 |
#include <cstring>
#include "html/Extensions.h"
using namespace std;
using namespace htmlcxx;
Extensions::Extensions(const string &exts)
{
const char *begin = exts.c_str();
while (*begin)
{
while (*begin == ' ') ++begin;
if (*begin == 0) break;
const char *end = begin + 1;
while (*end && *end != ' ') ++end;
insert(ci_string(begin, end));
begin = end;
}
}
bool Extensions::check(const string &url)
{
const char *slash;
const char *dot;
const char *question;
question = strchr(url.c_str(), '?');
if (question) return false;
slash = strrchr(url.c_str(), '/');
dot = strrchr(url.c_str(), '.');
if (slash >= dot) return false;
ci_string ext(dot);
return mExts.find(ext) != mExts.end();
}
| 849 | 290 |
// -*- C++ -*-
//
// Package: HGCalGeometry
// Class: HGCalGeometryESProducer
//
/**\class HGCalGeometryESProducer HGCalGeometryESProducer.h
Description: <one line class summary>
Implementation:
<Notes on implementation>
*/
//
// Original Author: Sunanda Banerjee
//
//
// system include files
#include <memory>
// user include files
#include "FWCore/Framework/interface/ModuleFactory.h"
#include "FWCore/Framework/interface/ESProducer.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "Geometry/CaloGeometry/interface/CaloSubdetectorGeometry.h"
#include "Geometry/CaloTopology/interface/HGCalTopology.h"
#include "Geometry/HGCalGeometry/interface/HGCalGeometry.h"
#include "Geometry/HGCalGeometry/interface/HGCalGeometryLoader.h"
//#define EDM_ML_DEBUG
//
// class decleration
//
class HGCalGeometryESProducer : public edm::ESProducer {
public:
HGCalGeometryESProducer( const edm::ParameterSet& iP );
~HGCalGeometryESProducer() override ;
using ReturnType = std::unique_ptr<HGCalGeometry>;
ReturnType produce(const IdealGeometryRecord&);
private:
// ----------member data ---------------------------
std::string name_;
};
HGCalGeometryESProducer::HGCalGeometryESProducer(const edm::ParameterSet& iConfig) {
name_ = iConfig.getUntrackedParameter<std::string>("Name");
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "Constructing HGCalGeometry for " << name_;
#endif
setWhatProduced(this, name_);
}
HGCalGeometryESProducer::~HGCalGeometryESProducer() { }
//
// member functions
//
// ------------ method called to produce the data ------------
HGCalGeometryESProducer::ReturnType
HGCalGeometryESProducer::produce(const IdealGeometryRecord& iRecord ) {
edm::ESHandle<HGCalTopology> topo;
iRecord.get(name_,topo);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "Create HGCalGeometry (*topo) with "
<< topo.isValid();
#endif
HGCalGeometryLoader builder;
return ReturnType(builder.build(*topo));
}
DEFINE_FWK_EVENTSETUP_MODULE(HGCalGeometryESProducer);
| 2,175 | 785 |
/**
* Copyright (c) 2017-present, Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "logdevice/common/StatsCollectionThread.h"
#include <folly/Optional.h>
#include "logdevice/common/ThreadID.h"
#include "logdevice/common/configuration/ServerConfig.h"
#include "logdevice/common/debug.h"
#include "logdevice/common/plugin/PluginRegistry.h"
#include "logdevice/common/plugin/StatsPublisherFactory.h"
#include "logdevice/common/settings/Settings.h"
#include "logdevice/common/settings/UpdateableSettings.h"
#include "logdevice/common/stats/Stats.h"
namespace facebook { namespace logdevice {
StatsCollectionThread::StatsCollectionThread(
const StatsHolder* source,
std::chrono::seconds interval,
std::unique_ptr<StatsPublisher> publisher)
: source_stats_(source),
interval_(interval),
publisher_(std::move(publisher)),
thread_(std::bind(&StatsCollectionThread::mainLoop, this)) {
ld_debug("Stats Collection Thread Started...");
}
StatsCollectionThread::~StatsCollectionThread() {
shutDown();
thread_.join();
}
namespace {
struct StatsSnapshot {
Stats stats;
std::chrono::steady_clock::time_point when;
};
} // namespace
void StatsCollectionThread::mainLoop() {
ThreadID::set(ThreadID::Type::UTILITY, "ld:stats");
folly::Optional<StatsSnapshot> previous;
while (true) {
using namespace std::chrono;
const auto now = steady_clock::now();
const auto next_tick = now + interval_;
StatsSnapshot current = {source_stats_->aggregate(), now};
ld_debug("Publishing Stats...");
if (previous.hasValue()) {
publisher_->publish(
current.stats,
previous.value().stats,
duration_cast<milliseconds>(now - previous.value().when));
}
previous.assign(std::move(current));
{
std::unique_lock<std::mutex> lock(mutex_);
if (stop_) {
break;
}
if (next_tick > steady_clock::now()) {
cv_.wait_until(lock, next_tick, [this]() { return stop_; });
}
// NOTE: even if we got woken up by shutDown(), we still aggregate and
// push once more so we don't lose data from the partial interval
}
}
}
std::unique_ptr<StatsCollectionThread> StatsCollectionThread::maybeCreate(
const UpdateableSettings<Settings>& settings,
std::shared_ptr<ServerConfig> config,
std::shared_ptr<PluginRegistry> plugin_registry,
StatsPublisherScope scope,
int num_shards,
const StatsHolder* source) {
ld_check(settings.get());
ld_check(config);
ld_check(plugin_registry);
auto stats_collection_interval = settings->stats_collection_interval;
if (stats_collection_interval.count() <= 0) {
return nullptr;
}
auto factory = plugin_registry->getSinglePlugin<StatsPublisherFactory>(
PluginType::STATS_PUBLISHER_FACTORY);
if (!factory) {
return nullptr;
}
auto stats_publisher = (*factory)(scope, settings, num_shards);
if (!stats_publisher) {
return nullptr;
}
auto rollup_entity = config->getClusterName();
stats_publisher->addRollupEntity(rollup_entity);
if (scope == StatsPublisherScope::CLIENT) {
// This is here for backward compatibility with our tooling. The
// <tier>.client entity space is deprecated and all new tooling should
// be using the tier name without suffix
stats_publisher->addRollupEntity(rollup_entity + ".client");
}
return std::make_unique<StatsCollectionThread>(
source, stats_collection_interval, std::move(stats_publisher));
}
}} // namespace facebook::logdevice
| 3,682 | 1,129 |
//===- VectorToLLVM.cpp - Conversion from Vector to the LLVM dialect ------===//
//
// Copyright 2019 The MLIR 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.
// =============================================================================
#include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVM.h"
#include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVMPass.h"
#include "mlir/Conversion/VectorConversions/VectorConversions.h"
#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
#include "mlir/Dialect/VectorOps/VectorOps.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/MLIRContext.h"
#include "mlir/IR/Module.h"
#include "mlir/IR/Operation.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/IR/StandardTypes.h"
#include "mlir/IR/Types.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Pass/PassManager.h"
#include "mlir/Transforms/DialectConversion.h"
#include "mlir/Transforms/Passes.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/ErrorHandling.h"
using namespace mlir;
template <typename T>
static LLVM::LLVMType getPtrToElementType(T containerType,
LLVMTypeConverter &lowering) {
return lowering.convertType(containerType.getElementType())
.template cast<LLVM::LLVMType>()
.getPointerTo();
}
class VectorExtractElementOpConversion : public LLVMOpLowering {
public:
explicit VectorExtractElementOpConversion(MLIRContext *context,
LLVMTypeConverter &typeConverter)
: LLVMOpLowering(vector::VectorExtractElementOp::getOperationName(),
context, typeConverter) {}
PatternMatchResult
matchAndRewrite(Operation *op, ArrayRef<Value *> operands,
ConversionPatternRewriter &rewriter) const override {
auto loc = op->getLoc();
auto adaptor = vector::VectorExtractElementOpOperandAdaptor(operands);
auto extractOp = cast<vector::VectorExtractElementOp>(op);
auto vectorType = extractOp.vector()->getType().cast<VectorType>();
auto resultType = extractOp.getResult()->getType();
auto llvmResultType = lowering.convertType(resultType);
auto positionArrayAttr = extractOp.position();
// One-shot extraction of vector from array (only requires extractvalue).
if (resultType.isa<VectorType>()) {
Value *extracted = rewriter.create<LLVM::ExtractValueOp>(
loc, llvmResultType, adaptor.vector(), positionArrayAttr);
rewriter.replaceOp(op, extracted);
return matchSuccess();
}
// Potential extraction of 1-D vector from struct.
auto *context = op->getContext();
Value *extracted = adaptor.vector();
auto positionAttrs = positionArrayAttr.getValue();
auto i32Type = rewriter.getIntegerType(32);
if (positionAttrs.size() > 1) {
auto nDVectorType = vectorType;
auto oneDVectorType = VectorType::get(nDVectorType.getShape().take_back(),
nDVectorType.getElementType());
auto nMinusOnePositionAttrs =
ArrayAttr::get(positionAttrs.drop_back(), context);
extracted = rewriter.create<LLVM::ExtractValueOp>(
loc, lowering.convertType(oneDVectorType), extracted,
nMinusOnePositionAttrs);
}
// Remaining extraction of element from 1-D LLVM vector
auto position = positionAttrs.back().cast<IntegerAttr>();
auto constant = rewriter.create<LLVM::ConstantOp>(
loc, lowering.convertType(i32Type), position);
extracted =
rewriter.create<LLVM::ExtractElementOp>(loc, extracted, constant);
rewriter.replaceOp(op, extracted);
return matchSuccess();
}
};
class VectorOuterProductOpConversion : public LLVMOpLowering {
public:
explicit VectorOuterProductOpConversion(MLIRContext *context,
LLVMTypeConverter &typeConverter)
: LLVMOpLowering(vector::VectorOuterProductOp::getOperationName(),
context, typeConverter) {}
PatternMatchResult
matchAndRewrite(Operation *op, ArrayRef<Value *> operands,
ConversionPatternRewriter &rewriter) const override {
auto loc = op->getLoc();
auto adaptor = vector::VectorOuterProductOpOperandAdaptor(operands);
auto *ctx = op->getContext();
auto vLHS = adaptor.lhs()->getType().cast<LLVM::LLVMType>();
auto vRHS = adaptor.rhs()->getType().cast<LLVM::LLVMType>();
auto rankLHS = vLHS.getUnderlyingType()->getVectorNumElements();
auto rankRHS = vRHS.getUnderlyingType()->getVectorNumElements();
auto llvmArrayOfVectType = lowering.convertType(
cast<vector::VectorOuterProductOp>(op).getResult()->getType());
Value *desc = rewriter.create<LLVM::UndefOp>(loc, llvmArrayOfVectType);
Value *a = adaptor.lhs(), *b = adaptor.rhs();
Value *acc = adaptor.acc().empty() ? nullptr : adaptor.acc().front();
SmallVector<Value *, 8> lhs, accs;
lhs.reserve(rankLHS);
accs.reserve(rankLHS);
for (unsigned d = 0, e = rankLHS; d < e; ++d) {
// shufflevector explicitly requires i32.
auto attr = rewriter.getI32IntegerAttr(d);
SmallVector<Attribute, 4> bcastAttr(rankRHS, attr);
auto bcastArrayAttr = ArrayAttr::get(bcastAttr, ctx);
Value *aD = nullptr, *accD = nullptr;
// 1. Broadcast the element a[d] into vector aD.
aD = rewriter.create<LLVM::ShuffleVectorOp>(loc, a, a, bcastArrayAttr);
// 2. If acc is present, extract 1-d vector acc[d] into accD.
if (acc)
accD = rewriter.create<LLVM::ExtractValueOp>(
loc, vRHS, acc, rewriter.getI64ArrayAttr(d));
// 3. Compute aD outer b (plus accD, if relevant).
Value *aOuterbD =
accD ? rewriter.create<LLVM::FMulAddOp>(loc, vRHS, aD, b, accD)
.getResult()
: rewriter.create<LLVM::FMulOp>(loc, aD, b).getResult();
// 4. Insert as value `d` in the descriptor.
desc = rewriter.create<LLVM::InsertValueOp>(loc, llvmArrayOfVectType,
desc, aOuterbD,
rewriter.getI64ArrayAttr(d));
}
rewriter.replaceOp(op, desc);
return matchSuccess();
}
};
class VectorTypeCastOpConversion : public LLVMOpLowering {
public:
explicit VectorTypeCastOpConversion(MLIRContext *context,
LLVMTypeConverter &typeConverter)
: LLVMOpLowering(vector::VectorTypeCastOp::getOperationName(), context,
typeConverter) {}
PatternMatchResult
matchAndRewrite(Operation *op, ArrayRef<Value *> operands,
ConversionPatternRewriter &rewriter) const override {
auto loc = op->getLoc();
vector::VectorTypeCastOp castOp = cast<vector::VectorTypeCastOp>(op);
MemRefType sourceMemRefType =
castOp.getOperand()->getType().cast<MemRefType>();
MemRefType targetMemRefType =
castOp.getResult()->getType().cast<MemRefType>();
// Only static shape casts supported atm.
if (!sourceMemRefType.hasStaticShape() ||
!targetMemRefType.hasStaticShape())
return matchFailure();
auto llvmSourceDescriptorTy =
operands[0]->getType().dyn_cast<LLVM::LLVMType>();
if (!llvmSourceDescriptorTy || !llvmSourceDescriptorTy.isStructTy())
return matchFailure();
MemRefDescriptor sourceMemRef(operands[0]);
auto llvmTargetDescriptorTy = lowering.convertType(targetMemRefType)
.dyn_cast_or_null<LLVM::LLVMType>();
if (!llvmTargetDescriptorTy || !llvmTargetDescriptorTy.isStructTy())
return matchFailure();
int64_t offset;
SmallVector<int64_t, 4> strides;
auto successStrides =
getStridesAndOffset(sourceMemRefType, strides, offset);
bool isContiguous = (strides.back() == 1);
if (isContiguous) {
auto sizes = sourceMemRefType.getShape();
for (int index = 0, e = strides.size() - 2; index < e; ++index) {
if (strides[index] != strides[index + 1] * sizes[index + 1]) {
isContiguous = false;
break;
}
}
}
// Only contiguous source tensors supported atm.
if (failed(successStrides) || !isContiguous)
return matchFailure();
auto int64Ty = LLVM::LLVMType::getInt64Ty(lowering.getDialect());
// Create descriptor.
auto desc = MemRefDescriptor::undef(rewriter, loc, llvmTargetDescriptorTy);
Type llvmTargetElementTy = desc.getElementType();
// Set allocated ptr.
Value *allocated = sourceMemRef.allocatedPtr(rewriter, loc);
allocated =
rewriter.create<LLVM::BitcastOp>(loc, llvmTargetElementTy, allocated);
desc.setAllocatedPtr(rewriter, loc, allocated);
// Set aligned ptr.
Value *ptr = sourceMemRef.alignedPtr(rewriter, loc);
ptr = rewriter.create<LLVM::BitcastOp>(loc, llvmTargetElementTy, ptr);
desc.setAlignedPtr(rewriter, loc, ptr);
// Fill offset 0.
auto attr = rewriter.getIntegerAttr(rewriter.getIndexType(), 0);
auto zero = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, attr);
desc.setOffset(rewriter, loc, zero);
// Fill size and stride descriptors in memref.
for (auto indexedSize : llvm::enumerate(targetMemRefType.getShape())) {
int64_t index = indexedSize.index();
auto sizeAttr =
rewriter.getIntegerAttr(rewriter.getIndexType(), indexedSize.value());
auto size = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, sizeAttr);
desc.setSize(rewriter, loc, index, size);
auto strideAttr =
rewriter.getIntegerAttr(rewriter.getIndexType(), strides[index]);
auto stride = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, strideAttr);
desc.setStride(rewriter, loc, index, stride);
}
rewriter.replaceOp(op, {desc});
return matchSuccess();
}
};
/// Populate the given list with patterns that convert from Vector to LLVM.
void mlir::populateVectorToLLVMConversionPatterns(
LLVMTypeConverter &converter, OwningRewritePatternList &patterns) {
patterns.insert<VectorExtractElementOpConversion,
VectorOuterProductOpConversion, VectorTypeCastOpConversion>(
converter.getDialect()->getContext(), converter);
}
namespace {
struct LowerVectorToLLVMPass : public ModulePass<LowerVectorToLLVMPass> {
void runOnModule() override;
};
} // namespace
void LowerVectorToLLVMPass::runOnModule() {
// Convert to the LLVM IR dialect using the converter defined above.
OwningRewritePatternList patterns;
LLVMTypeConverter converter(&getContext());
populateVectorToLLVMConversionPatterns(converter, patterns);
populateStdToLLVMConversionPatterns(converter, patterns);
ConversionTarget target(getContext());
target.addLegalDialect<LLVM::LLVMDialect>();
target.addDynamicallyLegalOp<FuncOp>(
[&](FuncOp op) { return converter.isSignatureLegal(op.getType()); });
if (failed(
applyPartialConversion(getModule(), target, patterns, &converter))) {
signalPassFailure();
}
}
OpPassBase<ModuleOp> *mlir::createLowerVectorToLLVMPass() {
return new LowerVectorToLLVMPass();
}
static PassRegistration<LowerVectorToLLVMPass>
pass("convert-vector-to-llvm",
"Lower the operations from the vector dialect into the LLVM dialect");
| 11,892 | 3,666 |
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int length, width, height;
double percent;
cin >> length >> width >> height >> percent;
int volume = length * width * height;
double liters = volume * 0.001;
percent = percent * 0.01;
double realLeaters = liters * (1-percent);
cout.setf(ios::fixed);
cout.precision(3);
cout << realLeaters << endl;
return 0;
}
| 430 | 146 |
#include <catch2/catch.hpp>
#include <nlohmann/json.hpp>
#include <nw/kernel/Kernel.hpp>
#include <nw/objects/Door.hpp>
#include <nw/serialization/Archives.hpp>
#include <filesystem>
#include <fstream>
namespace fs = std::filesystem;
TEST_CASE("door: from_gff", "[objects]")
{
auto door = nw::kernel::objects().load(fs::path("test_data/user/development/door_ttr_002.utd"));
auto d = door.get<nw::Door>();
auto common = door.get<nw::Common>();
auto lock = door.get<nw::Lock>();
REQUIRE(common->resref == "door_ttr_002");
REQUIRE(d->appearance == 0);
REQUIRE(!d->plot);
REQUIRE(!lock->locked);
door.destruct();
}
TEST_CASE("door: to_json", "[objects]")
{
auto door = nw::kernel::objects().load(fs::path("test_data/user/development/door_ttr_002.utd"));
nlohmann::json j;
nw::kernel::objects().serialize(door, j, nw::SerializationProfile::blueprint);
auto door2 = nw::kernel::objects().deserialize(nw::ObjectType::door, j,
nw::SerializationProfile::blueprint);
REQUIRE(door2.is_alive());
nlohmann::json j2;
nw::kernel::objects().serialize(door, j2, nw::SerializationProfile::blueprint);
REQUIRE(j == j2);
std::ofstream f{"tmp/door_ttr_002.utd.json"};
f << std::setw(4) << j;
}
TEST_CASE("door: gff round trip", "[ojbects]")
{
nw::GffInputArchive g("test_data/user/development/door_ttr_002.utd");
REQUIRE(g.valid());
auto door = nw::kernel::objects().load(fs::path("test_data/user/development/door_ttr_002.utd"));
nw::GffOutputArchive oa = nw::kernel::objects().serialize(door, nw::SerializationProfile::blueprint);
oa.write_to("tmp/door_ttr_002.utd");
nw::GffInputArchive g2("tmp/door_ttr_002.utd");
REQUIRE(g2.valid());
REQUIRE(nw::gff_to_gffjson(g) == nw::gff_to_gffjson(g2));
REQUIRE(oa.header.struct_offset == g.head_->struct_offset);
REQUIRE(oa.header.struct_count == g.head_->struct_count);
REQUIRE(oa.header.field_offset == g.head_->field_offset);
REQUIRE(oa.header.field_count == g.head_->field_count);
REQUIRE(oa.header.label_offset == g.head_->label_offset);
REQUIRE(oa.header.label_count == g.head_->label_count);
REQUIRE(oa.header.field_data_offset == g.head_->field_data_offset);
REQUIRE(oa.header.field_data_count == g.head_->field_data_count);
REQUIRE(oa.header.field_idx_offset == g.head_->field_idx_offset);
REQUIRE(oa.header.field_idx_count == g.head_->field_idx_count);
REQUIRE(oa.header.list_idx_offset == g.head_->list_idx_offset);
REQUIRE(oa.header.list_idx_count == g.head_->list_idx_count);
}
| 2,594 | 1,061 |
/* $Id$
*
* Copyright 2010 Anders Wallin (anders.e.e.wallin "at" gmail.com)
*
* This file is part of OpenCAMlib.
*
* OpenCAMlib is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenCAMlib 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 OpenCAMlib. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef BPC_PY_H
#define BPC_PY_H
#include <boost/python.hpp>
#include "batchpushcutter.hpp"
#include "fiber_py.hpp"
namespace ocl
{
/// \brief python wrapper for batchpushcutter
class BatchPushCutter_py : public BatchPushCutter {
public:
BatchPushCutter_py() : BatchPushCutter() {}
/// return CL-points to Python
boost::python::list getCLPoints() const {
boost::python::list plist;
BOOST_FOREACH(Fiber f, *fibers) {
BOOST_FOREACH( Interval i, f.ints ) {
if ( !i.empty() ) {
Point tmp = f.point(i.lower);
CLPoint p1 = CLPoint( tmp.x, tmp.y, tmp.z );
p1.cc = new CCPoint(i.lower_cc);
tmp = f.point(i.upper);
CLPoint p2 = CLPoint( tmp.x, tmp.y, tmp.z );
p2.cc = new CCPoint(i.upper_cc);
plist.append(p1);
plist.append(p2);
}
}
}
return plist;
};
/// return triangles under cutter to Python. Not for CAM-algorithms,
/// more for visualization and demonstration.
boost::python::list getOverlapTriangles(Fiber& f) {
boost::python::list trilist;
std::list<Triangle> *overlap_triangles = new std::list<Triangle>();
//int plane = 3; // XY-plane
//Bbox bb; //FIXME
//KDNode2::search_kdtree( overlap_triangles, bb, root, plane);
CLPoint cl;
if (x_direction) {
cl.x = 0;
cl.y = f.p1.y;
cl.z = f.p1.z;
} else if (y_direction) {
cl.x = f.p1.x;
cl.y = 0;
cl.z = f.p1.z;
} else {
assert(0);
}
overlap_triangles = root->search_cutter_overlap(cutter, &cl);
BOOST_FOREACH(Triangle t, *overlap_triangles) {
trilist.append(t);
}
delete overlap_triangles;
return trilist;
};
/// return list of Fibers to python
boost::python::list getFibers_py() const {
boost::python::list flist;
BOOST_FOREACH(Fiber f, *fibers) {
flist.append( Fiber_py(f) );
}
return flist;
};
};
} // end namespace
#endif
| 3,265 | 1,030 |
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "update_image_block.h"
#include <cerrno>
#include <fcntl.h>
#include <pthread.h>
#include <sstream>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "applypatch/block_set.h"
#include "applypatch/store.h"
#include "applypatch/transfer_manager.h"
#include "applypatch/partition_record.h"
#include "fs_manager/mount.h"
#include "log/log.h"
#include "utils.h"
using namespace uscript;
using namespace hpackage;
using namespace updater;
namespace updater {
constexpr int32_t SHA_CHECK_SECOND = 2;
constexpr int32_t SHA_CHECK_PARAMS = 3;
static int ExtractNewData(const PkgBuffer &buffer, size_t size, size_t start, bool isFinish, const void* context)
{
void *p = const_cast<void *>(context);
WriterThreadInfo *info = static_cast<WriterThreadInfo *>(p);
uint8_t *addr = buffer.buffer;
while (size > 0) {
pthread_mutex_lock(&info->mutex);
while (info->writer == nullptr) {
if (!info->readyToWrite) {
LOG(WARNING) << "writer is not ready to write.";
pthread_mutex_unlock(&info->mutex);
return hpackage::PKG_INVALID_STREAM;
}
pthread_cond_wait(&info->cond, &info->mutex);
}
pthread_mutex_unlock(&info->mutex);
size_t toWrite = std::min(size, info->writer->GetBlocksSize() - info->writer->GetTotalWritten());
// No more data to write.
UPDATER_CHECK_ONLY_RETURN(toWrite != 0, break);
bool ret = info->writer->Write(const_cast<uint8_t *>(addr), toWrite, WRITE_BLOCK, "");
std::ostringstream logMessage;
logMessage << "Write " << toWrite << " byte(s) failed";
UPDATER_ERROR_CHECK(ret == true, logMessage.str(), return hpackage::PKG_INVALID_STREAM);
size -= toWrite;
addr += toWrite;
if (info->writer->IsWriteDone()) {
pthread_mutex_lock(&info->mutex);
info->writer.reset();
pthread_cond_broadcast(&info->cond);
pthread_mutex_unlock(&info->mutex);
}
}
return hpackage::PKG_SUCCESS;
}
void* UnpackNewData(void *arg)
{
WriterThreadInfo *info = static_cast<WriterThreadInfo *>(arg);
hpackage::PkgManager::StreamPtr stream = nullptr;
TransferManagerPtr tm = TransferManager::GetTransferManagerInstance();
if (info->newPatch.empty()) {
LOG(ERROR) << "new patch file name is empty. thread quit.";
pthread_mutex_lock(&info->mutex);
info->readyToWrite = false;
if (info->writer != nullptr) {
pthread_cond_broadcast(&info->cond);
}
pthread_mutex_unlock(&info->mutex);
return nullptr;
}
LOG(DEBUG) << "new patch file name: " << info->newPatch;
auto env = tm->GetGlobalParams()->env;
const FileInfo *file = env->GetPkgManager()->GetFileInfo(info->newPatch);
if (file == nullptr) {
LOG(ERROR) << "Cannot get file info of :" << info->newPatch;
pthread_mutex_lock(&info->mutex);
info->readyToWrite = false;
if (info->writer != nullptr) {
pthread_cond_broadcast(&info->cond);
}
pthread_mutex_unlock(&info->mutex);
return nullptr;
}
LOG(DEBUG) << info->newPatch << " info: size " << file->packedSize << " unpacked size " <<
file->unpackedSize << " name " << file->identity;
int32_t ret = env->GetPkgManager()->CreatePkgStream(stream, info->newPatch, ExtractNewData, info);
if (ret != hpackage::PKG_SUCCESS || stream == nullptr) {
LOG(ERROR) << "Cannot extract " << info->newPatch << " from package.";
pthread_mutex_lock(&info->mutex);
info->readyToWrite = false;
if (info->writer != nullptr) {
pthread_cond_broadcast(&info->cond);
}
pthread_mutex_unlock(&info->mutex);
return nullptr;
}
ret = env->GetPkgManager()->ExtractFile(info->newPatch, stream);
env->GetPkgManager()->ClosePkgStream(stream);
pthread_mutex_lock(&info->mutex);
LOG(DEBUG) << "new data writer ending...";
// extract new data done.
// tell command.
info->readyToWrite = false;
UPDATER_WARING_CHECK (info->writer == nullptr, "writer is null", pthread_cond_broadcast(&info->cond));
pthread_mutex_unlock(&info->mutex);
return nullptr;
}
static int32_t ReturnAndPushParam(int32_t returnValue, uscript::UScriptContext &context)
{
context.PushParam(returnValue);
return returnValue;
}
struct UpdateBlockInfo {
std::string partitionName;
std::string transferName;
std::string newDataName;
std::string patchDataName;
std::string devPath;
};
static int32_t GetUpdateBlockInfo(struct UpdateBlockInfo &infos, uscript::UScriptEnv &env,
uscript::UScriptContext &context)
{
UPDATER_ERROR_CHECK(context.GetParamCount() == 4, "Invalid param",
return ReturnAndPushParam(USCRIPT_INVALID_PARAM, context));
// Get partition Name first.
// Use partition name as zip file name. ${partition name}.zip
// load ${partition name}.zip from updater package.
// Try to unzip ${partition name}.zip, extract transfer.list, net.dat, patch.dat
size_t pos = 0;
int32_t ret = context.GetParam(pos++, infos.partitionName);
UPDATER_ERROR_CHECK(ret == USCRIPT_SUCCESS, "Error to get param 1", return ret);
ret = context.GetParam(pos++, infos.transferName);
UPDATER_ERROR_CHECK(ret == USCRIPT_SUCCESS, "Error to get param 2", return ret);
ret = context.GetParam(pos++, infos.newDataName);
UPDATER_ERROR_CHECK(ret == USCRIPT_SUCCESS, "Error to get param 3", return ret);
ret = context.GetParam(pos++, infos.patchDataName);
UPDATER_ERROR_CHECK(ret == USCRIPT_SUCCESS, "Error to get param 4", return ret);
LOG(INFO) << "ExecuteUpdateBlock::updating " << infos.partitionName << " ...";
infos.devPath = GetBlockDeviceByMountPoint(infos.partitionName);
LOG(INFO) << "ExecuteUpdateBlock::updating dev path : " << infos.devPath;
UPDATER_ERROR_CHECK(!infos.devPath.empty(), "cannot get block device of partition",
return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context));
return USCRIPT_SUCCESS;
}
static int32_t ExecuteTransferCommand(int fd, const std::vector<std::string> &lines, uscript::UScriptEnv &env,
uscript::UScriptContext &context, const std::string &partitionName)
{
TransferManagerPtr tm = TransferManager::GetTransferManagerInstance();
auto globalParams = tm->GetGlobalParams();
auto writerThreadInfo = globalParams->writerThreadInfo.get();
globalParams->storeBase = "/data/updater/update_tmp";
globalParams->retryFile = std::string("/data/updater") + partitionName + "_retry";
LOG(INFO) << "Store base path is " << globalParams->storeBase;
int32_t ret = Store::CreateNewSpace(globalParams->storeBase, !globalParams->env->IsRetry());
UPDATER_ERROR_CHECK(ret != -1, "Error to create new store space",
return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context));
globalParams->storeCreated = ret;
UPDATER_CHECK_ONLY_RETURN(tm->CommandsParser(fd, lines), return USCRIPT_ERROR_EXECUTE);
pthread_mutex_lock(&writerThreadInfo->mutex);
if (writerThreadInfo->readyToWrite) {
LOG(WARNING) << "New data writer thread is still available...";
}
writerThreadInfo->readyToWrite = false;
pthread_cond_broadcast(&writerThreadInfo->cond);
pthread_mutex_unlock(&writerThreadInfo->mutex);
ret = pthread_join(globalParams->thread, nullptr);
std::ostringstream logMessage;
logMessage << "pthread join returned with " << strerror(ret);
UPDATER_WARNING_CHECK_NOT_RETURN(ret == 0, logMessage.str());
if (globalParams->storeCreated != -1) {
Store::DoFreeSpace(globalParams->storeBase);
}
return USCRIPT_SUCCESS;
}
static int InitThread(struct UpdateBlockInfo &infos, uscript::UScriptEnv &env, uscript::UScriptContext &context)
{
TransferManagerPtr tm = TransferManager::GetTransferManagerInstance();
auto globalParams = tm->GetGlobalParams();
auto writerThreadInfo = globalParams->writerThreadInfo.get();
writerThreadInfo->readyToWrite = true;
pthread_mutex_init(&writerThreadInfo->mutex, nullptr);
pthread_cond_init(&writerThreadInfo->cond, nullptr);
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
writerThreadInfo->newPatch = infos.newDataName;
int error = pthread_create(&globalParams->thread, &attr, UnpackNewData, writerThreadInfo);
return error;
}
static int32_t ExtractDiffPackageAndLoad(const UpdateBlockInfo &infos, uscript::UScriptEnv &env,
uscript::UScriptContext &context)
{
hpackage::PkgManager::StreamPtr outStream = nullptr;
LOG(DEBUG) << "partitionName is " << infos.partitionName;
const FileInfo *info = env.GetPkgManager()->GetFileInfo(infos.partitionName);
UPDATER_ERROR_CHECK(info != nullptr, "Error to get file info", return USCRIPT_ERROR_EXECUTE);
std::string diffPackage = std::string("/data/updater") + infos.partitionName;
int32_t ret = env.GetPkgManager()->CreatePkgStream(outStream,
diffPackage, info->unpackedSize, PkgStream::PkgStreamType_Write);
UPDATER_ERROR_CHECK(outStream != nullptr, "Error to create output stream", return USCRIPT_ERROR_EXECUTE);
ret = env.GetPkgManager()->ExtractFile(infos.partitionName, outStream);
UPDATER_ERROR_CHECK(ret == USCRIPT_SUCCESS, "Error to extract file",
env.GetPkgManager()->ClosePkgStream(outStream); return USCRIPT_ERROR_EXECUTE);
env.GetPkgManager()->ClosePkgStream(outStream);
std::string diffPackageZip = diffPackage + ".zip";
rename(diffPackage.c_str(), diffPackageZip.c_str());
LOG(DEBUG) << "Rename " << diffPackage << " to zip\nExtract " << diffPackage << " done\nReload " << diffPackageZip;
std::vector<std::string> diffPackageComponents;
ret = env.GetPkgManager()->LoadPackage(diffPackageZip, updater::utils::GetCertName(), diffPackageComponents);
UPDATER_ERROR_CHECK(diffPackageComponents.size() >= 1, "Diff package is empty",
return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context));
return USCRIPT_SUCCESS;
}
static int32_t DoExecuteUpdateBlock(UpdateBlockInfo &infos, uscript::UScriptEnv &env,
hpackage::PkgManager::StreamPtr &outStream, const std::vector<std::string> &lines, uscript::UScriptContext &context)
{
int fd = open(infos.devPath.c_str(), O_RDWR | O_LARGEFILE);
UPDATER_ERROR_CHECK (fd != -1, "Failed to open block",
env.GetPkgManager()->ClosePkgStream(outStream); return USCRIPT_ERROR_EXECUTE);
int32_t ret = ExecuteTransferCommand(fd, lines, env, context, infos.partitionName);
fsync(fd);
close(fd);
fd = -1;
env.GetPkgManager()->ClosePkgStream(outStream);
if (ret == USCRIPT_SUCCESS) {
PartitionRecord::GetInstance().RecordPartitionUpdateStatus(infos.partitionName, true);
}
return ret;
}
static int32_t ExecuteUpdateBlock(uscript::UScriptEnv &env, uscript::UScriptContext &context)
{
UpdateBlockInfo infos {};
UPDATER_CHECK_ONLY_RETURN(!GetUpdateBlockInfo(infos, env, context), return USCRIPT_ERROR_EXECUTE);
UPDATER_ERROR_CHECK(env.GetPkgManager() != nullptr, "Error to get pkg manager", return USCRIPT_ERROR_EXECUTE);
if (env.IsRetry()) {
LOG(DEBUG) << "Retry updater, check if current partition updatered already during last time";
bool isUpdated = PartitionRecord::GetInstance().IsPartitionUpdated(infos.partitionName);
if (isUpdated) {
LOG(INFO) << infos.partitionName << " already updated, skip";
return USCRIPT_SUCCESS;
}
}
int32_t ret = ExtractDiffPackageAndLoad(infos, env, context);
UPDATER_CHECK_ONLY_RETURN(ret == USCRIPT_SUCCESS, return USCRIPT_ERROR_EXECUTE);
const FileInfo *info = env.GetPkgManager()->GetFileInfo(infos.transferName);
hpackage::PkgManager::StreamPtr outStream = nullptr;
ret = env.GetPkgManager()->CreatePkgStream(outStream,
infos.transferName, info->unpackedSize, PkgStream::PkgStreamType_MemoryMap);
ret = env.GetPkgManager()->ExtractFile(infos.transferName, outStream);
uint8_t *transferListBuffer = nullptr;
size_t transferListSize = 0;
ret = outStream->GetBuffer(transferListBuffer, transferListSize);
TransferManagerPtr tm = TransferManager::GetTransferManagerInstance();
auto globalParams = tm->GetGlobalParams();
/* Save Script Env to transfer manager */
globalParams->env = &env;
std::vector<std::string> lines =
updater::utils::SplitString(std::string(reinterpret_cast<const char*>(transferListBuffer)), "\n");
LOG(INFO) << "Ready to start a thread to handle new data processing";
UPDATER_ERROR_CHECK (InitThread(infos, env, context) == 0, "Failed to create pthread",
env.GetPkgManager()->ClosePkgStream(outStream); return USCRIPT_ERROR_EXECUTE);
LOG(DEBUG) << "Start unpack new data thread done. Get patch data: " << infos.patchDataName;
info = env.GetPkgManager()->GetFileInfo(infos.patchDataName);
// Close stream opened before.
env.GetPkgManager()->ClosePkgStream(outStream);
ret = env.GetPkgManager()->CreatePkgStream(outStream,
infos.patchDataName, info->unpackedSize, PkgStream::PkgStreamType_MemoryMap);
UPDATER_ERROR_CHECK(outStream != nullptr, "Error to create output stream", return USCRIPT_ERROR_EXECUTE);
ret = env.GetPkgManager()->ExtractFile(infos.patchDataName, outStream);
UPDATER_ERROR_CHECK(ret == USCRIPT_SUCCESS, "Error to extract file",
env.GetPkgManager()->ClosePkgStream(outStream); return USCRIPT_ERROR_EXECUTE);
outStream->GetBuffer(globalParams->patchDataBuffer, globalParams->patchDataSize);
LOG(DEBUG) << "Patch data size is: " << globalParams->patchDataSize;
ret = DoExecuteUpdateBlock(infos, env, outStream, lines, context);
TransferManager::ReleaseTransferManagerInstance(tm);
return ret;
}
int32_t UScriptInstructionBlockUpdate::Execute(uscript::UScriptEnv &env, uscript::UScriptContext &context)
{
int32_t result = ExecuteUpdateBlock(env, context);
context.PushParam(result);
return result;
}
int32_t UScriptInstructionBlockCheck::Execute(uscript::UScriptEnv &env, uscript::UScriptContext &context)
{
UPDATER_ERROR_CHECK(context.GetParamCount() == 1, "Invalid param",
return ReturnAndPushParam(USCRIPT_INVALID_PARAM, context));
UPDATER_CHECK_ONLY_RETURN(!env.IsRetry(), return ReturnAndPushParam(USCRIPT_SUCCESS, context));
std::string partitionName;
int32_t ret = context.GetParam(0, partitionName);
UPDATER_ERROR_CHECK(ret == USCRIPT_SUCCESS, "Failed to get param",
return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context));
auto devPath = GetBlockDeviceByMountPoint(partitionName);
LOG(INFO) << "UScriptInstructionBlockCheck::dev path : " << devPath;
UPDATER_ERROR_CHECK(!devPath.empty(), "cannot get block device of partition",
return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context));
int fd = open(devPath.c_str(), O_RDWR | O_LARGEFILE);
UPDATER_ERROR_CHECK(fd != -1, "Failed to open file",
return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context));
std::vector<uint8_t> block_buff(H_BLOCK_SIZE);
BlockSet blk0(std::vector<BlockPair> {BlockPair{0, 1}});
size_t pos = 0;
std::vector<BlockPair>::iterator it = blk0.Begin();
for (; it != blk0.End(); ++it) {
LOG(INFO) << "BlockSet::ReadDataFromBlock lseek64";
ret = lseek64(fd, static_cast<off64_t>(it->first * H_BLOCK_SIZE), SEEK_SET);
UPDATER_ERROR_CHECK(ret != -1, "Failed to seek",
return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context));
size_t size = (it->second - it->first) * H_BLOCK_SIZE;
LOG(INFO) << "BlockSet::ReadDataFromBlock Read " << size << " from block";
UPDATER_ERROR_CHECK(utils::ReadFully(fd, block_buff.data() + pos, size), "Failed to read",
return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context));
pos += size;
}
time_t mountTime = *reinterpret_cast<uint32_t *>(&block_buff[0x400 + 0x2C]);
uint16_t mountCount = *reinterpret_cast<uint16_t *>(&block_buff[0x400 + 0x34]);
if (mountCount > 0) {
std::ostringstream ostr;
ostr << "Device was remounted R/W " << mountCount << "times\nLast remount happened on " <<
ctime(&mountTime) << std::endl;
std::string message = ostr.str();
env.PostMessage("ui_log", message);
}
LOG(INFO) << "UScriptInstructionBlockCheck::Execute Success";
context.PushParam(USCRIPT_SUCCESS);
return USCRIPT_SUCCESS;
}
int32_t UScriptInstructionShaCheck::Execute(uscript::UScriptEnv &env, uscript::UScriptContext &context)
{
UPDATER_ERROR_CHECK(context.GetParamCount() == SHA_CHECK_PARAMS, "Invalid param",
return ReturnAndPushParam(USCRIPT_INVALID_PARAM, context));
UPDATER_CHECK_ONLY_RETURN(!env.IsRetry(), return ReturnAndPushParam(USCRIPT_SUCCESS, context));
std::string partitionName;
int32_t ret = context.GetParam(0, partitionName);
UPDATER_ERROR_CHECK(ret == USCRIPT_SUCCESS, "Failed to get param",
return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context));
std::string blockPairs;
ret = context.GetParam(1, blockPairs);
UPDATER_ERROR_CHECK(ret == USCRIPT_SUCCESS, "Failed to get param",
return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context));
std::string contrastSha;
ret = context.GetParam(SHA_CHECK_SECOND, contrastSha);
UPDATER_ERROR_CHECK(ret == USCRIPT_SUCCESS, "Failed to get param",
return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context));
auto devPath = GetBlockDeviceByMountPoint(partitionName);
LOG(INFO) << "UScriptInstructionShaCheck::dev path : " << devPath;
UPDATER_ERROR_CHECK(!devPath.empty(), "cannot get block device of partition",
return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context));
int fd = open(devPath.c_str(), O_RDWR | O_LARGEFILE);
UPDATER_ERROR_CHECK(fd != -1, "Failed to open file",
return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context));
BlockSet blk;
blk.ParserAndInsert(blockPairs);
std::vector<uint8_t> block_buff(H_BLOCK_SIZE);
SHA256_CTX ctx;
SHA256_Init(&ctx);
std::vector<BlockPair>::iterator it = blk.Begin();
for (; it != blk.End(); ++it) {
ret = lseek64(fd, static_cast<off64_t>(it->first * H_BLOCK_SIZE), SEEK_SET);
UPDATER_ERROR_CHECK(ret != -1, "Failed to seek",
return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context));
for (size_t i = it->first; i < it->second; ++i) {
UPDATER_ERROR_CHECK(utils::ReadFully(fd, block_buff.data(), H_BLOCK_SIZE), "Failed to read",
return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context));
SHA256_Update(&ctx, block_buff.data(), H_BLOCK_SIZE);
}
}
uint8_t digest[SHA256_DIGEST_LENGTH];
SHA256_Final(digest, &ctx);
std::string resultSha = utils::ConvertSha256Hex(digest, SHA256_DIGEST_LENGTH);
UPDATER_ERROR_CHECK(resultSha == contrastSha, "Different sha256, cannot continue",
return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context));
LOG(INFO) << "UScriptInstructionShaCheck::Execute Success";
context.PushParam(USCRIPT_SUCCESS);
return USCRIPT_SUCCESS;
}
}
| 20,479 | 6,652 |
#ifndef LIBCAER_NETWORK_HPP_
#define LIBCAER_NETWORK_HPP_
#include "libcaer.hpp"
#include <libcaer/network.h>
namespace libcaer {
namespace network {
class AEDAT3NetworkHeader : private aedat3_network_header {
public:
AEDAT3NetworkHeader() {
magicNumber = AEDAT3_NETWORK_MAGIC_NUMBER;
sequenceNumber = 0;
versionNumber = AEDAT3_NETWORK_VERSION;
formatNumber = 0;
sourceID = 0;
}
AEDAT3NetworkHeader(const uint8_t *h) {
struct aedat3_network_header header = caerParseNetworkHeader(h);
magicNumber = header.magicNumber;
sequenceNumber = header.sequenceNumber;
versionNumber = header.versionNumber;
formatNumber = header.formatNumber;
sourceID = header.sourceID;
}
int64_t getMagicNumber() const noexcept {
return (magicNumber);
}
bool checkMagicNumber() const noexcept {
return (magicNumber == AEDAT3_NETWORK_MAGIC_NUMBER);
}
int64_t getSequenceNumber() const noexcept {
return (sequenceNumber);
}
void incrementSequenceNumber() noexcept {
sequenceNumber++;
}
int8_t getVersionNumber() const noexcept {
return (versionNumber);
}
bool checkVersionNumber() const noexcept {
return (versionNumber == AEDAT3_NETWORK_VERSION);
}
int8_t getFormatNumber() const noexcept {
return (formatNumber);
}
void setFormatNumber(int8_t format) noexcept {
formatNumber = format;
}
int16_t getSourceID() const noexcept {
return (sourceID);
}
void setSourceID(int16_t source) noexcept {
sourceID = source;
}
};
}
}
#endif /* LIBCAER_NETWORK_HPP_ */
| 1,533 | 589 |
#include <libcryptosec/certificate/Certificate.h>
Certificate::Certificate(X509 *cert)
{
this->cert = cert;
}
Certificate::Certificate(std::string pemEncoded)
throw (EncodeException)
{
BIO *buffer;
buffer = BIO_new(BIO_s_mem());
if (buffer == NULL)
{
throw EncodeException(EncodeException::BUFFER_CREATING, "Certificate::Certificate");
}
if ((unsigned int)(BIO_write(buffer, pemEncoded.c_str(), pemEncoded.size())) != pemEncoded.size())
{
BIO_free(buffer);
throw EncodeException(EncodeException::BUFFER_WRITING, "Certificate::Certificate");
}
this->cert = PEM_read_bio_X509(buffer, NULL, NULL, NULL);
if (this->cert == NULL)
{
BIO_free(buffer);
throw EncodeException(EncodeException::PEM_DECODE, "Certificate::Certificate");
}
BIO_free(buffer);
}
Certificate::Certificate(ByteArray &derEncoded)
throw (EncodeException)
{
BIO *buffer;
buffer = BIO_new(BIO_s_mem());
if (buffer == NULL)
{
throw EncodeException(EncodeException::BUFFER_CREATING, "Certificate::Certificate");
}
if ((unsigned int)(BIO_write(buffer, derEncoded.getDataPointer(), derEncoded.size())) != derEncoded.size())
{
BIO_free(buffer);
throw EncodeException(EncodeException::BUFFER_WRITING, "Certificate::Certificate");
}
this->cert = d2i_X509_bio(buffer, NULL); /* TODO: will the second parameter work fine ? */
if (this->cert == NULL)
{
BIO_free(buffer);
throw EncodeException(EncodeException::DER_DECODE, "Certificate::Certificate");
}
BIO_free(buffer);
}
Certificate::Certificate(const Certificate& cert)
{
this->cert = X509_dup(cert.getX509());
}
Certificate::~Certificate()
{
X509_free(this->cert);
this->cert = NULL;
}
std::string Certificate::getXmlEncoded()
{
return this->getXmlEncoded("");
}
std::string Certificate::getXmlEncoded(std::string tab)
{
std::string ret, string;
ByteArray data;
char temp[15];
long value;
std::vector<Extension *> extensions;
unsigned int i;
ret = "<?xml version=\"1.0\"?>\n";
ret += "<certificate>\n";
ret += "\t<tbsCertificate>\n";
try /* version */
{
value = this->getVersion();
sprintf(temp, "%d", (int)value);
string = temp;
ret += "\t\t<version>" + string + "</version>\n";
}
catch (...)
{
}
try /* Serial Number */
{
value = this->getSerialNumber();
sprintf(temp, "%d", (int)value);
string = temp;
ret += "\t\t<serialNumber>" + string + "</serialNumber>\n";
}
catch (...)
{
}
string = OBJ_nid2ln(OBJ_obj2nid(this->cert->sig_alg->algorithm));
ret += "\t\t<signature>" + string + "</signature>\n";
ret += "\t\t<issuer>\n";
try
{
ret += (this->getIssuer()).getXmlEncoded("\t\t\t");
}
catch (...)
{
}
ret += "\t\t</issuer>\n";
ret += "\t\t<validity>\n";
try
{
ret += "\t\t\t<notBefore>" + ((this->getNotBefore()).getXmlEncoded()) + "</notBefore>\n";
}
catch (...)
{
}
try
{
ret += "\t\t\t<notAfter>" + ((this->getNotAfter()).getXmlEncoded()) + "</notAfter>\n";
}
catch (...)
{
}
ret += "\t\t</validity>\n";
ret += "\t\t<subject>\n";
try
{
ret += (this->getSubject()).getXmlEncoded("\t\t\t");
}
catch (...)
{
}
ret += "\t\t</subject>\n";
ret += "\t\t<subjectPublicKeyInfo>\n";
string = OBJ_nid2ln(OBJ_obj2nid(this->cert->cert_info->key->algor->algorithm));
ret += "\t\t\t<algorithm>" + string + "</algorithm>\n";
data = ByteArray(this->cert->cert_info->key->public_key->data, this->cert->cert_info->key->public_key->length);
string = Base64::encode(data);
ret += "\t\t\t<subjectPublicKey>" + string + "</subjectPublicKey>\n";
ret += "\t\t</subjectPublicKeyInfo>\n";
if (this->cert->cert_info->issuerUID)
{
data = ByteArray(this->cert->cert_info->issuerUID->data, this->cert->cert_info->issuerUID->length);
string = Base64::encode(data);
ret += "\t\t<issuerUniqueID>" + string + "</issuerUniqueID>\n";
}
if (this->cert->cert_info->subjectUID)
{
data = ByteArray(this->cert->cert_info->subjectUID->data, this->cert->cert_info->subjectUID->length);
string = Base64::encode(data);
ret += "\t\t<subjectUniqueID>" + string + "</subjectUniqueID>\n";
}
ret += "\t\t<extensions>\n";
extensions = this->getExtensions();
for (i=0;i<extensions.size();i++)
{
ret += extensions.at(i)->getXmlEncoded("\t\t\t");
delete extensions.at(i);
}
ret += "\t\t</extensions>\n";
ret += "\t</tbsCertificate>\n";
ret += "\t<signatureAlgorithm>\n";
string = OBJ_nid2ln(OBJ_obj2nid(this->cert->sig_alg->algorithm));
ret += "\t\t<algorithm>" + string + "</algorithm>\n";
ret += "\t</signatureAlgorithm>\n";
data = ByteArray(this->cert->signature->data, this->cert->signature->length);
string = Base64::encode(data);
ret += "\t<signatureValue>" + string + "</signatureValue>\n";
ret += "</certificate>\n";
return ret;
}
std::string Certificate::toXml(std::string tab)
{
std::string ret, string;
ByteArray data;
char temp[15];
long value;
std::vector<Extension *> extensions;
unsigned int i;
ret = "<?xml version=\"1.0\"?>\n";
ret += "<certificate>\n";
ret += "\t<tbsCertificate>\n";
try /* version */
{
value = this->getVersion();
sprintf(temp, "%d", (int)value);
string = temp;
ret += "\t\t<version>" + string + "</version>\n";
}
catch (...)
{
}
try /* Serial Number */
{
ret += "\t\t<serialNumber>" + this->getSerialNumberBigInt().toDec() + "</serialNumber>\n";
}
catch (...)
{
}
string = OBJ_nid2ln(OBJ_obj2nid(this->cert->sig_alg->algorithm));
ret += "\t\t<signature>" + string + "</signature>\n";
ret += "\t\t<issuer>\n";
try
{
ret += (this->getIssuer()).getXmlEncoded("\t\t\t");
}
catch (...)
{
}
ret += "\t\t</issuer>\n";
ret += "\t\t<validity>\n";
try
{
ret += "\t\t\t<notBefore>" + ((this->getNotBefore()).getXmlEncoded()) + "</notBefore>\n";
}
catch (...)
{
}
try
{
ret += "\t\t\t<notAfter>" + ((this->getNotAfter()).getXmlEncoded()) + "</notAfter>\n";
}
catch (...)
{
}
ret += "\t\t</validity>\n";
ret += "\t\t<subject>\n";
try
{
ret += (this->getSubject()).getXmlEncoded("\t\t\t");
}
catch (...)
{
}
ret += "\t\t</subject>\n";
ret += "\t\t<subjectPublicKeyInfo>\n";
string = OBJ_nid2ln(OBJ_obj2nid(this->cert->cert_info->key->algor->algorithm));
ret += "\t\t\t<algorithm>" + string + "</algorithm>\n";
data = ByteArray(this->cert->cert_info->key->public_key->data, this->cert->cert_info->key->public_key->length);
string = Base64::encode(data);
ret += "\t\t\t<subjectPublicKey>" + string + "</subjectPublicKey>\n";
ret += "\t\t</subjectPublicKeyInfo>\n";
if (this->cert->cert_info->issuerUID)
{
data = ByteArray(this->cert->cert_info->issuerUID->data, this->cert->cert_info->issuerUID->length);
string = Base64::encode(data);
ret += "\t\t<issuerUniqueID>" + string + "</issuerUniqueID>\n";
}
if (this->cert->cert_info->subjectUID)
{
data = ByteArray(this->cert->cert_info->subjectUID->data, this->cert->cert_info->subjectUID->length);
string = Base64::encode(data);
ret += "\t\t<subjectUniqueID>" + string + "</subjectUniqueID>\n";
}
ret += "\t\t<extensions>\n";
extensions = this->getExtensions();
for (i=0;i<extensions.size();i++)
{
ret += extensions.at(i)->toXml("\t\t\t");
delete extensions.at(i);
}
ret += "\t\t</extensions>\n";
ret += "\t</tbsCertificate>\n";
ret += "\t<signatureAlgorithm>\n";
string = OBJ_nid2ln(OBJ_obj2nid(this->cert->sig_alg->algorithm));
ret += "\t\t<algorithm>" + string + "</algorithm>\n";
ret += "\t</signatureAlgorithm>\n";
data = ByteArray(this->cert->signature->data, this->cert->signature->length);
string = Base64::encode(data);
ret += "\t<signatureValue>" + string + "</signatureValue>\n";
ret += "</certificate>\n";
return ret;
}
std::string Certificate::getPemEncoded() const
throw (EncodeException)
{
BIO *buffer;
int ndata, wrote;
std::string ret;
ByteArray *retTemp;
unsigned char *data;
buffer = BIO_new(BIO_s_mem());
if (buffer == NULL)
{
throw EncodeException(EncodeException::BUFFER_CREATING, "Certificate::getPemEncoded");
}
wrote = PEM_write_bio_X509(buffer, this->cert);
if (!wrote)
{
BIO_free(buffer);
throw EncodeException(EncodeException::PEM_ENCODE, "Certificate::getPemEncoded");
}
ndata = BIO_get_mem_data(buffer, &data);
if (ndata <= 0)
{
BIO_free(buffer);
throw EncodeException(EncodeException::BUFFER_READING, "Certificate::getPemEncoded");
}
retTemp = new ByteArray(data, ndata);
ret = retTemp->toString();
delete retTemp;
BIO_free(buffer);
return ret;
}
ByteArray Certificate::getDerEncoded() const
throw (EncodeException)
{
BIO *buffer;
int ndata, wrote;
ByteArray ret;
unsigned char *data;
buffer = BIO_new(BIO_s_mem());
if (buffer == NULL)
{
throw EncodeException(EncodeException::BUFFER_CREATING, "Certificate::getDerEncoded");
}
wrote = i2d_X509_bio(buffer, this->cert);
if (!wrote)
{
BIO_free(buffer);
throw EncodeException(EncodeException::DER_ENCODE, "Certificate::getDerEncoded");
}
ndata = BIO_get_mem_data(buffer, &data);
if (ndata <= 0)
{
BIO_free(buffer);
throw EncodeException(EncodeException::BUFFER_READING, "Certificate::getDerEncoded");
}
ret = ByteArray(data, ndata);
BIO_free(buffer);
return ret;
}
long int Certificate::getSerialNumber() throw (CertificationException)
{
ASN1_INTEGER *asn1Int;
long ret;
if (this->cert == NULL)
{
throw CertificationException(CertificationException::INVALID_CERTIFICATE, "Certificate::getSerialNumber");
}
/* Here, we have a problem!!! the return value -1 can be error and a valid value. */
asn1Int = X509_get_serialNumber(this->cert);
if (asn1Int == NULL)
{
throw CertificationException(CertificationException::SET_NO_VALUE, "Certificate::getSerialNumber");
}
if (asn1Int->data == NULL)
{
throw CertificationException(CertificationException::INTERNAL_ERROR, "Certificate::getSerialNumber");
}
ret = ASN1_INTEGER_get(asn1Int);
if (ret < 0L)
{
throw CertificationException(CertificationException::INTERNAL_ERROR, "Certificate::getSerialNumber");
}
return ret;
}
BigInteger Certificate::getSerialNumberBigInt() throw (CertificationException)
{
ASN1_INTEGER *asn1Int;
BigInteger ret;
if (this->cert == NULL)
{
throw CertificationException(CertificationException::INVALID_CERTIFICATE, "Certificate::getSerialNumberBytes");
}
/* Here, we have a problem!!! the return value -1 can be error and a valid value. */
asn1Int = X509_get_serialNumber(this->cert);
if (asn1Int == NULL)
{
throw CertificationException(CertificationException::SET_NO_VALUE, "Certificate::getSerialNumberBytes");
}
if (asn1Int->data == NULL)
{
throw CertificationException(CertificationException::INTERNAL_ERROR, "Certificate::getSerialNumberBytes");
}
ret = BigInteger(asn1Int);
return ret;
}
MessageDigest::Algorithm Certificate::getMessageDigestAlgorithm()
throw (MessageDigestException)
{
MessageDigest::Algorithm ret;
ret = MessageDigest::getMessageDigest(OBJ_obj2nid(this->cert->sig_alg->algorithm));
return ret;
}
PublicKey* Certificate::getPublicKey() throw (CertificationException, AsymmetricKeyException)
{
EVP_PKEY *key;
PublicKey *ret;
if (this->cert == NULL)
{
throw CertificationException(CertificationException::INVALID_CERTIFICATE, "Certificate::getPublicKey");
}
key = X509_get_pubkey(this->cert);
if (key == NULL)
{
throw CertificationException(CertificationException::SET_NO_VALUE, "Certificate::getPublicKey");
}
try
{
ret = new PublicKey(key);
}
catch (...)
{
EVP_PKEY_free(key);
throw;
}
return ret;
}
ByteArray Certificate::getPublicKeyInfo()
throw (CertificationException)
{
ByteArray ret;
unsigned int size;
ASN1_BIT_STRING *temp;
if (!this->cert->cert_info->key)
{
throw CertificationException(CertificationException::SET_NO_VALUE, "Certificate::getPublicKeyInfo");
}
temp = this->cert->cert_info->key->public_key;
ret = ByteArray(EVP_MAX_MD_SIZE);
EVP_Digest(temp->data, temp->length, ret.getDataPointer(), &size, EVP_sha1(), NULL);
ret = ByteArray(ret.getDataPointer(), size);
return ret;
}
long Certificate::getVersion() throw (CertificationException)
{
long ret;
/* Here, we have a problem!!! the return value 0 can be error and a valid value. */
if (this->cert == NULL)
{
throw CertificationException(CertificationException::INVALID_CERTIFICATE, "Certificate::getVersion");
}
ret = X509_get_version(this->cert);
if (ret < 0 || ret > 2)
{
throw CertificationException(CertificationException::SET_NO_VALUE, "Certificate::getVersion");
}
return ret;
}
DateTime Certificate::getNotBefore()
{
ASN1_TIME *asn1Time;
asn1Time = X509_get_notBefore(this->cert);
return DateTime(asn1Time);
}
DateTime Certificate::getNotAfter()
{
ASN1_TIME *asn1Time;
asn1Time = X509_get_notAfter(this->cert);
return DateTime(asn1Time);
}
RDNSequence Certificate::getIssuer()
{
RDNSequence name;
if (this->cert)
{
name = RDNSequence(X509_get_issuer_name(this->cert));
}
return name;
}
RDNSequence Certificate::getSubject()
{
RDNSequence name;
if (this->cert)
{
name = RDNSequence(X509_get_subject_name(this->cert));
}
return name;
}
std::vector<Extension*> Certificate::getExtension(Extension::Name extensionName)
{
int next, i;
X509_EXTENSION *ext;
std::vector<Extension *> ret;
Extension *oneExt;
next = X509_get_ext_count(this->cert);
for (i=0;i<next;i++)
{
ext = X509_get_ext(this->cert, i);
if (Extension::getName(ext) == extensionName)
{
switch (Extension::getName(ext))
{
case Extension::KEY_USAGE:
oneExt = new KeyUsageExtension(ext);
break;
case Extension::EXTENDED_KEY_USAGE:
oneExt = new ExtendedKeyUsageExtension(ext);
break;
case Extension::AUTHORITY_KEY_IDENTIFIER:
oneExt = new AuthorityKeyIdentifierExtension(ext);
break;
case Extension::CRL_DISTRIBUTION_POINTS:
oneExt = new CRLDistributionPointsExtension(ext);
break;
case Extension::AUTHORITY_INFORMATION_ACCESS:
oneExt = new AuthorityInformationAccessExtension(ext);
break;
case Extension::BASIC_CONSTRAINTS:
oneExt = new BasicConstraintsExtension(ext);
break;
case Extension::CERTIFICATE_POLICIES:
oneExt = new CertificatePoliciesExtension(ext);
break;
case Extension::ISSUER_ALTERNATIVE_NAME:
oneExt = new IssuerAlternativeNameExtension(ext);
break;
case Extension::SUBJECT_ALTERNATIVE_NAME:
oneExt = new SubjectAlternativeNameExtension(ext);
break;
case Extension::SUBJECT_INFORMATION_ACCESS:
oneExt = new SubjectInformationAccessExtension(ext);
break;
case Extension::SUBJECT_KEY_IDENTIFIER:
oneExt = new SubjectKeyIdentifierExtension(ext);
break;
default:
oneExt = new Extension(ext);
break;
}
ret.push_back(oneExt);
}
}
return ret;
}
std::vector<Extension*> Certificate::getExtensions()
{
int next, i;
X509_EXTENSION *ext;
std::vector<Extension *> ret;
Extension *oneExt;
next = X509_get_ext_count(this->cert);
for (i=0;i<next;i++)
{
ext = X509_get_ext(this->cert, i);
switch (Extension::getName(ext))
{
case Extension::KEY_USAGE:
oneExt = new KeyUsageExtension(ext);
break;
case Extension::EXTENDED_KEY_USAGE:
oneExt = new ExtendedKeyUsageExtension(ext);
break;
case Extension::AUTHORITY_KEY_IDENTIFIER:
oneExt = new AuthorityKeyIdentifierExtension(ext);
break;
case Extension::CRL_DISTRIBUTION_POINTS:
oneExt = new CRLDistributionPointsExtension(ext);
break;
case Extension::AUTHORITY_INFORMATION_ACCESS:
oneExt = new AuthorityInformationAccessExtension(ext);
break;
case Extension::BASIC_CONSTRAINTS:
oneExt = new BasicConstraintsExtension(ext);
break;
case Extension::CERTIFICATE_POLICIES:
oneExt = new CertificatePoliciesExtension(ext);
break;
case Extension::ISSUER_ALTERNATIVE_NAME:
oneExt = new IssuerAlternativeNameExtension(ext);
break;
case Extension::SUBJECT_ALTERNATIVE_NAME:
oneExt = new SubjectAlternativeNameExtension(ext);
break;
case Extension::SUBJECT_INFORMATION_ACCESS:
oneExt = new SubjectInformationAccessExtension(ext);
break;
case Extension::SUBJECT_KEY_IDENTIFIER:
oneExt = new SubjectKeyIdentifierExtension(ext);
break;
default:
oneExt = new Extension(ext);
break;
}
ret.push_back(oneExt);
}
return ret;
}
std::vector<Extension *> Certificate::getUnknownExtensions()
{
int next, i;
X509_EXTENSION *ext;
std::vector<Extension *> ret;
Extension *oneExt;
next = X509_get_ext_count(this->cert);
for (i=0;i<next;i++)
{
ext = X509_get_ext(this->cert, i);
switch (Extension::getName(ext))
{
case Extension::UNKNOWN:
oneExt = new Extension(ext);
ret.push_back(oneExt);
default:
break;
}
}
return ret;
}
ByteArray Certificate::getFingerPrint(MessageDigest::Algorithm algorithm) const
throw (CertificationException, EncodeException, MessageDigestException)
{
ByteArray ret, derEncoded;
MessageDigest messageDigest;
derEncoded = this->getDerEncoded();
messageDigest.init(algorithm);
ret = messageDigest.doFinal(derEncoded);
return ret;
}
bool Certificate::verify(PublicKey &publicKey)
{
int ok;
ok = X509_verify(this->cert, publicKey.getEvpPkey());
return (ok == 1);
}
X509* Certificate::getX509() const
{
return this->cert;
}
CertificateRequest Certificate::getNewCertificateRequest(PrivateKey &privateKey, MessageDigest::Algorithm algorithm)
throw (CertificationException)
{
X509_REQ* req = NULL;
req = X509_to_X509_REQ(this->cert, privateKey.getEvpPkey(), MessageDigest::getMessageDigest(algorithm));
if (!req)
{
throw CertificationException(CertificationException::INTERNAL_ERROR, "Certificate::getNewCertificateRequest");
}
return CertificateRequest(req);
}
Certificate& Certificate::operator =(const Certificate& value)
{
if (this->cert)
{
X509_free(this->cert);
}
this->cert = X509_dup(value.getX509());
return (*this);
}
bool Certificate::operator ==(const Certificate& value)
{
return X509_cmp(this->cert, value.getX509()) == 0;
}
bool Certificate::operator !=(const Certificate& value)
{
return !this->operator==(value);
}
| 18,190 | 7,371 |
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/crt/Api.h>
#include <aws/crt/Optional.h>
#include <aws/testing/aws_test_harness.h>
const char *s_test_str = "This is a string, that should be long enough to avoid small string optimizations";
static int s_OptionalCopySafety(struct aws_allocator *allocator, void *ctx)
{
(void)ctx;
{
Aws::Crt::ApiHandle apiHandle(allocator);
Aws::Crt::Optional<Aws::Crt::String> str1(s_test_str);
Aws::Crt::Optional<Aws::Crt::String> strCpyAssigned = str1;
Aws::Crt::Optional<Aws::Crt::String> strCpyConstructedOptional(strCpyAssigned);
Aws::Crt::Optional<Aws::Crt::String> strCpyConstructedValue(*strCpyAssigned);
// now force data access just to check there's not a segfault hiding somewhere.
ASSERT_STR_EQUALS(s_test_str, str1->c_str());
ASSERT_STR_EQUALS(s_test_str, strCpyAssigned->c_str());
ASSERT_STR_EQUALS(s_test_str, strCpyConstructedOptional->c_str());
ASSERT_STR_EQUALS(s_test_str, strCpyConstructedValue->c_str());
}
return AWS_OP_SUCCESS;
}
AWS_TEST_CASE(OptionalCopySafety, s_OptionalCopySafety)
static int s_OptionalMoveSafety(struct aws_allocator *allocator, void *ctx)
{
(void)ctx;
{
Aws::Crt::ApiHandle apiHandle(allocator);
Aws::Crt::Optional<Aws::Crt::String> str1(s_test_str);
Aws::Crt::Optional<Aws::Crt::String> strMoveAssigned = std::move(str1);
ASSERT_STR_EQUALS(s_test_str, strMoveAssigned->c_str());
Aws::Crt::Optional<Aws::Crt::String> strMoveValueAssigned = std::move(*strMoveAssigned);
ASSERT_STR_EQUALS(s_test_str, strMoveValueAssigned->c_str());
Aws::Crt::Optional<Aws::Crt::String> strMoveConstructed(std::move(strMoveValueAssigned));
ASSERT_STR_EQUALS(s_test_str, strMoveConstructed->c_str());
Aws::Crt::Optional<Aws::Crt::String> strMoveValueConstructed(std::move(*strMoveConstructed));
ASSERT_STR_EQUALS(s_test_str, strMoveValueConstructed->c_str());
}
return AWS_OP_SUCCESS;
}
AWS_TEST_CASE(OptionalMoveSafety, s_OptionalMoveSafety)
class CopyMoveTester
{
public:
CopyMoveTester() : m_copied(false), m_moved(false) {}
CopyMoveTester(const CopyMoveTester &) : m_copied(true), m_moved(false) {}
CopyMoveTester(CopyMoveTester &&) : m_copied(false), m_moved(true) {}
CopyMoveTester &operator=(const CopyMoveTester &)
{
m_copied = true;
m_moved = false;
return *this;
}
CopyMoveTester &operator=(CopyMoveTester &&)
{
m_copied = false;
m_moved = true;
return *this;
}
~CopyMoveTester() {}
bool m_copied;
bool m_moved;
};
static int s_OptionalCopyAndMoveSemantics(struct aws_allocator *allocator, void *ctx)
{
(void)ctx;
{
Aws::Crt::ApiHandle apiHandle(allocator);
CopyMoveTester initialItem;
ASSERT_FALSE(initialItem.m_copied);
ASSERT_FALSE(initialItem.m_moved);
Aws::Crt::Optional<CopyMoveTester> copyConstructedValue(initialItem);
ASSERT_TRUE(copyConstructedValue->m_copied);
ASSERT_FALSE(copyConstructedValue->m_moved);
Aws::Crt::Optional<CopyMoveTester> copyConstructedOptional(copyConstructedValue);
ASSERT_TRUE(copyConstructedOptional->m_copied);
ASSERT_FALSE(copyConstructedOptional->m_moved);
Aws::Crt::Optional<CopyMoveTester> copyAssignedValue = initialItem;
ASSERT_TRUE(copyAssignedValue->m_copied);
ASSERT_FALSE(copyAssignedValue->m_moved);
Aws::Crt::Optional<CopyMoveTester> copyAssignedOptional = copyConstructedOptional;
ASSERT_TRUE(copyAssignedOptional->m_copied);
ASSERT_FALSE(copyAssignedOptional->m_moved);
Aws::Crt::Optional<CopyMoveTester> moveConstructedValue(std::move(initialItem));
ASSERT_FALSE(moveConstructedValue->m_copied);
ASSERT_TRUE(moveConstructedValue->m_moved);
Aws::Crt::Optional<CopyMoveTester> moveConstructedOptional(std::move(moveConstructedValue));
ASSERT_FALSE(moveConstructedOptional->m_copied);
ASSERT_TRUE(moveConstructedOptional->m_moved);
Aws::Crt::Optional<CopyMoveTester> moveAssignedValue = std::move(*moveConstructedOptional);
ASSERT_FALSE(moveAssignedValue->m_copied);
ASSERT_TRUE(moveAssignedValue->m_moved);
Aws::Crt::Optional<CopyMoveTester> moveAssignedOptional = std::move(moveAssignedValue);
ASSERT_FALSE(moveAssignedOptional->m_copied);
ASSERT_TRUE(moveAssignedOptional->m_moved);
}
return AWS_OP_SUCCESS;
}
AWS_TEST_CASE(OptionalCopyAndMoveSemantics, s_OptionalCopyAndMoveSemantics)
| 4,749 | 1,710 |
/*
Maximum Sum Circular Subarray
Given a circular array C of integers represented by A, find the maximum possible sum of a non-empty subarray of C.
Here, a circular array means the end of the array connects to the beginning of the array. (Formally, C[i] = A[i] when 0 <= i < A.length, and C[i+A.length] = C[i] when i >= 0.)
Also, a subarray may only include each element of the fixed buffer A at most once. (Formally, for a subarray C[i], C[i+1], ..., C[j], there does not exist i <= k1, k2 <= j with k1 % A.length = k2 % A.length.)
Example 1:
Input: [1,-2,3,-2]
Output: 3
Explanation: Subarray [3] has maximum sum 3
Example 2:
Input: [5,-3,5]
Output: 10
Explanation: Subarray [5,5] has maximum sum 5 + 5 = 10
Example 3:
Input: [3,-1,2,-1]
Output: 4
Explanation: Subarray [2,-1,3] has maximum sum 2 + (-1) + 3 = 4
Example 4:
Input: [3,-2,2,-3]
Output: 3
Explanation: Subarray [3] and [3,-2,2] both have maximum sum 3
Example 5:
Input: [-2,-3,-1]
Output: -1
Explanation: Subarray [-1] has maximum sum -1
Note:
-30000 <= A[i] <= 30000
1 <= A.length <= 30000
*/
class Solution {
public:
int maxSubarraySumCircular(vector<int>& A) {
int total_sum = 0, global_max = INT_MIN, global_min = INT_MAX,
local_min = 0, local_max = 0;
// kadane's algorithm
for (int a : A) {
local_max = max(a, local_max + a);
global_max = max(global_max, local_max);
local_min = min(a, local_min + a);
global_min = min(global_min, local_min);
total_sum += a;
}
// case 1: max subarray is not circular
// ______________________________
// | | Max subarray| |
// 0 --------------------------- N-1
// case 2: max subarray is circular
// _____________________________
// | | Max su|barray| |
// 0 -----------|N-1------------ 2N-1
// which is equal to
// ______________________________
// | max | Min subarray| subarray|
// 0 --------------------------- N-1
// max(the max subarray sum, the total sum - the min subarray sum)
return global_max > 0 ? max(global_max, total_sum - global_min)
: global_max;
}
}; | 2,156 | 795 |
// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2015 Intel Corporation. All Rights Reserved.
#include "../include/librealsense2/rs.hpp"
#include "../include/librealsense2/rsutil.h"
#include "core/video.h"
#include "align.h"
#include "archive.h"
#include "context.h"
#include "environment.h"
namespace librealsense
{
template<class MAP_DEPTH> void deproject_depth(float * points, const rs2_intrinsics & intrin, const uint16_t * depth, MAP_DEPTH map_depth)
{
for (int y = 0; y<intrin.height; ++y)
{
for (int x = 0; x<intrin.width; ++x)
{
const float pixel[] = { (float)x, (float)y };
rs2_deproject_pixel_to_point(points, &intrin, pixel, map_depth(*depth++));
points += 3;
}
}
}
const float3 * depth_to_points(uint8_t* image, const rs2_intrinsics &depth_intrinsics, const uint16_t * depth_image, float depth_scale)
{
deproject_depth(reinterpret_cast<float *>(image), depth_intrinsics, depth_image, [depth_scale](uint16_t z) { return depth_scale * z; });
return reinterpret_cast<float3 *>(image);
}
float3 transform(const rs2_extrinsics *extrin, const float3 &point) { float3 p = {}; rs2_transform_point_to_point(&p.x, extrin, &point.x); return p; }
float2 project(const rs2_intrinsics *intrin, const float3 & point) { float2 pixel = {}; rs2_project_point_to_pixel(&pixel.x, intrin, &point.x); return pixel; }
float2 pixel_to_texcoord(const rs2_intrinsics *intrin, const float2 & pixel) { return{ (pixel.x + 0.5f) / intrin->width, (pixel.y + 0.5f) / intrin->height }; }
float2 project_to_texcoord(const rs2_intrinsics *intrin, const float3 & point) { return pixel_to_texcoord(intrin, project(intrin, point)); }
void processing_block::set_processing_callback(frame_processor_callback_ptr callback)
{
std::lock_guard<std::mutex> lock(_mutex);
_callback = callback;
}
void processing_block::set_output_callback(frame_callback_ptr callback)
{
_source.set_callback(callback);
}
processing_block::processing_block()
: _source_wrapper(_source)
{
_source.init(std::make_shared<metadata_parser_map>());
}
void processing_block::invoke(frame_holder f)
{
auto callback = _source.begin_callback();
try
{
if (_callback)
{
frame_interface* ptr = nullptr;
std::swap(f.frame, ptr);
_callback->on_frame((rs2_frame*)ptr, _source_wrapper.get_c_wrapper());
}
}
catch(...)
{
LOG_ERROR("Exception was thrown during user processing callback!");
}
}
void synthetic_source::frame_ready(frame_holder result)
{
_actual_source.invoke_callback(std::move(result));
}
frame_interface* synthetic_source::allocate_points(std::shared_ptr<stream_profile_interface> stream, frame_interface* original)
{
auto vid_stream = dynamic_cast<video_stream_profile_interface*>(stream.get());
if (vid_stream)
{
frame_additional_data data{};
data.frame_number = original->get_frame_number();
data.timestamp = original->get_frame_timestamp();
data.timestamp_domain = original->get_frame_timestamp_domain();
data.metadata_size = 0;
data.system_time = _actual_source.get_time();
auto res = _actual_source.alloc_frame(RS2_EXTENSION_POINTS, vid_stream->get_width() * vid_stream->get_height() * sizeof(float) * 5, data, true);
if (!res) throw wrong_api_call_sequence_exception("Out of frame resources!");
res->set_sensor(original->get_sensor());
res->set_stream(stream);
return res;
}
return nullptr;
}
frame_interface* synthetic_source::allocate_video_frame(std::shared_ptr<stream_profile_interface> stream,
frame_interface* original,
int new_bpp,
int new_width,
int new_height,
int new_stride,
rs2_extension frame_type)
{
video_frame* vf = nullptr;
if (new_bpp == 0 || (new_width == 0 && new_stride == 0) || new_height == 0)
{
// If the user wants to delegate width, height and etc to original frame, it must be a video frame
if (!rs2_is_frame_extendable_to((rs2_frame*)original, RS2_EXTENSION_VIDEO_FRAME, nullptr))
{
throw std::runtime_error("If original frame is not video frame, you must specify new bpp, width/stide and height!");
}
vf = static_cast<video_frame*>(original);
}
frame_additional_data data{};
data.frame_number = original->get_frame_number();
data.timestamp = original->get_frame_timestamp();
data.timestamp_domain = original->get_frame_timestamp_domain();
data.metadata_size = 0;
data.system_time = _actual_source.get_time();
auto width = new_width;
auto height = new_height;
auto bpp = new_bpp * 8;
auto stride = new_stride;
if (bpp == 0)
{
bpp = vf->get_bpp();
}
if (width == 0 && stride == 0)
{
width = vf->get_width();
stride = width * bpp / 8;
}
else if (width == 0)
{
width = stride * 8 / bpp;
}
else if (stride == 0)
{
stride = width * bpp / 8;
}
if (height == 0)
{
height = vf->get_height();
}
auto res = _actual_source.alloc_frame(frame_type, stride * height, data, true);
if (!res) throw wrong_api_call_sequence_exception("Out of frame resources!");
vf = static_cast<video_frame*>(res);
vf->assign(width, height, stride, bpp);
vf->set_sensor(original->get_sensor());
res->set_stream(stream);
if (frame_type == RS2_EXTENSION_DEPTH_FRAME)
{
original->acquire();
(dynamic_cast<depth_frame*>(res))->set_original(original);
}
return res;
}
int get_embeded_frames_size(frame_interface* f)
{
if (f == nullptr) return 0;
if (auto c = dynamic_cast<composite_frame*>(f))
return static_cast<int>(c->get_embedded_frames_count());
return 1;
}
void copy_frames(frame_holder from, frame_interface**& target)
{
if (auto comp = dynamic_cast<composite_frame*>(from.frame))
{
auto frame_buff = comp->get_frames();
for (size_t i = 0; i < comp->get_embedded_frames_count(); i++)
{
std::swap(*target, frame_buff[i]);
target++;
}
from.frame->disable_continuation();
}
else
{
*target = nullptr; // "move" the frame ref into target
std::swap(*target, from.frame);
target++;
}
}
frame_interface* synthetic_source::allocate_composite_frame(std::vector<frame_holder> holders)
{
frame_additional_data d {};
auto req_size = 0;
for (auto&& f : holders)
req_size += get_embeded_frames_size(f.frame);
auto res = _actual_source.alloc_frame(RS2_EXTENSION_COMPOSITE_FRAME, req_size * sizeof(rs2_frame*), d, true);
if (!res) return nullptr;
auto cf = static_cast<composite_frame*>(res);
auto frames = cf->get_frames();
for (auto&& f : holders)
copy_frames(std::move(f), frames);
frames -= req_size;
auto releaser = [frames, req_size]()
{
for (auto i = 0; i < req_size; i++)
{
frames[i]->release();
frames[i] = nullptr;
}
};
frame_continuation release_frames(releaser, nullptr);
cf->attach_continuation(std::move(release_frames));
cf->set_stream(cf->first()->get_stream());
return res;
}
pointcloud::pointcloud()
:_depth_intrinsics_ptr(nullptr),
_depth_units_ptr(nullptr),
_mapped_intrinsics_ptr(nullptr),
_extrinsics_ptr(nullptr),
_mapped(nullptr),
_depth_stream_uid(0)
{
auto on_frame = [this](rs2::frame f, const rs2::frame_source& source)
{
auto inspect_depth_frame = [this](const rs2::frame& depth)
{
auto depth_frame = (frame_interface*)depth.get();
std::lock_guard<std::mutex> lock(_mutex);
if (!_stream.get() || _depth_stream_uid != depth_frame->get_stream()->get_unique_id())
{
_stream = depth_frame->get_stream()->clone();
_depth_stream_uid = depth_frame->get_stream()->get_unique_id();
environment::get_instance().get_extrinsics_graph().register_same_extrinsics(*_stream, *depth_frame->get_stream());
_depth_intrinsics_ptr = nullptr;
_depth_units_ptr = nullptr;
}
bool found_depth_intrinsics = false;
bool found_depth_units = false;
if (!_depth_intrinsics_ptr)
{
auto stream_profile = depth_frame->get_stream();
if (auto video = dynamic_cast<video_stream_profile_interface*>(stream_profile.get()))
{
_depth_intrinsics = video->get_intrinsics();
_depth_intrinsics_ptr = &_depth_intrinsics;
found_depth_intrinsics = true;
}
}
if (!_depth_units_ptr)
{
auto sensor = depth_frame->get_sensor();
_depth_units = sensor->get_option(RS2_OPTION_DEPTH_UNITS).query();
_depth_units_ptr = &_depth_units;
found_depth_units = true;
}
if (found_depth_units != found_depth_intrinsics)
{
throw wrong_api_call_sequence_exception("Received depth frame that doesn't provide either intrinsics or depth units!");
}
};
auto inspect_other_frame = [this](const rs2::frame& other)
{
auto other_frame = (frame_interface*)other.get();
std::lock_guard<std::mutex> lock(_mutex);
if (_mapped.get() != other_frame->get_stream().get())
{
_mapped = other_frame->get_stream();
_mapped_intrinsics_ptr = nullptr;
_extrinsics_ptr = nullptr;
}
if (!_mapped_intrinsics_ptr)
{
if (auto video = dynamic_cast<video_stream_profile_interface*>(_mapped.get()))
{
_mapped_intrinsics = video->get_intrinsics();
_mapped_intrinsics_ptr = &_mapped_intrinsics;
}
}
if (_stream && !_extrinsics_ptr)
{
if ( environment::get_instance().get_extrinsics_graph().try_fetch_extrinsics(
*_stream, *other_frame->get_stream(), &_extrinsics
))
{
_extrinsics_ptr = &_extrinsics;
}
}
};
auto process_depth_frame = [this](const rs2::depth_frame& depth)
{
frame_holder res = get_source().allocate_points(_stream, (frame_interface*)depth.get());
auto pframe = (points*)(res.frame);
auto depth_data = (const uint16_t*)depth.get_data();
//auto original_depth = ((depth_frame*)depth.get())->get_original_depth();
//if (original_depth) depth_data = (const uint16_t*)original_depth->get_frame_data();
auto points = depth_to_points((uint8_t*)pframe->get_vertices(), *_depth_intrinsics_ptr, depth_data, *_depth_units_ptr);
auto vid_frame = depth.as<rs2::video_frame>();
float2* tex_ptr = pframe->get_texture_coordinates();
rs2_intrinsics mapped_intr;
rs2_extrinsics extr;
bool map_texture = false;
{
std::lock_guard<std::mutex> lock(_mutex);
if (_extrinsics_ptr && _mapped_intrinsics_ptr)
{
mapped_intr = *_mapped_intrinsics_ptr;
extr = *_extrinsics_ptr;
map_texture = true;
}
}
if (map_texture)
{
for (int y = 0; y < vid_frame.get_height(); ++y)
{
for (int x = 0; x < vid_frame.get_width(); ++x)
{
if (points->z)
{
auto trans = transform(&extr, *points);
auto tex_xy = project_to_texcoord(&mapped_intr, trans);
*tex_ptr = tex_xy;
}
else
{
*tex_ptr = { 0.f, 0.f };
}
++points;
++tex_ptr;
}
}
}
get_source().frame_ready(std::move(res));
};
if (auto composite = f.as<rs2::frameset>())
{
auto depth = composite.first_or_default(RS2_STREAM_DEPTH);
if (depth)
{
inspect_depth_frame(depth);
process_depth_frame(depth);
}
else
{
composite.foreach(inspect_other_frame);
}
}
else
{
if (f.get_profile().stream_type() == RS2_STREAM_DEPTH)
{
inspect_depth_frame(f);
process_depth_frame(f);
}
else
{
inspect_other_frame(f);
}
}
};
auto callback = new rs2::frame_processor_callback<decltype(on_frame)>(on_frame);
processing_block::set_processing_callback(std::shared_ptr<rs2_frame_processor_callback>(callback));
}
//void colorize::set_color_map(rs2_color_map cm)
//{
// std::lock_guard<std::mutex> lock(_mutex);
// switch(cm)
// {
// case RS2_COLOR_MAP_CLASSIC:
// _cm = &classic;
// break;
// case RS2_COLOR_MAP_JET:
// _cm = &jet;
// break;
// case RS2_COLOR_MAP_HSV:
// _cm = &hsv;
// break;
// default:
// _cm = &classic;
// }
//}
//void colorize::histogram_equalization(bool enable)
//{
// std::lock_guard<std::mutex> lock(_mutex);
// _equalize = enable;
//}
//colorize::colorize(std::shared_ptr<uvc::time_service> ts)
// : processing_block(RS2_EXTENSION_VIDEO_FRAME, ts), _cm(&classic), _equalize(true)
//{
// auto on_frame = [this](std::vector<rs2::frame> frames, const rs2::frame_source& source)
// {
// std::lock_guard<std::mutex> lock(_mutex);
// for (auto&& f : frames)
// {
// if (f.get_stream_type() == RS2_STREAM_DEPTH)
// {
// const auto max_depth = 0x10000;
// static uint32_t histogram[max_depth];
// memset(histogram, 0, sizeof(histogram));
// auto vf = f.as<video_frame>();
// auto width = vf.get_width();
// auto height = vf.get_height();
// auto depth_image = vf.get_frame_data();
// for (auto i = 0; i < width*height; ++i) ++histogram[depth_image[i]];
// for (auto i = 2; i < max_depth; ++i) histogram[i] += histogram[i - 1]; // Build a cumulative histogram for the indices in [1,0xFFFF]
// for (auto i = 0; i < width*height; ++i)
// {
// auto d = depth_image[i];
// //if (d)
// //{
// // auto f = histogram[d] / (float)histogram[0xFFFF]; // 0-255 based on histogram location
// // auto c = map.get(f);
// // rgb_image[i * 3 + 0] = c.x;
// // rgb_image[i * 3 + 1] = c.y;
// // rgb_image[i * 3 + 2] = c.z;
// //}
// //else
// //{
// // rgb_image[i * 3 + 0] = 0;
// // rgb_image[i * 3 + 1] = 0;
// // rgb_image[i * 3 + 2] = 0;
// //}
// }
// }
// }
// };
// auto callback = new rs2::frame_processor_callback<decltype(on_frame)>(on_frame);
// set_processing_callback(std::shared_ptr<rs2_frame_processor_callback>(callback));
//}
template<class GET_DEPTH, class TRANSFER_PIXEL>
void align_images(const rs2_intrinsics & depth_intrin, const rs2_extrinsics & depth_to_other,
const rs2_intrinsics & other_intrin, GET_DEPTH get_depth, TRANSFER_PIXEL transfer_pixel)
{
// Iterate over the pixels of the depth image
#pragma omp parallel for schedule(dynamic)
for (int depth_y = 0; depth_y < depth_intrin.height; ++depth_y)
{
int depth_pixel_index = depth_y * depth_intrin.width;
for (int depth_x = 0; depth_x < depth_intrin.width; ++depth_x, ++depth_pixel_index)
{
// Skip over depth pixels with the value of zero, we have no depth data so we will not write anything into our aligned images
if (float depth = get_depth(depth_pixel_index))
{
// Map the top-left corner of the depth pixel onto the other image
float depth_pixel[2] = { depth_x - 0.5f, depth_y - 0.5f }, depth_point[3], other_point[3], other_pixel[2];
rs2_deproject_pixel_to_point(depth_point, &depth_intrin, depth_pixel, depth);
rs2_transform_point_to_point(other_point, &depth_to_other, depth_point);
rs2_project_point_to_pixel(other_pixel, &other_intrin, other_point);
const int other_x0 = static_cast<int>(other_pixel[0] + 0.5f);
const int other_y0 = static_cast<int>(other_pixel[1] + 0.5f);
// Map the bottom-right corner of the depth pixel onto the other image
depth_pixel[0] = depth_x + 0.5f; depth_pixel[1] = depth_y + 0.5f;
rs2_deproject_pixel_to_point(depth_point, &depth_intrin, depth_pixel, depth);
rs2_transform_point_to_point(other_point, &depth_to_other, depth_point);
rs2_project_point_to_pixel(other_pixel, &other_intrin, other_point);
const int other_x1 = static_cast<int>(other_pixel[0] + 0.5f);
const int other_y1 = static_cast<int>(other_pixel[1] + 0.5f);
if (other_x0 < 0 || other_y0 < 0 || other_x1 >= other_intrin.width || other_y1 >= other_intrin.height)
continue;
// Transfer between the depth pixels and the pixels inside the rectangle on the other image
for (int y = other_y0; y <= other_y1; ++y)
{
for (int x = other_x0; x <= other_x1; ++x)
{
transfer_pixel(depth_pixel_index, y * other_intrin.width + x);
}
}
}
}
}
}
align::align(rs2_stream to_stream)
: _depth_intrinsics_ptr(nullptr),
_depth_units_ptr(nullptr),
_other_intrinsics_ptr(nullptr),
_depth_to_other_extrinsics_ptr(nullptr),
_other_bytes_per_pixel_ptr(nullptr),
_other_stream_type(to_stream)
{
auto on_frame = [this](rs2::frame f, const rs2::frame_source& source)
{
auto inspect_depth_frame = [this, &source](const rs2::frame& depth, const rs2::frame& other)
{
auto depth_frame = (frame_interface*)depth.get();
std::lock_guard<std::mutex> lock(_mutex);
bool found_depth_intrinsics = false;
bool found_depth_units = false;
if (!_depth_intrinsics_ptr)
{
auto stream_profile = depth_frame->get_stream();
if (auto video = dynamic_cast<video_stream_profile_interface*>(stream_profile.get()))
{
_depth_intrinsics = video->get_intrinsics();
_depth_intrinsics_ptr = &_depth_intrinsics;
found_depth_intrinsics = true;
}
}
if (!_depth_units_ptr)
{
auto sensor = depth_frame->get_sensor();
_depth_units = sensor->get_option(RS2_OPTION_DEPTH_UNITS).query();
_depth_units_ptr = &_depth_units;
found_depth_units = true;
}
if (found_depth_units != found_depth_intrinsics)
{
throw wrong_api_call_sequence_exception("Received depth frame that doesn't provide either intrinsics or depth units!");
}
if (!_depth_stream_profile.get())
{
_depth_stream_profile = depth_frame->get_stream();
environment::get_instance().get_extrinsics_graph().register_same_extrinsics(*_depth_stream_profile, *depth_frame->get_stream());
auto vid_frame = depth.as<rs2::video_frame>();
_width = vid_frame.get_width();
_height = vid_frame.get_height();
}
if (!_depth_to_other_extrinsics_ptr && _depth_stream_profile && _other_stream_profile)
{
environment::get_instance().get_extrinsics_graph().try_fetch_extrinsics(*_depth_stream_profile, *_other_stream_profile, &_depth_to_other_extrinsics);
_depth_to_other_extrinsics_ptr = &_depth_to_other_extrinsics;
}
if (_depth_intrinsics_ptr && _depth_units_ptr && _depth_stream_profile && _other_bytes_per_pixel_ptr &&
_depth_to_other_extrinsics_ptr && _other_intrinsics_ptr && _other_stream_profile && other)
{
std::vector<frame_holder> frames(2);
auto other_frame = (frame_interface*)other.get();
other_frame->acquire();
frames[0] = frame_holder{ other_frame };
frame_holder out_frame = get_source().allocate_video_frame(_depth_stream_profile, depth_frame,
_other_bytes_per_pixel / 8, _other_intrinsics.width, _other_intrinsics.height, 0, RS2_EXTENSION_DEPTH_FRAME);
auto p_out_frame = reinterpret_cast<uint16_t*>(((frame*)(out_frame.frame))->data.data());
memset(p_out_frame, _depth_stream_profile->get_format() == RS2_FORMAT_DISPARITY16 ? 0xFF : 0x00, _other_intrinsics.height * _other_intrinsics.width * sizeof(uint16_t));
auto p_depth_frame = reinterpret_cast<const uint16_t*>(((frame*)(depth_frame))->get_frame_data());
align_images(*_depth_intrinsics_ptr, *_depth_to_other_extrinsics_ptr, *_other_intrinsics_ptr,
[p_depth_frame, this](int z_pixel_index)
{
return _depth_units * p_depth_frame[z_pixel_index];
},
[p_out_frame, p_depth_frame/*, p_out_other_frame, other_bytes_per_pixel*/](int z_pixel_index, int other_pixel_index)
{
p_out_frame[other_pixel_index] = p_out_frame[other_pixel_index] ?
std::min( (int)(p_out_frame[other_pixel_index]), (int)(p_depth_frame[z_pixel_index]) )
: p_depth_frame[z_pixel_index];
});
frames[1] = std::move(out_frame);
auto composite = get_source().allocate_composite_frame(std::move(frames));
get_source().frame_ready(std::move(composite));
}
};
auto inspect_other_frame = [this, &source](const rs2::frame& other)
{
auto other_frame = (frame_interface*)other.get();
std::lock_guard<std::mutex> lock(_mutex);
if (_other_stream_type != other_frame->get_stream()->get_stream_type())
return;
if (!_other_stream_profile.get())
{
_other_stream_profile = other_frame->get_stream();
}
if (!_other_bytes_per_pixel_ptr)
{
auto vid_frame = other.as<rs2::video_frame>();
_other_bytes_per_pixel = vid_frame.get_bytes_per_pixel();
_other_bytes_per_pixel_ptr = &_other_bytes_per_pixel;
}
if (!_other_intrinsics_ptr)
{
if (auto video = dynamic_cast<video_stream_profile_interface*>(_other_stream_profile.get()))
{
_other_intrinsics = video->get_intrinsics();
_other_intrinsics_ptr = &_other_intrinsics;
}
}
//source.frame_ready(other);
};
if (auto composite = f.as<rs2::frameset>())
{
auto depth = composite.first_or_default(RS2_STREAM_DEPTH);
auto other = composite.first_or_default(_other_stream_type);
if (other)
{
inspect_other_frame(other);
}
if (depth)
{
inspect_depth_frame(depth, other);
}
}
};
auto callback = new rs2::frame_processor_callback<decltype(on_frame)>(on_frame);
processing_block::set_processing_callback(std::shared_ptr<rs2_frame_processor_callback>(callback));
}
}
| 27,488 | 8,243 |
#include "MapControlBaseTpl.hpp"
| 34 | 14 |
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <queue>
using namespace std;
int x,y,fx[10][3],dis[105][105];
struct Point
{
int x,y;
};
void bfs()
{
memset(dis,-1,sizeof(dis));
dis[x][y]=0;
fx[1][1]=fx[2][1]=1,fx[3][1]=fx[4][1]=-1,fx[5][1]=fx[6][1]=2,fx[7][1]=fx[8][1]=-2;
fx[1][2]=fx[3][2]=2,fx[2][2]=fx[4][2]=-2,fx[5][2]=fx[7][2]=1,fx[6][2]=fx[8][2]=-1;
queue<Point> q;
Point p;
p.x=x,p.y=y;
q.push(p);
while (!q.empty())
{
Point x;
x=q.front();
q.pop();
for (int i=1;i<=8;i++)
{
int nowx=x.x+fx[i][1],nowy=x.y+fx[i][2];
if (nowx<0||nowy<0||nowx>100||nowy>100) continue;
if (dis[nowx][nowy]!=-1) continue;
dis[nowx][nowy]=dis[x.x][x.y]+1;
Point X;
X.x=nowx,X.y=nowy;
q.push(X);
if (nowx==50&&nowy==50) return;
}
}
}
int main()
{
freopen("code.in","r",stdin);freopen("std.out","w",stdout);
int xp,yp,xs,ys;
scanf("%d%d%d%d",&xp,&yp,&xs,&ys);
x=abs(xs-xp),y=abs(ys-yp);
int ans=0;
while (x+y>=50)
{
if (x<y) swap(x,y);
if (x-4>=y*2) x-=4;
else x-=4,y-=2;
ans+=2;
}
x+=50,y+=50;
bfs();
printf("%d\n",ans+dis[50][50]);
return 0;
}
| 1,158 | 701 |
class Solution {
public:
int XXX(int x) {
long long int ans = x;
long long int square= 0;
while(ans){
long long int temp = ans/2;
square= temp*temp;
ans = temp;
if(square<= x){
break;
}
}
while(square<= x){
ans++;
square= ans*ans;
}
return ans-1;
}
};
| 417 | 121 |
/**
** Isaac Genome Alignment Software
** Copyright (c) 2010-2017 Illumina, Inc.
** All rights reserved.
**
** This software is provided under the terms and conditions of the
** GNU GENERAL PUBLIC LICENSE Version 3
**
** You should have received a copy of the GNU GENERAL PUBLIC LICENSE Version 3
** along with this program. If not, see
** <https://github.com/illumina/licenses/>.
**
** \file XmlWriter.hh
**
** Helper classes for composing xml
**
** \author Roman Petrovski
**/
#ifndef iSAAC_XML_XML_WRITER_HH
#define iSAAC_XML_XML_WRITER_HH
#include <libxml/xmlwriter.h>
#include <iostream>
#include <boost/noncopyable.hpp>
#include "common/Debug.hh"
#include "common/Exceptions.hh"
namespace isaac
{
namespace xml
{
class XmlWriterException : public common::IsaacException
{
public:
XmlWriterException(const std::string &message) : common::IsaacException(message)
{
}
};
class XmlWriter: boost::noncopyable
{
std::ostream &os_;
xmlTextWriterPtr xmlWriter_;
static int xmlOutputWriteCallback(void * context, const char * buffer, int len);
public:
explicit XmlWriter(std::ostream &os);
~XmlWriter();
void close();
XmlWriter &startElement(const char *name);
XmlWriter &startElement(const std::string &name) {return startElement(name.c_str());}
XmlWriter &endElement();
XmlWriter &writeText(const char *text);
template <typename T> XmlWriter &writeElement(const char *name, const T& value)
{
return (startElement(name) << value).endElement();
}
template <typename T> XmlWriter &writeElement(const std::string &name, const T& value)
{
return writeElement(name.c_str(), value);
}
template <typename T> XmlWriter &writeAttribute(const char *name, const T& value)
{
const std::string strValue = boost::lexical_cast<std::string>(value);
const int written = xmlTextWriterWriteAttribute(xmlWriter_, BAD_CAST name, BAD_CAST strValue.c_str());
if (-1 == written)
{
BOOST_THROW_EXCEPTION(XmlWriterException(
std::string("xmlTextWriterWriteAttribute returned -1 for attribute name: ") + name + " value: " + strValue));
}
return *this;
}
template <typename T> XmlWriter &operator <<(const T&t)
{
return writeText(boost::lexical_cast<std::string>(t).c_str());
}
struct BlockMacroSupport
{
bool set_;
BlockMacroSupport() : set_(true){}
void reset () {set_ = false;};
operator bool() const {return set_;}
};
// This is to allow macro ISAAC_XML_WRITER_ELEMENT_BLOCK to work
operator BlockMacroSupport() const {return BlockMacroSupport();}
};
/**
* \brief Macro for controling xml element scope. Automatically closes the element at the end of the block
*/
#define ISAAC_XML_WRITER_ELEMENT_BLOCK(writer, name) for(xml::XmlWriter::BlockMacroSupport iSaacElementBlockVariable = writer.startElement(name); iSaacElementBlockVariable; iSaacElementBlockVariable.reset(), writer.endElement())
} // namespace xml
} // namespace isaac
#endif // #ifndef iSAAC_XML_XML_WRITER_HH
| 3,138 | 982 |
#include "PaintField.h"
#include <QPainter>
//We need to register this Type in MTQ
MTQ_QML_REGISTER_PLUGIN(PaintField)
//Constructor
PaintField::PaintField(QQuickItem *)
{
setHeight(600);
setWidth(600);
setStrokeHue(0);
setBackgroundBrightness(255);
}
void PaintField::paint(QPainter *painter)
{
painter->setRenderHint(QPainter::Antialiasing);
QRect rect(4, 4, width() - 8, height() - 8);
painter->fillRect(rect, m_bgColor);
for (int strokeI = 0; strokeI < m_strokes.size(); strokeI++)
{
painter->setPen(QPen(QBrush(m_strokeColors.at(strokeI)),4));
if (m_strokes.at(strokeI).size() == 1)
painter->drawPoint(m_strokes.at(strokeI).at(0));
else if (m_strokes.at(strokeI).size() > 1) {
for (int i = 0; i < m_strokes.at(strokeI).size() - 1; i++) {
painter->drawLine(m_strokes.at(strokeI).at(i),
m_strokes.at(strokeI).at(i+1));
}
}
}
}
qreal PaintField::strokeHue() const
{
return m_strokeHue;
}
void PaintField::setStrokeHue(const qreal hue)
{
m_strokeHue = hue;
}
int PaintField::backgroundBrightness() const
{
return m_backgroundBrightness;
}
void PaintField::setBackgroundBrightness(const int brightness)
{
m_backgroundBrightness = brightness;
m_bgColor = QColor().fromHsv(1, 0, brightness);
update();
}
void PaintField::processContactDown(mtq::ContactEvent *event)
{
m_strokes.push_back(QVector<QPointF>());
m_strokeColors.push_back(QColor().fromHsvF(m_strokeHue, 1, 1));
QPointF center = event->mappedCenter();
m_strokes.last().push_back(center);
update();
}
void PaintField::processContactMove(mtq::ContactEvent *event)
{
QPointF center = event->mappedCenter();
m_strokes.last().push_back(center);
update();
}
void PaintField::processContactUp(mtq::ContactEvent *event)
{
update();
}
| 1,753 | 763 |
// Copyright (C) 2004 Free Software Foundation
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING. If not, write to the Free
// Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
// USA.
// 27.6.1.3 unformatted input functions
#include <cwchar> // for wcslen
#include <istream>
#include <sstream>
#include <testsuite_hooks.h>
// [patch] bits/istream.tcc - getline(char_type*,streamsize,char_type)
// http://gcc.gnu.org/ml/libstdc++/2000-07/msg00003.html
void
test05()
{
const wchar_t* charray = L"\n"
L"a\n"
L"aa\n"
L"aaa\n"
L"aaaa\n"
L"aaaaa\n"
L"aaaaaa\n"
L"aaaaaaa\n"
L"aaaaaaaa\n"
L"aaaaaaaaa\n"
L"aaaaaaaaaa\n"
L"aaaaaaaaaaa\n"
L"aaaaaaaaaaaa\n"
L"aaaaaaaaaaaaa\n"
L"aaaaaaaaaaaaaa\n";
bool test __attribute__((unused)) = true;
const std::streamsize it = 5;
std::streamsize br = 0;
wchar_t tmp[it];
std::wstringbuf sb(charray, std::ios_base::in);
std::wistream ifs(&sb);
std::streamsize blen = std::wcslen(charray);
VERIFY(!(!ifs));
while(ifs.getline(tmp, it) || ifs.gcount())
{
br += ifs.gcount();
if(ifs.eof())
{
// Just sanity checks to make sure we've extracted the same
// number of chars that were in the streambuf
VERIFY( br == blen );
// Also, we should only set the failbit if we could
// _extract_ no chars from the stream, i.e. the first read
// returned EOF.
VERIFY( ifs.fail() && ifs.gcount() == 0 );
}
else if(ifs.fail())
{
// delimiter not read
//
// either
// -> extracted no characters
// or
// -> n - 1 characters are stored
ifs.clear(ifs.rdstate() & ~std::ios::failbit);
VERIFY( (ifs.gcount() == 0) || (std::wcslen(tmp) == it - 1) );
VERIFY( !(!ifs) );
continue;
}
else
{
// delimiter was read.
//
// -> wcslen(__s) < n - 1
// -> delimiter was seen -> gcount() > wcslen(__s)
VERIFY( ifs.gcount() == static_cast<std::streamsize>(std::wcslen(tmp)
+ 1) );
continue;
}
}
}
int
main()
{
test05();
return 0;
}
| 2,747 | 1,027 |
#include "Experiment/Experiment.hh"
/*******************************************************************************
* Project: BaBar detector at the SLAC PEP-II B-factory
* Package: EvtGenBase
* File: $Id: EvtPropBreitWigner.cc 427 2010-01-14 13:25:53Z stroili $
* Author: Alexei Dvoretskii, dvoretsk@slac.stanford.edu, 2001-2002
*
* Copyright (C) 2002 Caltech
*******************************************************************************/
#include <math.h>
#include "EvtGenBase/EvtConst.hh"
#include "EvtGenBase/EvtPropBreitWigner.hh"
EvtPropBreitWigner::EvtPropBreitWigner(double m0, double g0)
: EvtPropagator(m0,g0)
{}
EvtPropBreitWigner::EvtPropBreitWigner(const EvtPropBreitWigner& other)
: EvtPropagator(other)
{}
EvtPropBreitWigner::~EvtPropBreitWigner()
{}
EvtAmplitude<EvtPoint1D>* EvtPropBreitWigner::clone() const
{
return new EvtPropBreitWigner(*this);
}
EvtComplex EvtPropBreitWigner::amplitude(const EvtPoint1D& x) const
{
double m = x.value();
EvtComplex value = sqrt(_g0/EvtConst::twoPi)/(m-_m0-EvtComplex(0.0,_g0/2.));
return value;
}
| 1,101 | 453 |
class Solution {
public:
bool searchMatrix(vector<vector<int> > &matrix, int target) {
int posx = 0, posy = 0;
int n = matrix.size();
int m = matrix[0].size();
do {
if (matrix[posx][posy] == target) return true;
if (posx + 1 < n && matrix[posx+1][posy] <= target) posx ++;
else posy++;
} while (posx < n && posy < m);
return false;
}
};
| 439 | 148 |
/*############################################################################
# Copyright Intel Corporation
#
# SPDX-License-Identifier: MIT
############################################################################*/
#pragma once
#include <algorithm>
#include <iostream>
#include <utility>
#include <tuple>
#include "vpl/preview/detail/string_helpers.hpp"
namespace oneapi {
namespace vpl {
#define DECLARE_MEMBER_ACCESS(father, type, name) \
/*! @brief Returns name value. */ \
/*! @return name value. */ \
type get_##name() const { \
return param_.name; \
} \
/*! @brief Sets name value. */ \
/*! @param[in] name Value. */ \
/*! @return Reference to the instance. */ \
father &set_##name(type name) { \
param_.name = name; \
return *this; \
}
#define DECLARE_INNER_MEMBER_ACCESS(father, type, parent, name) \
/*! @brief Returns name value. */ \
/*! @return name value. */ \
type get_##name() const { \
return param_.parent.name; \
} \
/*! @brief Sets name value. */ \
/*! @param[in] name Value. */ \
/*! @return Reference to the instance. */ \
father &set_##name(type name) { \
param_.parent.name = name; \
return *this; \
}
#define DECLARE_INNER_MEMBER_ARRAY_ACCESS(father, type, size, parent, name) \
/*! @brief Returns name value. */ \
/*! @return name value. */ \
auto get_##name() const { \
return param_.parent.name; \
} \
/*! @brief Sets name value. */ \
/*! @param[in] name Value. */ \
/*! @return Reference to the instance. */ \
father &set_##name(type name[size]) { \
std::copy(name, name + size, param_.parent.name); \
return *this; \
}
/// @brief Holds general video params applicable for all kind of sessions.
class video_param {
public:
/// @brief Constructs params and initialize them with default values.
video_param() : param_() {}
video_param(const video_param ¶m) : param_(param.param_) {
clear_extension_buffers();
}
video_param& operator=(const video_param& other){
param_ = other.param_;
clear_extension_buffers();
return *this;
}
/// @brief Dtor
virtual ~video_param() {
param_ = {};
}
public:
/// @brief Returns pointer to raw data
/// @return Pointer to raw data
mfxVideoParam *getMfx() {
return ¶m_;
}
public:
DECLARE_MEMBER_ACCESS(video_param, uint32_t, AllocId)
DECLARE_MEMBER_ACCESS(video_param, uint16_t, AsyncDepth)
DECLARE_MEMBER_ACCESS(video_param, uint16_t, Protected)
/// @brief Returns i/o memory pattern value.
/// @return i/o memory pattern value.
io_pattern get_IOPattern() const {
return (io_pattern)param_.IOPattern;
}
/// @brief Sets i/o memory pattern value.
/// @param[in] IOPattern i/o memory pattern.
/// @return Reference to this object
video_param &set_IOPattern(io_pattern IOPattern) {
param_.IOPattern = (uint32_t)IOPattern;
return *this;
}
/// @brief Attaches extension buffers to the video params
/// @param[in] buffer Array of extension buffers
/// @param[in] num Number of extension buffers
/// @return Reference to this object
video_param &set_extension_buffers(mfxExtBuffer **buffer, uint16_t num) {
param_.ExtParam = buffer;
param_.NumExtParam = num;
return *this;
}
/// @brief Clear extension buffers from the video params
/// @param[in] buffer Array of extension buffers
/// @param[in] num Number of extension buffers
/// @return Reference to this object
video_param &clear_extension_buffers() {
param_.ExtParam = nullptr;
param_.NumExtParam = 0;
return *this;
}
/// @brief Friend operator to print out state of the class in human readable form.
/// @param[inout] out Reference to the stream to write.
/// @param[in] p Referebce to the video_param instance to dump the state.
/// @return Reference to the stream.
friend std::ostream &operator<<(std::ostream &out, const video_param &p);
protected:
/// @brief Raw data
mfxVideoParam param_;
};
inline std::ostream &operator<<(std::ostream &out, const video_param &p) {
out << "Base:" << std::endl;
out << detail::space(detail::INTENT, out, "AllocId = ") << p.param_.AllocId << std::endl;
out << detail::space(detail::INTENT, out, "AsyncDepth = ")
<< detail::NotSpecifyed0(p.param_.AsyncDepth) << std::endl;
out << detail::space(detail::INTENT, out, "Protected = ") << p.param_.Protected << std::endl;
out << detail::space(detail::INTENT, out, "IOPattern = ")
<< detail::IOPattern2String(p.param_.IOPattern) << std::endl;
return out;
}
class codec_video_param;
class vpp_video_param;
/// @brief Holds general frame related params.
class frame_info {
public:
/// @brief Default ctor.
frame_info() : param_() {}
/// @brief Copy ctor.
/// @param[in] other another object to use as data source
frame_info(const frame_info &other) {
param_ = other.param_;
}
/// @brief Constructs object from the raw data.
/// @param[in] other another object to use as data source
explicit frame_info(const mfxFrameInfo &other) {
param_ = other;
}
/// @brief Copy operator.
/// @param[in] other another object to use as data source
/// @returns Reference to this object
frame_info &operator=(const frame_info &other) {
param_ = other.param_;
return *this;
}
DECLARE_MEMBER_ACCESS(frame_info, uint16_t, BitDepthLuma)
DECLARE_MEMBER_ACCESS(frame_info, uint16_t, BitDepthChroma)
DECLARE_MEMBER_ACCESS(frame_info, uint16_t, Shift)
DECLARE_MEMBER_ACCESS(frame_info, mfxFrameId, FrameId)
/// @brief Returns color format fourCC value.
/// @return color format fourCC value.
color_format_fourcc get_FourCC() const {
return (color_format_fourcc)param_.FourCC;
}
/// @brief Sets color format fourCC value.
/// @param[in] FourCC color format fourCC.
/// @return Reference to this object
frame_info &set_FourCC(color_format_fourcc FourCC) {
param_.FourCC = (uint32_t)FourCC;
return *this;
}
/// @todo below group valid for formats != P8
/// @brief Returns frame size.
/// @return Pair of width and height.
auto get_frame_size() const {
return std::pair(param_.Width, param_.Height);
}
/// @brief Sets frame size value.
/// @param[in] size pair of width and height.
/// @return Reference to this object
frame_info &set_frame_size(std::pair<uint32_t, uint32_t> size) {
param_.Width = std::get<0>(size);
param_.Height = std::get<1>(size);
return *this;
}
/// @brief Returns ROI.
/// @return Two pairs: pair of left corner and pair of size.
auto get_ROI() const {
return std::pair(std::pair(param_.CropX, param_.CropY),
std::pair(param_.CropW, param_.CropH));
}
/// @brief Sets ROI.
/// @param[in] roi Two pairs: pair of left corner and pair of size.
/// @return Reference to this object
frame_info &set_ROI(
std::pair<std::pair<uint16_t, uint16_t>, std::pair<uint16_t, uint16_t>> roi) {
param_.CropX = std::get<0>(std::get<0>(roi));
param_.CropY = std::get<1>(std::get<0>(roi));
param_.CropW = std::get<0>(std::get<1>(roi));
param_.CropH = std::get<1>(std::get<1>(roi));
return *this;
}
/// @todo below method is valid for P8 format only
DECLARE_MEMBER_ACCESS(frame_info, uint64_t, BufferSize)
/// @brief Returns frame rate value.
/// @return Pair of numerator and denominator.
auto get_frame_rate() const {
return std::pair(param_.FrameRateExtN, param_.FrameRateExtD);
}
/// @brief Sets frame rate value.
/// @param[in] rate pair of numerator and denominator.
/// @return Reference to this object
frame_info &set_frame_rate(std::pair<uint32_t, uint32_t> rate) {
param_.FrameRateExtN = std::get<0>(rate);
param_.FrameRateExtD = std::get<1>(rate);
return *this;
}
/// @brief Returns aspect ratio.
/// @return Pair of width and height of aspect ratio.
auto get_aspect_ratio() const {
return std::pair(param_.AspectRatioW, param_.AspectRatioH);
}
/// @brief Sets aspect ratio.
/// @param[in] ratio pair of width and height of aspect ratio.
/// @return Reference to this object
frame_info &set_aspect_ratio(std::pair<uint32_t, uint32_t> ratio) {
param_.AspectRatioW = std::get<0>(ratio);
param_.AspectRatioH = std::get<1>(ratio);
return *this;
}
/// @brief Returns picture structure value.
/// @return picture structure value.
pic_struct get_PicStruct() const {
return (pic_struct)param_.PicStruct;
}
/// @brief Sets picture structure value.
/// @param[in] PicStruct picture structure.
/// @return Reference to this object
frame_info &set_PicStruct(pic_struct PicStruct) {
param_.PicStruct = (uint16_t)PicStruct;
return *this;
}
/// @brief Returns chroma format value.
/// @return chroma format value.
chroma_format_idc get_ChromaFormat() const {
return (chroma_format_idc)param_.ChromaFormat;
}
/// @brief Sets chroma format value.
/// @param[in] ChromaFormat chroma format.
/// @return Reference to this object
frame_info &set_ChromaFormat(chroma_format_idc ChromaFormat) {
param_.ChromaFormat = (uint32_t)ChromaFormat;
return *this;
}
/// @brief Friend class
friend class codec_video_param;
/// @brief Friend class
friend class vpp_video_param;
/// @brief Friend operator to print out state of the class in human readable form.
/// @param[inout] out Reference to the stream to write.
/// @param[in] p Reference to the codec_video_param instance to dump the state.
/// @return Reference to the stream.
friend std::ostream &operator<<(std::ostream &out, const codec_video_param &p);
/// @brief Friend operator to print out state of the class in human readable form.
/// @param[inout] out Reference to the stream to write.
/// @param[in] v Reference to the vpp_video_param instance to dump the state.
/// @return Reference to the stream.
friend std::ostream &operator<<(std::ostream &out, const vpp_video_param &v);
/// @brief Friend operator to print out state of the class in human readable form.
/// @param[inout] out Reference to the stream to write.
/// @param[in] f Reference to the frame_info instance to dump the state.
/// @return Reference to the stream.
friend std::ostream &operator<<(std::ostream &out, const frame_info &f);
/// @brief Provides raw data.
/// @return Raw data.
mfxFrameInfo operator()() const {
return param_;
}
protected:
/// @brief Raw data
mfxFrameInfo param_;
};
inline std::ostream &operator<<(std::ostream &out, const frame_info &f) {
out << detail::space(detail::INTENT, out, "BitDepthLuma = ") << f.param_.BitDepthLuma
<< std::endl;
out << detail::space(detail::INTENT, out, "BitDepthChroma = ") << f.param_.BitDepthChroma
<< std::endl;
out << detail::space(detail::INTENT, out, "Shift = ")
<< detail::NotSpecifyed0(f.param_.Shift) << std::endl;
out << detail::space(detail::INTENT, out, "Color Format = ")
<< detail::FourCC2String(f.param_.FourCC) << std::endl;
if (f.param_.FourCC == MFX_FOURCC_P8) {
out << detail::space(detail::INTENT, out, "BufferSize = ") << f.param_.BufferSize
<< std::endl;
}
else {
out << detail::space(detail::INTENT, out, "Size [W,H] = [") << f.param_.Width << ","
<< f.param_.Height << "]" << std::endl;
out << detail::space(detail::INTENT, out, "ROI [X,Y,W,H] = [") << f.param_.CropX << ","
<< f.param_.CropY << "," << f.param_.CropW << "," << f.param_.CropH << "]" << std::endl;
}
out << detail::space(detail::INTENT, out, "FrameRate [N:D]= ")
<< detail::NotSpecifyed0(f.param_.FrameRateExtN) << ":"
<< detail::NotSpecifyed0(f.param_.FrameRateExtD) << std::endl;
if (0 == f.param_.AspectRatioW && 0 == f.param_.AspectRatioH) {
out << detail::space(detail::INTENT, out, "AspecRato [W,H]= [") << "Unset"
<< "]" << std::endl;
}
else {
out << detail::space(detail::INTENT, out, "AspecRato [W,H]= [") << f.param_.AspectRatioW
<< "," << f.param_.AspectRatioH << "]" << std::endl;
}
out << detail::space(detail::INTENT, out, "PicStruct = ")
<< detail::PicStruct2String(f.param_.PicStruct) << std::endl;
out << detail::space(detail::INTENT, out, "ChromaFormat = ")
<< detail::ChromaFormat2String(f.param_.ChromaFormat) << std::endl;
return out;
}
/// @brief Holds general frame related params.
class frame_data {
public:
/// @brief Default ctor.
frame_data() : param_() {}
/// @brief Copy ctor.
/// @param[in] other another object to use as data source
frame_data(const frame_data &other) {
param_ = other.param_;
}
/// @brief Constructs object from the raw data.
/// @param[in] other another object to use as data source
explicit frame_data(const mfxFrameData &other) {
param_ = other;
}
/// @brief Copy operator.
/// @param[in] other another object to use as data source
/// @return Reference to this object
frame_data &operator=(const frame_data &other) {
param_ = other.param_;
return *this;
}
DECLARE_MEMBER_ACCESS(frame_data, uint16_t, MemType)
/// @brief Returns pitch value.
/// @return Pitch value.
uint32_t get_pitch() const {
return ((uint32_t)param_.PitchHigh << 16) | (uint32_t)(uint32_t)param_.PitchLow;
}
/// @brief Sets pitch value.
/// @param[in] pitch Pitch.
void set_pitch(uint32_t pitch) {
param_.PitchHigh = (uint16_t)(pitch >> 16);
param_.PitchLow = (uint16_t)(pitch & 0xFFFF);
}
DECLARE_MEMBER_ACCESS(frame_data, uint64_t, TimeStamp)
DECLARE_MEMBER_ACCESS(frame_data, uint32_t, FrameOrder)
DECLARE_MEMBER_ACCESS(frame_data, uint16_t, Locked)
DECLARE_MEMBER_ACCESS(frame_data, uint16_t, Corrupted)
DECLARE_MEMBER_ACCESS(frame_data, uint16_t, DataFlag)
/// @brief Gets pointer for formats with 1 plane.
/// @return Pointer for formats with 1 plane.
auto get_plane_ptrs_1() const {
return param_.R;
}
/// @brief Gets pointer for formats with 1 plane (BGRA).
/// @return Pointer for formats with 1 plane (BGRA).
auto get_plane_ptrs_1_BGRA() const {
return param_.B;
}
/// @brief Gets pointer for formats with 2 planes.
/// @return Pointers for formats with 2 planes. Pointers for planes layout is: Y, UV.
auto get_plane_ptrs_2() const {
return std::pair(param_.R, param_.G);
}
/// @brief Gets pointer for formats with 3 planes.
/// @return Pointers for formats with 3 planes. Pointers for planes layout is: R, G, B or Y, U, V.
auto get_plane_ptrs_3() const {
return std::make_tuple(param_.R, param_.G, param_.B);
}
/// @brief Gets pointer for formats with 4 planes.
/// @return Pointers for formats with 4 planes. Pointers for planes layout is: R, G, B, A.
auto get_plane_ptrs_4() const {
return std::make_tuple(param_.R, param_.G, param_.B, param_.A);
}
/// @brief Friend operator to print out state of the class in human readable form.
/// @param[inout] out Reference to the stream to write.
/// @param[in] f Reference to the frame_data instance to dump the state.
/// @return Reference to the stream.
friend std::ostream &operator<<(std::ostream &out, const frame_data &f);
protected:
/// @brief Raw data
mfxFrameData param_;
};
inline std::ostream &operator<<(std::ostream &out, const frame_data &f) {
out << detail::space(detail::INTENT, out, "MemType = ")
<< detail::MemType2String(f.param_.MemType) << std::endl;
out << detail::space(detail::INTENT, out, "PitchHigh = ") << f.param_.PitchHigh << std::endl;
out << detail::space(detail::INTENT, out, "PitchLow = ") << f.param_.PitchLow << std::endl;
out << detail::space(detail::INTENT, out, "TimeStamp = ")
<< detail::TimeStamp2String(static_cast<uint64_t>(f.param_.TimeStamp)) << std::endl;
out << detail::space(detail::INTENT, out, "FrameOrder = ") << f.param_.FrameOrder << std::endl;
out << detail::space(detail::INTENT, out, "Locked = ") << f.param_.Locked << std::endl;
out << detail::space(detail::INTENT, out, "Corrupted = ")
<< detail::Corruption2String(f.param_.Corrupted) << std::endl;
out << detail::space(detail::INTENT, out, "DataFlag = ")
<< detail::TimeStamp2String(f.param_.DataFlag) << std::endl;
return out;
}
/// @brief Holds general codec-specific params applicable for any decoder and encoder.
class codec_video_param : public video_param {
protected:
/// @brief Constructs params and initialize them with default values.
codec_video_param() : video_param() {}
codec_video_param(const codec_video_param ¶m) : video_param(param) {}
codec_video_param& operator=(const codec_video_param ¶m){
video_param::operator=(param);
return *this;
}
public:
DECLARE_INNER_MEMBER_ACCESS(codec_video_param, uint16_t, mfx, LowPower);
DECLARE_INNER_MEMBER_ACCESS(codec_video_param, uint16_t, mfx, BRCParamMultiplier);
/// @brief Returns codec fourCC value.
/// @return codec fourCC value.
codec_format_fourcc get_CodecId() const {
return (codec_format_fourcc)param_.mfx.CodecId;
}
/// @brief Sets codec fourCC value.
/// @param[in] CodecID codec fourCC.
/// @return Reference to this object
codec_video_param &set_CodecId(codec_format_fourcc CodecID) {
param_.mfx.CodecId = (uint32_t)CodecID;
return *this;
}
DECLARE_INNER_MEMBER_ACCESS(codec_video_param, uint16_t, mfx, CodecProfile);
DECLARE_INNER_MEMBER_ACCESS(codec_video_param, uint16_t, mfx, CodecLevel);
DECLARE_INNER_MEMBER_ACCESS(codec_video_param, uint16_t, mfx, NumThread);
/// @brief Returns frame_info value.
/// @return frame info value.
frame_info get_frame_info() const {
return frame_info(param_.mfx.FrameInfo);
}
/// @brief Sets name value.
/// @param[in] name Value.
/// @return Reference to this object
codec_video_param &set_frame_info(frame_info name) {
param_.mfx.FrameInfo = name();
return *this;
}
/// Friend operator to print out state of the class in human readable form.
friend std::ostream &operator<<(std::ostream &out, const codec_video_param &p);
};
inline std::ostream &operator<<(std::ostream &out, const codec_video_param &p) {
const video_param &v = dynamic_cast<const video_param &>(p);
out << v;
out << "Codec:" << std::endl;
out << detail::space(detail::INTENT, out, "LowPower = ")
<< detail::TriState2String(p.param_.mfx.LowPower) << std::endl;
out << detail::space(detail::INTENT, out, "BRCParamMultiplier = ")
<< p.param_.mfx.BRCParamMultiplier << std::endl;
out << detail::space(detail::INTENT, out, "CodecId = ")
<< detail::FourCC2String(p.param_.mfx.CodecId) << std::endl;
out << detail::space(detail::INTENT, out, "CodecProfile = ") << p.param_.mfx.CodecProfile
<< std::endl;
out << detail::space(detail::INTENT, out, "CodecLevel = ") << p.param_.mfx.CodecLevel
<< std::endl;
out << detail::space(detail::INTENT, out, "NumThread = ") << p.param_.mfx.NumThread
<< std::endl;
out << "FrameInfo:" << std::endl;
out << frame_info(p.param_.mfx.FrameInfo) << std::endl;
return out;
}
/// @brief Holds encoder specific params.
class encoder_video_param : public codec_video_param {
public:
/// @brief Constructs params and initialize them with default values.
encoder_video_param() : codec_video_param() {}
/// @brief Returns TargetUsage value.
/// @return TargetUsage Target Usage value.
target_usage get_TargetUsage() const {
return (target_usage)param_.mfx.TargetUsage;
}
/// @brief Sets Target Usage value.
/// @param[in] TargetUsage Target Usage.
/// @return Reference to this object
encoder_video_param &set_TargetUsage(target_usage TargetUsage) {
param_.mfx.CodecId = (uint32_t)TargetUsage;
return *this;
}
DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, GopPicSize);
DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint32_t, mfx, GopRefDist);
DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, GopOptFlag);
DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, IdrInterval);
/// @brief Returns rate control method value.
/// @return rate control method value.
rate_control_method get_RateControlMethod() const {
return (rate_control_method)param_.mfx.RateControlMethod;
}
/// @brief Sets rate control method value.
/// @param[in] RateControlMethod rate control method.
/// @return Reference to this object
encoder_video_param &set_RateControlMethod(rate_control_method RateControlMethod) {
param_.mfx.RateControlMethod = (uint32_t)RateControlMethod;
return *this;
}
DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, InitialDelayInKB);
DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, QPI);
DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, Accuracy);
DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, BufferSizeInKB);
DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, TargetKbps);
DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, QPP);
DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, ICQQuality);
DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, MaxKbps);
DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, QPB);
DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, Convergence);
DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, NumSlice);
DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, NumRefFrame);
DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, EncodedOrder);
/// @brief Friend operator to print out state of the class in human readable form.
/// @param[inout] out Reference to the stream to write.
/// @param[in] e Reference to the encoder_video_param instance to dump the state.
/// @return Reference to the stream.
friend std::ostream &operator<<(std::ostream &out, const encoder_video_param &e);
};
inline std::ostream &operator<<(std::ostream &out, const encoder_video_param &e) {
const codec_video_param &c = dynamic_cast<const codec_video_param &>(e);
out << c;
out << "Encoder:" << std::endl;
out << detail::space(detail::INTENT, out, "TargetUsage = ")
<< detail::NotSpecifyed0(e.param_.mfx.TargetUsage) << std::endl;
out << detail::space(detail::INTENT, out, "GopPicSize = ")
<< detail::NotSpecifyed0(e.param_.mfx.GopPicSize) << std::endl;
out << detail::space(detail::INTENT, out, "GopRefDist = ")
<< detail::NotSpecifyed0(e.param_.mfx.GopRefDist) << std::endl;
out << detail::space(detail::INTENT, out, "GopOptFlag = ")
<< detail::GopOptFlag2String(e.param_.mfx.GopOptFlag) << std::endl;
out << detail::space(detail::INTENT, out, "IdrInterval = ") << e.param_.mfx.IdrInterval
<< std::endl;
out << detail::space(detail::INTENT, out, "RateControlMethod = ")
<< detail::RateControlMethod2String(e.param_.mfx.RateControlMethod) << std::endl;
out << detail::space(detail::INTENT, out, "InitialDelayInKB = ")
<< e.param_.mfx.InitialDelayInKB << std::endl;
out << detail::space(detail::INTENT, out, "QPI = ") << e.param_.mfx.QPI
<< std::endl;
out << detail::space(detail::INTENT, out, "Accuracy = ") << e.param_.mfx.Accuracy
<< std::endl;
out << detail::space(detail::INTENT, out, "BufferSizeInKB = ") << e.param_.mfx.BufferSizeInKB
<< std::endl;
out << detail::space(detail::INTENT, out, "TargetKbps = ") << e.param_.mfx.TargetKbps
<< std::endl;
out << detail::space(detail::INTENT, out, "QPP = ") << e.param_.mfx.QPP
<< std::endl;
out << detail::space(detail::INTENT, out, "ICQQuality = ") << e.param_.mfx.ICQQuality
<< std::endl;
out << detail::space(detail::INTENT, out, "MaxKbps = ") << e.param_.mfx.MaxKbps
<< std::endl;
out << detail::space(detail::INTENT, out, "QPB = ") << e.param_.mfx.QPB
<< std::endl;
out << detail::space(detail::INTENT, out, "Convergence = ") << e.param_.mfx.Convergence
<< std::endl;
out << detail::space(detail::INTENT, out, "NumSlice = ")
<< detail::NotSpecifyed0(e.param_.mfx.NumSlice) << std::endl;
out << detail::space(detail::INTENT, out, "NumRefFrame = ")
<< detail::NotSpecifyed0(e.param_.mfx.NumRefFrame) << std::endl;
out << detail::space(detail::INTENT, out, "EncodedOrder = ")
<< detail::Boolean2String(e.param_.mfx.EncodedOrder) << std::endl;
return out;
}
/// @brief Holds decoder specific params.
class decoder_video_param : public codec_video_param {
public:
/// @brief Constructs params and initialize them with default values.
decoder_video_param() : codec_video_param() {}
explicit decoder_video_param(const codec_video_param &other) : codec_video_param(other) {}
DECLARE_INNER_MEMBER_ACCESS(decoder_video_param, uint16_t, mfx, DecodedOrder);
DECLARE_INNER_MEMBER_ACCESS(decoder_video_param, uint16_t, mfx, ExtendedPicStruct);
DECLARE_INNER_MEMBER_ACCESS(decoder_video_param, uint32_t, mfx, TimeStampCalc);
DECLARE_INNER_MEMBER_ACCESS(decoder_video_param, uint16_t, mfx, SliceGroupsPresent);
DECLARE_INNER_MEMBER_ACCESS(decoder_video_param, uint16_t, mfx, MaxDecFrameBuffering);
DECLARE_INNER_MEMBER_ACCESS(decoder_video_param, uint16_t, mfx, EnableReallocRequest);
/// @brief Friend operator to print out state of the class in human readable form.
/// @param[inout] out Reference to the stream to write.
/// @param[in] d Reference to the decoder_video_param instance to dump the state.
/// @return Reference to the stream.
friend std::ostream &operator<<(std::ostream &out, const decoder_video_param &d);
};
inline std::ostream &operator<<(std::ostream &out, const decoder_video_param &d) {
const codec_video_param &c = dynamic_cast<const codec_video_param &>(d);
out << c;
out << "Decoder:" << std::endl;
out << detail::space(detail::INTENT, out, "DecodedOrder = ")
<< detail::Boolean2String(d.param_.mfx.DecodedOrder) << std::endl;
out << detail::space(detail::INTENT, out, "ExtendedPicStruct = ")
<< detail::PicStruct2String(d.param_.mfx.ExtendedPicStruct) << std::endl;
out << detail::space(detail::INTENT, out, "TimeStampCalc = ")
<< detail::TimeStampCalc2String(d.param_.mfx.TimeStampCalc) << std::endl;
out << detail::space(detail::INTENT, out, "SliceGroupsPresent = ")
<< detail::Boolean2String(d.param_.mfx.SliceGroupsPresent) << std::endl;
out << detail::space(detail::INTENT, out, "MaxDecFrameBuffering = ")
<< detail::NotSpecifyed0(d.param_.mfx.MaxDecFrameBuffering) << std::endl;
out << detail::space(detail::INTENT, out, "EnableReallocRequest = ")
<< detail::TriState2String(d.param_.mfx.EnableReallocRequest) << std::endl;
return out;
}
/// @brief Holds JPEG decoder specific params.
class jpeg_decoder_video_param : public codec_video_param {
public:
/// @brief Constructs params and initialize them with default values.
jpeg_decoder_video_param() : codec_video_param() {}
DECLARE_INNER_MEMBER_ACCESS(jpeg_decoder_video_param, uint16_t, mfx, JPEGChromaFormat);
DECLARE_INNER_MEMBER_ACCESS(jpeg_decoder_video_param, uint16_t, mfx, Rotation);
DECLARE_INNER_MEMBER_ACCESS(jpeg_decoder_video_param, uint32_t, mfx, JPEGColorFormat);
DECLARE_INNER_MEMBER_ACCESS(jpeg_decoder_video_param, uint16_t, mfx, InterleavedDec);
DECLARE_INNER_MEMBER_ARRAY_ACCESS(jpeg_decoder_video_param, uint8_t, 4, mfx, SamplingFactorH);
DECLARE_INNER_MEMBER_ARRAY_ACCESS(jpeg_decoder_video_param, uint8_t, 4, mfx, SamplingFactorV);
};
/// @brief Holds JPEG encoder specific params.
class jpeg_encoder_video_param : public codec_video_param {
public:
/// @brief Constructs params and initialize them with default values.
jpeg_encoder_video_param() : codec_video_param() {}
DECLARE_INNER_MEMBER_ACCESS(jpeg_encoder_video_param, uint16_t, mfx, Interleaved);
DECLARE_INNER_MEMBER_ACCESS(jpeg_encoder_video_param, uint16_t, mfx, Quality);
DECLARE_INNER_MEMBER_ACCESS(jpeg_encoder_video_param, uint32_t, mfx, RestartInterval);
};
/// @brief Holds VPP specific params.
class vpp_video_param : public video_param {
public:
/// @brief Constructs params and initialize them with default values.
vpp_video_param() : video_param() {}
public:
/// @brief Returns frame_info in value.
/// @return frame info in value.
frame_info get_in_frame_info() const {
return frame_info(param_.vpp.In);
}
/// @brief Sets name value.
/// @param[in] name Value.
/// @return Reference to this object
vpp_video_param &set_in_frame_info(frame_info name) {
param_.vpp.In = name();
return *this;
}
/// @brief Returns frame_info out value.
/// @return frame info out value.
frame_info get_out_frame_info() const {
return frame_info(param_.vpp.Out);
}
/// @brief Sets name value.
/// @param[in] name Value.
/// @return Reference to this object
vpp_video_param &set_out_frame_info(frame_info name) {
param_.vpp.Out = name();
return *this;
}
/// @brief Friend operator to print out state of the class in human readable form.
/// @param[inout] out Reference to the stream to write.
/// @param[in] v Reference to the vpp_video_param instance to dump the state.
/// @return Reference to the stream.
friend std::ostream &operator<<(std::ostream &out, const vpp_video_param &v);
};
inline std::ostream &operator<<(std::ostream &out, const vpp_video_param &vpp) {
const video_param &v = dynamic_cast<const video_param &>(vpp);
out << v;
out << "Input FrameInfo:" << std::endl;
out << frame_info(vpp.param_.vpp.In) << std::endl;
out << "Output FrameInfo:" << std::endl;
out << frame_info(vpp.param_.vpp.Out) << std::endl;
return out;
}
} // namespace vpl
} // namespace oneapi
| 32,319 | 10,631 |
#include <bits/stdc++.h>
using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int g[20][20];
// once you feel prob is high, random.
void solve() {
int n,m;
cin >> n >> m;
const int TRY = 100*(n+m);
const int JUMP = 25;
for (int _ = 0; _ < TRY; _++) {
vector<int> a(n*m);
iota(a.begin(), a.end(), 0);
vector<pair<int, int>> res;
auto take = [&](int step, int i){
int x = a[i];
g[x/m][x%m] = step;
res.emplace_back(x/m, x%m);
swap(a[i], a[a.size()-1]); a.pop_back();
return x;
};
int k = rng() % a.size();
int now = take(0, k);
for (int s = 1; s < n*m; s++) {
for (int _ = 0; _ < JUMP; _++) {
int k = rng() % a.size();
int nxt = a[k];
if (now%m == nxt%m) continue;
if (now/m == nxt/m) continue;
if (now%m + now/m == nxt%m + nxt/m) continue;
if (now%m - now/m == nxt%m - nxt/m) continue;
now = take(s, k);
goto next_step;
}
goto one_fail;
next_step:;
}
// success
cout << "POSSIBLE\n";
for (auto& _: res) {
cout << _.first+1 << ' ' << _.second+1 << '\n';
}
//for (int i = 0; i < n; i++) {
// for (int j = 0; j < m; j++) {
// cout << g[i][j]+1 << ' ';
// }cout << '\n';
//}
return;
one_fail:;
}
cout << "IMPOSSIBLE\n";
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int T; cin >> T;
for (int t = 1; t <= T; t++) {
cout << "Case #" << t << ": ";
solve();
//cout << "\n";
}
fflush(stdout);
}
| 1,827 | 707 |
/**
\file mpi_mesh_grdecl.cpp
\brief This file implement class for decompose main mesh among processes
\author Iskhakov Ruslan
\date 2008-10-14*/
#include "mpi_mesh_grdecl.h"
#ifdef _MPI_MY
namespace blue_sky
{
//! default constructor
mpi_mesh_grdecl::mpi_mesh_grdecl(bs_type_ctor_param)
{
}
mpi_mesh_grdecl::mpi_mesh_grdecl(const mpi_mesh_grdecl& src)
{
*this = src;
}
int mpi_mesh_grdecl::par_distribution()
{
return 0;
}
int mpi_mesh_grdecl::print_debug_info()
{
printf("numprocs=%d,myid = %d\n",numprocs,myid);
fflush(0);
printf("lx=%d, ly=%d, lz=%d\n",lx,ly,lz);
fflush(0);
printf("start_x=%d, start_y=%d, start_z=%d\n",i_start,j_start,k_start);
fflush(0);
printf("end_x=%d, end_y=%d, end_z=%d\n",i_end,j_end,k_end);
fflush(0);
return 0;
}
int mpi_mesh_grdecl::par_fileOpen_cube_hdf5(const char* file_name)
{
hid_t file_id, dset_id = 0; //file and dataset identifiers
int cut_dir, n_layers;
hid_t filespace = 0, memspace=0; //file and memory dataspace identifiers
hsize_t dims_memory; // dataset dimensions
//hyperslab selection parameters
hsize_t stride[1];
hsize_t block[1];
hsize_t count[1];
hsize_t start[1] = {0};
//bounds for hyperslab selection
i_start=0, j_start=0, k_start=0, i_end=0, j_end=0, k_end=0;
file_id = open_file_mpi_hdf5(file_name); // open file
if (file_id < 0 )
return -1;
//! read initial_data
int initial_data[3];
dims_memory = 3;
count[0] = 3;
stride[0] = 1;
block[0] = 1;
mpi_hdf5_read_dataset ("/grid/initial_data", file_id, dims_memory, stride, block, count, TYPE_INT, initial_data, 0,
nx, ny, i_start, j_start, k_start, i_end, j_end, k_end, 1);
nx = initial_data[0];
ny = initial_data[1];
nz = initial_data[2];
if (!myid)
printf("nx %d, ny %d, nz %d\n", nx, ny, nz);
//! make 1D-decomposition
if (nx <= ny)
cut_dir = CUT_DIR_X;
else
cut_dir = CUT_DIR_Y;
//cut_dir = CUT_DIR_Z;
if (!myid)
printf("cut_dir %d\n", cut_dir);
// at first, init as full
i_start = 0;
j_start = 0;
k_start = 0;
i_end = nx - 1;
j_end = ny - 1;
k_end = nz - 1;
if (cut_dir == CUT_DIR_X)
{
i_start = (int) (myid) * ((double) nx / numprocs);
i_end = (int) (myid + 1) * ((double) nx / numprocs) - 1;
n_layers = nx;
}
else if (cut_dir == CUT_DIR_Y)
{
j_start = (int) myid * ((double) ny / numprocs);
j_end = (int) (myid + 1) * ((double) ny / numprocs) - 1;
n_layers = ny;
}
else if (cut_dir == CUT_DIR_Z)
{
k_start = (int) myid * ((double) nz / numprocs);
k_end = (int) (myid + 1) * ((double) nz / numprocs) - 1;
n_layers = nz;
}
if (n_layers < numprocs)
{
printf("Error: n_procs %d > nx %d!\n", numprocs, nx);
return -1;
}
printf ("BOUND_INDEXES : [%d, %d] , [%d, %d] , [%d, %d]\n", i_start, i_end, j_start, j_end, k_start, k_end);
if ((i_end < i_start) || (j_end < j_start) || (k_end < k_start))
{
printf("Wrong decomp!\n");
return -1;
}
/*
//! make 1D-decomposition
if (nx <= ny)
cut_dir = CUT_DIR_X;
else
cut_dir = CUT_DIR_Y;
if (!myid)
{printf("cut_dir %d\n", cut_dir); fflush(0);}
// at first, init as full
i_start = 0;
j_start = 0;
k_start = 0;
i_end = nx - 1;
j_end = ny - 1;
k_end = nz - 1;
if (cut_dir == CUT_DIR_X)
{
i_start = (int) myid * ((double) nx / numprocs);
i_end = (int) (myid + 1) * ((double) nx / numprocs) - 1;
n_layers = nx;
}
else if (cut_dir == CUT_DIR_Y)
{
j_start = (int) myid * ((double) ny / numprocs);
j_end = (int) (myid + 1) * ((double) ny / numprocs) - 1;
n_layers = ny;
}
//
else if (cut_dir == CUT_DIR_Z)
{
k_start = (int) mpi_rank * ((double) nz / mpi_size);
k_end = (int) (mpi_rank + 1) * ((double) nz / mpi_size) - 1;
n_layers = nz;
}
if (n_layers < numprocs)
{
printf("Error: n_procs %d > nx %d!\n", numprocs, nx);
return -1;
}
printf ("BOUND_INDEXES : [%d, %d] , [%d, %d] , [%d, %d]\n", i_start, i_end, j_start, j_end, k_start, k_end);
//share between process by equal part of active cells (begin)
#ifdef _WIN32
mesh_grdecl::fileOpen_cube_hdf5(file_name,i_start, j_start, k_start, i_end, j_end,k_end);
//#elif UNIX //hdf5-parallel only in UNIX-like system
//put misha direction he
#endif
printf("mesh_zcorn_number = %d\n",zcorn_array.size());
return true;
*/
return 0;
}
void mpi_mesh_grdecl::set_mpi_comm(MPI_Comm acomm)
{
mpi_comm = acomm;
MPI_Comm_size(mpi_comm, &numprocs);
MPI_Comm_rank(mpi_comm, &myid);
}
int mpi_mesh_grdecl::open_file_mpi_hdf5(const char *file_name)
{
//Set up file access property list with parallel I/O access
hid_t plist_id = H5Pcreate(H5P_FILE_ACCESS); // Creates a new property as an instance of a property li_startt class.
//Each process of the MPI communicator creates an access template and sets i_end up wi_endh MPI parallel access information. Thi_start i_start2 done wi_endh the H5Pcreate call to obtain the file access property li_startt and the H5Pset_fapl_mpio call to set up parallel I/O access.
H5Pset_fapl_mpio(plist_id, mpi_comm, mpi_info);
// Open a new file and release property list identifier
hid_t file_id = H5Fopen (file_name, H5F_ACC_RDONLY, H5P_DEFAULT); // H5F_ACC_RDONLY - Allow read-only access to file.
if (file_id < 0)
{
printf("Error: Can't open file %s!\n", file_name);
return -1;
}
H5Pclose (plist_id);
return file_id;
}
int mpi_mesh_grdecl::mpi_hdf5_read_dataset (const char* dset_title, hid_t file_id, hsize_t dims_memory,
hsize_t *stride,
hsize_t *block,
hsize_t *count,
const int datatype, int *data_int, float *data_float,
const int nx, const int ny,
const int i_start2, const int j_start, const int k_start,
const int i_end, const int j_end, const int k_end, int mode)
{
herr_t status;
int rank = 1; // read 1-dimensional array
hid_t filespace, memspace; // file and memory dataspace identifiers
int k;
float *data_float_ptr = data_float;
int *data_int_ptr = data_int;
hid_t dset_id;
hsize_t start[1];
if (datatype != TYPE_FLOAT && datatype != TYPE_INT)
{
printf("Error: wrong type!\n");
return -1;
}
dset_id = open_dataset(rank, &dims_memory, file_id, dset_title);
if (dset_id < 0)
return -1; //cant' open dataset!
filespace = H5Dget_space(dset_id);
memspace = H5Screate_simple(rank, &dims_memory, NULL);
hid_t plist_id = H5Pcreate(H5P_DATASET_XFER);
H5Pset_dxpl_mpio(plist_id, H5FD_MPIO_INDEPENDENT);
if (mode) // for 1 pass read
{
if (mode == 1)// initial_data
start[0] = 0;
else if (mode == 2)// coord
start[0] = (i_start + j_start * (nx + 1)) * 6;
H5Sselect_hyperslab(filespace, H5S_SELECT_SET, start, stride, count, block);
if (datatype == TYPE_FLOAT)
status = H5Dread(dset_id, H5T_NATIVE_FLOAT, memspace, filespace, plist_id, data_float);
else if (datatype == TYPE_INT)
status = H5Dread(dset_id, H5T_NATIVE_INT, memspace, filespace, plist_id, data_int);
}
else // multi pass read
{
for (k = 0; k < k_end - k_start + 1; k++)
{
start[0] = i_start + j_start * nx + (k + k_start) * nx * ny;
H5Sselect_hyperslab(filespace, H5S_SELECT_SET, start, stride, count, block);
if (datatype == TYPE_FLOAT)
status = H5Dread(dset_id, H5T_NATIVE_FLOAT, memspace, filespace, plist_id, data_float_ptr);
else if (datatype == TYPE_INT)
status = H5Dread(dset_id, H5T_NATIVE_INT, memspace, filespace, plist_id, data_int_ptr);
if (status < 0)
{
printf("Error: Dataset read error!\n");
return -1;
}
data_int_ptr = data_int_ptr + dims_memory;
data_float_ptr = data_float_ptr + dims_memory;
}
}
//release resources
H5Dclose(dset_id);
H5Sclose(filespace);
H5Sclose(memspace);
H5Pclose(plist_id);
return 0;
}
int mpi_mesh_grdecl::open_dataset(int rank, hsize_t dims_memory[], hid_t file_id, const char* dset_title)
{
hid_t filespace = H5Screate_simple(rank, dims_memory, NULL);
//Open the dataset and close filespace
hid_t dset_id = H5Dopen(file_id, dset_title);
if (dset_id < 0)// check if file has been opened
{
printf("Error: Can't open dataset %s!\n", dset_title);
return -1;
}
H5Sclose(filespace);
return dset_id;
}
BLUE_SKY_TYPE_IMPL_T_EXT(1 , (mpi_mesh_grdecl<base_strategy_fif>) , 1, (objbase), "mpi_mesh_grdecl<float, int,float>", "MPI mesh_grdecl class", "MPI mesh ecllipse class", false);
BLUE_SKY_TYPE_IMPL_T_EXT(1 , (mpi_mesh_grdecl<base_strategy_did>) , 1, (objbase), "mpi_mesh_grdecl<double, int,double>", "MPI mesh ecllipse class", "MPI mesh ecllipse class", false);
BLUE_SKY_TYPE_STD_CREATE_T_DEF(mpi_mesh_grdecl, (class));
BLUE_SKY_TYPE_STD_COPY_T_DEF(mpi_mesh_grdecl, (class));
}; //namespace blue_sky
#endif //_MPI_MY
| 9,678 | 3,992 |
#pragma once
#include "i-game-state.hpp"
class Game; // Forward declaration
class CinematicState : public IGameState {
public:
CinematicState(Game& game);
virtual ~CinematicState();
void enter() override;
void update(float deltatime) override;
void exit() override;
};
| 278 | 91 |
#include "ShadingOperation.h"
extern "C" {
#include <math.h>
}
#include "Graphics.h"
#include "Textures.h"
#include "Light.h"
#include "FrameBuffer.h"
namespace GraphicsEngine
{
void ShadingOperation::Initialize()
{
auto shadowCamera = Engine::Create<Camera>();
auto shadowScene = Engine::Create<Scene>();
shadowCamera->SetParent(This.lock());
shadowScene->SetParent(This.lock());
ShadowCamera = shadowCamera;
ShadowScene = shadowScene;
shadowScene->CurrentCamera = ShadowCamera;
int width = 2048;
int height = 2048;
auto rightMap = FrameBuffer::Create(width, height, Textures::Create(width, height, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_FLOAT, GL_R32F, GL_RED));
auto leftMap = FrameBuffer::Create(width, height, Textures::Create(width, height, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_FLOAT, GL_R32F, GL_RED));
auto topMap = FrameBuffer::Create(width, height, Textures::Create(width, height, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_FLOAT, GL_R32F, GL_RED));
auto bottomMap = FrameBuffer::Create(width, height, Textures::Create(width, height, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_FLOAT, GL_R32F, GL_RED));
auto frontMap = FrameBuffer::Create(width, height, Textures::Create(width, height, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_FLOAT, GL_R32F, GL_RED));
auto backMap = FrameBuffer::Create(width, height, Textures::Create(width, height, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_FLOAT, GL_R32F, GL_RED));
auto parent = This.lock();
rightMap->SetParent(parent);
leftMap->SetParent(parent);
topMap->SetParent(parent);
bottomMap->SetParent(parent);
frontMap->SetParent(parent);
backMap->SetParent(parent);
RightMap = rightMap;
LeftMap = leftMap;
TopMap = topMap;
BottomMap = bottomMap;
FrontMap = frontMap;
BackMap = backMap;
}
void ShadingOperation::Update(float)
{
if (CurrentScene.expired())
return;
CurrentScene.lock()->RefreshWatches();
}
void ShadingOperation::Render()
{
if (CurrentCamera.expired() || CurrentScene.expired())
return;
glEnable(GL_BLEND); CheckGLErrors();
glEnable(GL_DEPTH_TEST); CheckGLErrors();
glDepthMask(GL_FALSE); CheckGLErrors();
glBlendFunc(GL_SRC_ALPHA, GL_ONE); CheckGLErrors();
Programs::PhongOutput->Use();
Programs::PhongOutput->SetInputBuffer(SceneBuffer.lock());
Programs::PhongOutput->resolution.Set(Resolution);
Programs::PhongOutput->shadowsEnabled.Set(false);
Programs::PhongOutput->shadowLeft.Set(LeftMap.lock()->GetTexture(), 8);
Programs::PhongOutput->shadowRight.Set(RightMap.lock()->GetTexture(), 9);
Programs::PhongOutput->shadowFront.Set(FrontMap.lock()->GetTexture(), 10);
Programs::PhongOutput->shadowBack.Set(BackMap.lock()->GetTexture(), 11);
Programs::PhongOutput->shadowTop.Set(TopMap.lock()->GetTexture(), 12);
Programs::PhongOutput->shadowBottom.Set(BottomMap.lock()->GetTexture(), 13);
auto currentCamera = CurrentCamera.lock();
if (GlobalLight.expired())
{
Programs::PhongOutput->lightBrightness.Set(1);
Programs::PhongOutput->attenuation.Set(1, 0, 0);
Programs::PhongOutput->lightPosition.Set(0, 0, 0);
Programs::PhongOutput->lightDirection.Set(-currentCamera->GetTransformationInverse().UpVector());
Programs::PhongOutput->lightDiffuse.Set(0.5f, 0.5f, 0.5f);
Programs::PhongOutput->lightSpecular.Set(1, 1, 1);
Programs::PhongOutput->lightAmbient.Set(0.5f, 0.5f, 0.5f);
Programs::PhongOutput->spotlightAngles.Set(0, 0);
Programs::PhongOutput->spotlightFalloff.Set(0);
Programs::PhongOutput->lightType.Set(0);
}
else
{
auto globalLight = GlobalLight.lock();
Programs::PhongOutput->lightBrightness.Set(globalLight->Brightness);
Programs::PhongOutput->attenuation.Set(globalLight->Attenuation);
Programs::PhongOutput->lightPosition.Set(globalLight->Position);
Programs::PhongOutput->lightDirection.Set(currentCamera->GetTransformationInverse() * -globalLight->Direction);
Programs::PhongOutput->lightDiffuse.Set(globalLight->Diffuse);
Programs::PhongOutput->lightSpecular.Set(globalLight->Specular);
Programs::PhongOutput->lightAmbient.Set(globalLight->Ambient);
Programs::PhongOutput->spotlightAngles.Set(globalLight->InnerRadius, globalLight->OuterRadius);
Programs::PhongOutput->spotlightFalloff.Set(globalLight->SpotlightFalloff);
Programs::PhongOutput->lightType.Set(globalLight->Type);
}
Programs::PhongOutput->transform.Set(Matrix3().Scale(1, 1, 1));
Programs::PhongOutput->CoreMeshes.Square->Draw();
glEnable(GL_STENCIL_TEST); CheckGLErrors();
glDepthFunc(GL_GEQUAL); CheckGLErrors();
auto currentScene = CurrentScene.lock();
for (int i = 0; i < currentScene->GetLights(); ++i)
{
std::shared_ptr<Light> light = currentScene->GetLight(i);
if (!light->Enabled || light->AreShadowsEnabled())
continue;
if (currentCamera->GetFrustum().Intersects(light->GetBoundingBox()) == Enum::IntersectionType::Outside)
continue;
Draw(light);
}
glBlendFunc(GL_SRC_ALPHA, GL_ONE); CheckGLErrors();
for (int i = 0; i < currentScene->GetLights(); ++i)
{
std::shared_ptr<Light> light = currentScene->GetLight(i);
if (!light->Enabled || !light->AreShadowsEnabled())
continue;
if (currentCamera->GetFrustum().Intersects(light->GetBoundingBox()) == Enum::IntersectionType::Outside)
continue;
glDisable(GL_BLEND); CheckGLErrors();
glDepthMask(GL_TRUE); CheckGLErrors();
glDisable(GL_STENCIL_TEST); CheckGLErrors();
glEnable(GL_DEPTH_TEST); CheckGLErrors();
glDepthFunc(GL_LEQUAL); CheckGLErrors();
glCullFace(GL_FRONT); CheckGLErrors();
Programs::DepthTrace->Use();
DrawShadows(light, i);
glCullFace(GL_BACK); CheckGLErrors();
glEnable(GL_BLEND); CheckGLErrors();
glEnable(GL_DEPTH_TEST); CheckGLErrors();
glDepthMask(GL_FALSE); CheckGLErrors();
glEnable(GL_STENCIL_TEST); CheckGLErrors();
glDepthFunc(GL_GEQUAL); CheckGLErrors();
Programs::PhongOutput->Use();
LightBuffer.lock()->DrawTo();
Draw(light);
}
glDepthMask(GL_TRUE); CheckGLErrors();
glDisable(GL_STENCIL_TEST); CheckGLErrors();
//glEnable(GL_DEPTH_TEST); CheckGLErrors();
glDepthFunc(GL_LEQUAL); CheckGLErrors();
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); CheckGLErrors();
}
void ShadingOperation::Draw(const std::shared_ptr<Light>& light)
{
auto currentCamera = CurrentCamera.lock();
Programs::PhongOutput->lightBrightness.Set(light->Brightness);
Programs::PhongOutput->cameraTransform.Set(light->GetShadowMapInverseTransformation() * currentCamera->GetTransformation());
Programs::PhongOutput->attenuation.Set(light->Attenuation);
Programs::PhongOutput->lightPosition.Set(currentCamera->GetTransformationInverse() * light->Position);
Programs::PhongOutput->lightDirection.Set(currentCamera->GetTransformationInverse() * -light->Direction);
Programs::PhongOutput->lightDiffuse.Set(light->Diffuse);
Programs::PhongOutput->lightSpecular.Set(light->Specular);
Programs::PhongOutput->lightAmbient.Set(light->Ambient);
Programs::PhongOutput->spotlightAngles.Set(cosf(light->InnerRadius), cosf(light->OuterRadius));
Programs::PhongOutput->spotlightFalloff.Set(light->SpotlightFalloff);
Programs::PhongOutput->lightType.Set(light->Type);
const Mesh* mesh = nullptr;
const Mesh* stencilMesh = nullptr;
float lightRadius = 0;
Matrix3 transform;
if (light->Type == Enum::LightType::Directional)
{
transform = Matrix3().Scale(1, 1, 1);
Programs::PhongOutput->shadowsEnabled.Set(false);
Programs::PhongOutput->transform.Set(transform);
mesh = Programs::PhongOutput->CoreMeshes.Square;
stencilMesh = Programs::PhongOutputStencil->CoreMeshes.Square;
}
else
{
Dimensions shadowMapSize = light->GetShadowMapSize();
Programs::PhongOutput->shadowsEnabled.Set(light->AreShadowsEnabled());
Programs::PhongOutput->shadowDebugView.Set(light->ShadowDebugView);
if (light->AreShadowsEnabled())
Programs::PhongOutput->shadowScale.Set(float(shadowMapSize.Width) / 2048, float(shadowMapSize.Height) / 2048);
lightRadius = light->GetRadius();
Programs::PhongOutput->maxRadius.Set(lightRadius);
lightRadius *= 1.1f;
if (light->Type == Enum::LightType::Spot && light->OuterRadius <= PI / 2 + 0.001f)
{
Matrix3 rotation;
float direction = 1;
if (light->Direction == Vector3(0, -1, 0))
rotation = Matrix3().RotatePitch(PI);//direction = -1;
else if (light->Direction != Vector3(0, 1, 0))
rotation = Matrix3().RotateYaw(atan2f(light->Direction.X, -light->Direction.Z)) * Matrix3().RotatePitch(-acosf(light->Direction.Y));
transform = currentCamera->GetProjection() * Matrix3().Translate(light->Position) * Matrix3().Scale(-lightRadius, lightRadius, lightRadius) * rotation;
Programs::PhongOutput->transform.Set(transform);
if (light->OuterRadius <= PI / 4 + 0.001f)
{
mesh = Programs::PhongOutput->CoreMeshes.Cone;
stencilMesh = Programs::PhongOutputStencil->CoreMeshes.Cone;
}
else
{
mesh = Programs::PhongOutput->CoreMeshes.HalfBoundingVolume;
stencilMesh = Programs::PhongOutputStencil->CoreMeshes.HalfBoundingVolume;
}
}
else
{
transform = currentCamera->GetProjectionMatrix() * Matrix3().Translate(
currentCamera->GetTransformationInverse() * light->Position
) * Matrix3().Scale(-lightRadius, lightRadius, lightRadius);
Programs::PhongOutput->transform.Set(transform);
mesh = Programs::PhongOutput->CoreMeshes.BoundingVolume;
stencilMesh = Programs::PhongOutputStencil->CoreMeshes.BoundingVolume;
}
}
glStencilMask(0xFF); CheckGLErrors();
glStencilFunc(GL_ALWAYS, 1, 0xFF); CheckGLErrors();
glStencilOp(GL_ZERO, GL_ZERO, GL_REPLACE); CheckGLErrors();
Programs::PhongOutputStencil->Use();
Programs::PhongOutputStencil->transform.Set(transform);
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); CheckGLErrors();
stencilMesh->Draw();
glStencilFunc(GL_EQUAL, 1, 0xFF); CheckGLErrors();
glStencilOp(GL_ZERO, GL_ZERO, GL_REPLACE); CheckGLErrors();
Programs::PhongOutputStencil->transform.Set(transform * Matrix3().Scale(-1, 1, 1));
glDepthFunc(GL_LEQUAL); CheckGLErrors();
stencilMesh->Draw();
Programs::PhongOutput->Use();
glStencilMask(0x00); CheckGLErrors();
glStencilFunc(GL_EQUAL, 1, 0xFF); CheckGLErrors();
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); CheckGLErrors();
glDepthFunc(GL_GEQUAL); CheckGLErrors();
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); CheckGLErrors();
mesh->Draw();
}
void ShadingOperation::DrawShadows(const std::shared_ptr<Light>& light, int index)
{
float lightRadius = light->GetRadius() * 1.1f;
Matrix3 backPanelTransform = Matrix3(0, 0, -lightRadius + 0.01f) * Matrix3().Scale(lightRadius, lightRadius, 0);
//Matrix3 base = Matrix3().ExtractRotation(CurrentCamera->GetTransformation(), light->Position);
Dimensions bufferSize = light->GetShadowMapSize();
const AabbTree& watch = CurrentScene.lock()->GetWatched(index);
auto shadowCamera = ShadowCamera.lock();
shadowCamera->SetProperties(0.5f * PI, 1, 1e-1f, lightRadius);
if (light->Type != Enum::LightType::Spot || light->OuterRadius > PI / 4 + 0.001f)
{
RightMap.lock()->DrawTo(0, 0, bufferSize.Width, bufferSize.Height);
Graphics::ClearScreen(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
shadowCamera->SetTransformation(light->GetShadowMapTransformation() * Matrix3(Vector3(), Vector3(0, 0, 1), Vector3(0, 1, 0), Vector3(-1, 0, 0)));
Scene::Draw(watch, false, shadowCamera);
Programs::DepthTrace->transform.Set(shadowCamera->GetProjectionMatrix() * backPanelTransform);
Programs::DepthTrace->objectTransform.Set(shadowCamera->GetTransformation() * backPanelTransform);
Programs::DepthTrace->CoreMeshes.Cube->Draw();
}
if (light->Type != Enum::LightType::Spot || light->OuterRadius > PI / 4 + 0.001f)
{
LeftMap.lock()->DrawTo(0, 0, bufferSize.Width, bufferSize.Height);
Graphics::ClearScreen(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
shadowCamera->SetTransformation(light->GetShadowMapTransformation() * Matrix3(Vector3(), Vector3(0, 0, -1), Vector3(0, 1, 0), Vector3(1, 0, 0)));
Scene::Draw(watch, false, shadowCamera);
Programs::DepthTrace->transform.Set(shadowCamera->GetProjectionMatrix() * backPanelTransform);
Programs::DepthTrace->objectTransform.Set(shadowCamera->GetTransformation() * backPanelTransform);
Programs::DepthTrace->CoreMeshes.Cube->Draw();
}
if (light->Type != Enum::LightType::Spot || light->OuterRadius > PI / 4 + 0.001f)
{
FrontMap.lock()->DrawTo(0, 0, bufferSize.Width, bufferSize.Height);
Graphics::ClearScreen(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
shadowCamera->SetTransformation(light->GetShadowMapTransformation() * Matrix3(Vector3(), Vector3(1, 0, 0), Vector3(0, 1, 0), Vector3(0, 0, 1)));
Scene::Draw(watch, false, shadowCamera);
Programs::DepthTrace->transform.Set(shadowCamera->GetProjectionMatrix() * backPanelTransform);
Programs::DepthTrace->objectTransform.Set(shadowCamera->GetTransformation() * backPanelTransform);
Programs::DepthTrace->CoreMeshes.Cube->Draw();
}
if (light->Type != Enum::LightType::Spot || light->OuterRadius > PI / 4 + 0.001f)
{
BackMap.lock()->DrawTo(0, 0, bufferSize.Width, bufferSize.Height);
Graphics::ClearScreen(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
shadowCamera->SetTransformation(light->GetShadowMapTransformation() * Matrix3(Vector3(), Vector3(-1, 0, 0), Vector3(0, 1, 0), Vector3(0, 0, -1)));
Scene::Draw(watch, false, shadowCamera);
Programs::DepthTrace->transform.Set(shadowCamera->GetProjectionMatrix() * backPanelTransform);
Programs::DepthTrace->objectTransform.Set(shadowCamera->GetTransformation() * backPanelTransform);
Programs::DepthTrace->CoreMeshes.Cube->Draw();
}
//if (light->Type != Enum::LightType::Spot || light->OuterRadius <= PI / 4 + 0.001f)
{
TopMap.lock()->DrawTo(0, 0, bufferSize.Width, bufferSize.Height);
Graphics::ClearScreen(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
shadowCamera->SetTransformation(light->GetShadowMapTransformation() * Matrix3(Vector3(), Vector3(1, 0, 0), Vector3(0, 0, 1), Vector3(0, -1, 0)));
Scene::Draw(watch, false, shadowCamera);
Programs::DepthTrace->transform.Set(shadowCamera->GetProjectionMatrix() * backPanelTransform);
Programs::DepthTrace->objectTransform.Set(shadowCamera->GetTransformation() * backPanelTransform);
Programs::DepthTrace->CoreMeshes.Cube->Draw();
}
if (light->Type != Enum::LightType::Spot || light->OuterRadius > 3 * PI / 4 + 0.001f)
{
BottomMap.lock()->DrawTo(0, 0, bufferSize.Width, bufferSize.Height);
Graphics::ClearScreen(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
shadowCamera->SetTransformation(light->GetShadowMapTransformation() * Matrix3(Vector3(), Vector3(1, 0, 0), Vector3(0, 0, -1), Vector3(0, 1, 0)));
Scene::Draw(watch, false, shadowCamera);
Programs::DepthTrace->transform.Set(shadowCamera->GetProjectionMatrix() * backPanelTransform);
Programs::DepthTrace->objectTransform.Set(shadowCamera->GetTransformation() * backPanelTransform);
Programs::DepthTrace->CoreMeshes.Cube->Draw();
}
}
}
| 15,127 | 5,948 |