<commit_before>/**
@file unix/filesystem.cpp
@author Tim Howard

@section LICENSE
Copyright (c) 2010-2011 Tim Howard

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include <stdio.h>
#include <fcntl.h>
#include <duct/debug.hpp>
#include <duct/filesystem.hpp>

namespace duct {

// class DirStream implementation

DirStream::DirStream(const char* path) {
	_path.append(path);
	init();
}

DirStream::DirStream(const std::string& path) {
	_path.append(path);
	init();
}

DirStream::DirStream(const UnicodeString& path) {
	path.toUTF8String(_path);
	init();
}

DirStream::~DirStream() {
	if (_inst) {
		closedir(_inst);
		_inst=NULL;
		_entry=NULL;
	}
}

bool DirStream::nextEntry() {
	_entry=(void*)readdir(_inst);
	return _entry!=NULL;
}

bool DirStream::nextEntry(UnicodeString& result) {
	_entry=(void*)readdir(_inst);
	if (_entry) {
		result.setTo(UnicodeString(((struct dirent*)_entry)->d_name));
		return true;
	}
	return false;
}

bool DirStream::entryName(UnicodeString& result) const {
	if (_entry) {
		result.setTo(UnicodeString(((struct dirent*)_entry)->d_name));
		return true;
	}
	return false;
}

PathType DirStream::entryType() const {
	if (_entry) {
		std::string temp(_path);
		temp.append(((struct dirent*)_entry)->d_name);
		return FileSystem::pathType(temp);
	} else {
		return PATHTYPE_NONE;
	}
}

bool DirStream::isOpen() const {
	return _inst!=NULL;
}

bool DirStream::close() {
	if (_inst) {
		closedir(_inst);
		_inst=NULL;
		return true;
	}
	return false;
}

void DirStream::init() {
	char c=_path[_path.length()-1];
	if (c=='\\') {
		_path.replace(_path.length()-1, 1, 1, '/');
	} else if (c!='/') {
		_path.append("/");
	}
	_inst=(void*)opendir(_path.c_str());
}

// FileSystem implementation

namespace FileSystem {

bool statPath(const char* path, struct stat* s) {
	return stat(path, s)==0;
}

bool statPath(const std::string& path, struct stat* s) {
	return stat(path.c_str(), s)==0;
}

bool statPath(const UnicodeString& path, struct stat* s) {
	std::string str;
	path.toUTF8String(str);
	return stat(str.c_str(), s)==0;
}

PathType pathType(const char* path) {
	struct stat s;
	if (statPath(path, &s)) {
		return S_ISREG(s.st_mode) ? PATHTYPE_FILE : (S_ISDIR(s.st_mode) ? PATHTYPE_DIR : PATHTYPE_NONE);
	} else {
		return PATHTYPE_NONE;
	}
}

PathType pathType(const std::string& path) {
	struct stat s;
	if (statPath(path, &s)) {
		return S_ISREG(s.st_mode) ? PATHTYPE_FILE : (S_ISDIR(s.st_mode) ? PATHTYPE_DIR : PATHTYPE_NONE);
	} else {
		return PATHTYPE_NONE;
	}
}

PathType pathType(const UnicodeString& path) {
	struct stat s;
	if (statPath(path, &s)) {
		return S_ISREG(s.st_mode) ? PATHTYPE_FILE : (S_ISDIR(s.st_mode) ? PATHTYPE_DIR : PATHTYPE_NONE);
	} else {
		return PATHTYPE_NONE;
	}
}

bool dirExists(const char* path) {
	struct stat s;
	if (statPath(path, &s)) {
		return S_ISDIR(s.st_mode);
	} else {
		return false;
	}
}

bool dirExists(const std::string& path) {
	struct stat s;
	if (statPath(path, &s)) {
		return S_ISDIR(s.st_mode);
	} else {
		return false;
	}
}

bool dirExists(const UnicodeString& path) {
	struct stat s;
	if (statPath(path, &s)) {
		return S_ISDIR(s.st_mode);
	} else {
		return false;
	}
}

bool fileExists(const char* path) {
	struct stat s;
	if (statPath(path, &s)) {
		return S_ISREG(s.st_mode);
	} else {
		return false;
	}
}

bool fileExists(const std::string& path) {
	struct stat s;
	if (statPath(path, &s)) {
		return S_ISREG(s.st_mode);
	} else {
		return false;
	}
}

bool fileExists(const UnicodeString& path) {
	struct stat s;
	if (statPath(path, &s)) {
		return S_ISREG(s.st_mode);
	} else {
		return false;
	}
}

// TODO structure creation
bool createDir(const char* path, bool structure) {
	return mkdir(path, S_IRWXU|S_IRWXG|S_IROTH|S_IXOTH)==0;
}

bool createDir(const std::string& path, bool structure) {
	return createDir(path.c_str(), false);
}

bool createDir(const UnicodeString& path, bool structure) {
	std::string str;
	path.toUTF8String(str);
	return createDir(str.c_str(), false);
}

bool createFile(const char* path, bool createpath) {
	// TODO: dir/path extraction from file path
	/*if (createpath && !dirExists()) {
		createDir();
	}*/
	int fd=creat(path, 0);
	if (fd!=-1) {
		close(fd);
		return true;
	}
	return false;
}

bool createFile(const std::string& path, bool createpath) {
	return createFile(path.c_str(), createpath);
}

bool createFile(const UnicodeString& path, bool createpath) {
	std::string str;
	path.toUTF8String(str);
	return createFile(str.c_str(), createpath);
}

bool deleteFile(const char* path) {
	return remove(path)==0;
}

bool deleteFile(const std::string& path) {
	return remove(path.c_str())==0;
}

bool deleteFile(const UnicodeString& path) {
	std::string str;
	path.toUTF8String(str);
	return remove(str.c_str())==0;
}

bool deleteDir(const char* path) {
	return rmdir(path)==0;
}

bool deleteDir(const std::string& path) {
	return rmdir(path.c_str())==0;
}

bool deleteDir(const UnicodeString& path) {
	std::string str;
	path.toUTF8String(str);
	return rmdir(str.c_str())==0;
}

} // namespace FileSystem

} // namespace duct

<commit_msg>Fixed FileSystem for Linux (mid-dev, borked it while testing Windows).<commit_after>/**
@file unix/filesystem.cpp
@author Tim Howard

@section LICENSE
Copyright (c) 2010-2011 Tim Howard

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include <stdio.h>
#include <fcntl.h>
#include <duct/debug.hpp>
#include <duct/filesystem.hpp>

namespace duct {

// class DirStream implementation

DirStream::DirStream(const char* path) {
	_path.append(path);
	init();
}

DirStream::DirStream(const std::string& path) {
	_path.append(path);
	init();
}

DirStream::DirStream(const UnicodeString& path) {
	path.toUTF8String(_path);
	init();
}

DirStream::~DirStream() {
	if (_dir) {
		closedir(_dir);
		_dir=NULL;
		_entry=NULL;
	}
}

bool DirStream::nextEntry() {
	_entry=readdir(_dir);
	return _entry!=NULL;
}

bool DirStream::nextEntry(UnicodeString& result) {
	_entry=readdir(_dir);
	if (_entry) {
		result.setTo(UnicodeString(_entry->d_name));
		return true;
	}
	return false;
}

bool DirStream::entryName(UnicodeString& result) const {
	if (_entry) {
		result.setTo(UnicodeString(_entry->d_name));
		return true;
	}
	return false;
}

PathType DirStream::entryType() const {
	if (_entry) {
		std::string temp(_path);
		temp.append(_entry->d_name);
		return FileSystem::pathType(temp);
	} else {
		return PATHTYPE_NONE;
	}
}

bool DirStream::isOpen() const {
	return _dir!=NULL;
}

bool DirStream::close() {
	if (_dir) {
		closedir(_dir);
		_dir=NULL;
		return true;
	}
	return false;
}

void DirStream::init() {
	char c=_path[_path.length()-1];
	if (c=='\\') {
		_path.replace(_path.length()-1, 1, 1, '/');
	} else if (c!='/') {
		_path.append("/");
	}
	_dir=opendir(_path.c_str());
}

// FileSystem implementation

namespace FileSystem {

bool statPath(const char* path, struct stat* s) {
	return stat(path, s)==0;
}

bool statPath(const std::string& path, struct stat* s) {
	return stat(path.c_str(), s)==0;
}

bool statPath(const UnicodeString& path, struct stat* s) {
	std::string str;
	path.toUTF8String(str);
	return stat(str.c_str(), s)==0;
}

PathType pathType(const char* path) {
	struct stat s;
	if (statPath(path, &s)) {
		return S_ISREG(s.st_mode) ? PATHTYPE_FILE : (S_ISDIR(s.st_mode) ? PATHTYPE_DIR : PATHTYPE_NONE);
	} else {
		return PATHTYPE_NONE;
	}
}

PathType pathType(const std::string& path) {
	struct stat s;
	if (statPath(path, &s)) {
		return S_ISREG(s.st_mode) ? PATHTYPE_FILE : (S_ISDIR(s.st_mode) ? PATHTYPE_DIR : PATHTYPE_NONE);
	} else {
		return PATHTYPE_NONE;
	}
}

PathType pathType(const UnicodeString& path) {
	struct stat s;
	if (statPath(path, &s)) {
		return S_ISREG(s.st_mode) ? PATHTYPE_FILE : (S_ISDIR(s.st_mode) ? PATHTYPE_DIR : PATHTYPE_NONE);
	} else {
		return PATHTYPE_NONE;
	}
}

bool dirExists(const char* path) {
	struct stat s;
	if (statPath(path, &s)) {
		return S_ISDIR(s.st_mode);
	} else {
		return false;
	}
}

bool dirExists(const std::string& path) {
	struct stat s;
	if (statPath(path, &s)) {
		return S_ISDIR(s.st_mode);
	} else {
		return false;
	}
}

bool dirExists(const UnicodeString& path) {
	struct stat s;
	if (statPath(path, &s)) {
		return S_ISDIR(s.st_mode);
	} else {
		return false;
	}
}

bool fileExists(const char* path) {
	struct stat s;
	if (statPath(path, &s)) {
		return S_ISREG(s.st_mode);
	} else {
		return false;
	}
}

bool fileExists(const std::string& path) {
	struct stat s;
	if (statPath(path, &s)) {
		return S_ISREG(s.st_mode);
	} else {
		return false;
	}
}

bool fileExists(const UnicodeString& path) {
	struct stat s;
	if (statPath(path, &s)) {
		return S_ISREG(s.st_mode);
	} else {
		return false;
	}
}

// TODO structure creation
bool createDir(const char* path, bool structure) {
	return mkdir(path, S_IRWXU|S_IRWXG|S_IROTH|S_IXOTH)==0;
}

bool createDir(const std::string& path, bool structure) {
	return createDir(path.c_str(), false);
}

bool createDir(const UnicodeString& path, bool structure) {
	std::string str;
	path.toUTF8String(str);
	return createDir(str.c_str(), false);
}

bool createFile(const char* path, bool createpath) {
	// TODO: dir/path extraction from file path
	/*if (createpath && !dirExists()) {
		createDir();
	}*/
	int fd=creat(path, 0);
	if (fd!=-1) {
		close(fd);
		return true;
	}
	return false;
}

bool createFile(const std::string& path, bool createpath) {
	return createFile(path.c_str(), createpath);
}

bool createFile(const UnicodeString& path, bool createpath) {
	std::string str;
	path.toUTF8String(str);
	return createFile(str.c_str(), createpath);
}

bool deleteFile(const char* path) {
	return remove(path)==0;
}

bool deleteFile(const std::string& path) {
	return remove(path.c_str())==0;
}

bool deleteFile(const UnicodeString& path) {
	std::string str;
	path.toUTF8String(str);
	return remove(str.c_str())==0;
}

bool deleteDir(const char* path) {
	return rmdir(path)==0;
}

bool deleteDir(const std::string& path) {
	return rmdir(path.c_str())==0;
}

bool deleteDir(const UnicodeString& path) {
	std::string str;
	path.toUTF8String(str);
	return rmdir(str.c_str())==0;
}

} // namespace FileSystem

} // namespace duct

<|endoftext|>


<commit_before>//===--- IncorrectRoundings.cpp - clang-tidy ------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "IncorrectRoundings.h"
#include "clang/AST/DeclBase.h"
#include "clang/AST/Type.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/Lex/Lexer.h"

using namespace clang::ast_matchers;

namespace clang {
namespace tidy {
namespace misc {

namespace {
AST_MATCHER(FloatingLiteral, floatHalf) {
  const auto &literal = Node.getValue();
  if ((&Node.getSemantics()) == &llvm::APFloat::IEEEsingle)
    return literal.convertToFloat() == 0.5f;
  if ((&Node.getSemantics()) == &llvm::APFloat::IEEEdouble)
    return literal.convertToDouble() == 0.5;
  return false;
}
} // namespace

void IncorrectRoundings::registerMatchers(MatchFinder *MatchFinder) {
  // Match a floating literal with value 0.5.
  auto FloatHalf = floatLiteral(floatHalf());

  // Match a floating point expression.
  auto FloatType = expr(hasType(realFloatingPointType()));

  // Match a floating literal of 0.5 or a floating literal of 0.5 implicitly.
  // cast to floating type.
  auto FloatOrCastHalf =
      anyOf(FloatHalf,
            implicitCastExpr(FloatType, has(ignoringParenImpCasts(FloatHalf))));

  // Match if either the LHS or RHS is a floating literal of 0.5 or a floating
  // literal of 0.5 and the other is of type double or vice versa.
  auto OneSideHalf = anyOf(allOf(hasLHS(FloatOrCastHalf), hasRHS(FloatType)),
                           allOf(hasRHS(FloatOrCastHalf), hasLHS(FloatType)));

  // Find expressions of cast to int of the sum of a floating point expression
  // and 0.5.
  MatchFinder->addMatcher(
      implicitCastExpr(
          hasImplicitDestinationType(isInteger()),
          ignoringParenCasts(binaryOperator(hasOperatorName("+"), OneSideHalf)))
          .bind("CastExpr"),
      this);
}

void IncorrectRoundings::check(const MatchFinder::MatchResult &Result) {
  const auto *CastExpr = Result.Nodes.getNodeAs<ImplicitCastExpr>("CastExpr");
  diag(CastExpr->getLocStart(),
       "casting (double + 0.5) to integer leads to incorrect rounding; "
       "consider using lround (#include <cmath>) instead");
}

} // namespace misc
} // namespace tidy
} // namespace clang
<commit_msg>Replace APFloatBase static fltSemantics data members with getter functions<commit_after>//===--- IncorrectRoundings.cpp - clang-tidy ------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "IncorrectRoundings.h"
#include "clang/AST/DeclBase.h"
#include "clang/AST/Type.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/Lex/Lexer.h"

using namespace clang::ast_matchers;

namespace clang {
namespace tidy {
namespace misc {

namespace {
AST_MATCHER(FloatingLiteral, floatHalf) {
  const auto &literal = Node.getValue();
  if ((&Node.getSemantics()) == &llvm::APFloat::IEEEsingle())
    return literal.convertToFloat() == 0.5f;
  if ((&Node.getSemantics()) == &llvm::APFloat::IEEEdouble())
    return literal.convertToDouble() == 0.5;
  return false;
}
} // namespace

void IncorrectRoundings::registerMatchers(MatchFinder *MatchFinder) {
  // Match a floating literal with value 0.5.
  auto FloatHalf = floatLiteral(floatHalf());

  // Match a floating point expression.
  auto FloatType = expr(hasType(realFloatingPointType()));

  // Match a floating literal of 0.5 or a floating literal of 0.5 implicitly.
  // cast to floating type.
  auto FloatOrCastHalf =
      anyOf(FloatHalf,
            implicitCastExpr(FloatType, has(ignoringParenImpCasts(FloatHalf))));

  // Match if either the LHS or RHS is a floating literal of 0.5 or a floating
  // literal of 0.5 and the other is of type double or vice versa.
  auto OneSideHalf = anyOf(allOf(hasLHS(FloatOrCastHalf), hasRHS(FloatType)),
                           allOf(hasRHS(FloatOrCastHalf), hasLHS(FloatType)));

  // Find expressions of cast to int of the sum of a floating point expression
  // and 0.5.
  MatchFinder->addMatcher(
      implicitCastExpr(
          hasImplicitDestinationType(isInteger()),
          ignoringParenCasts(binaryOperator(hasOperatorName("+"), OneSideHalf)))
          .bind("CastExpr"),
      this);
}

void IncorrectRoundings::check(const MatchFinder::MatchResult &Result) {
  const auto *CastExpr = Result.Nodes.getNodeAs<ImplicitCastExpr>("CastExpr");
  diag(CastExpr->getLocStart(),
       "casting (double + 0.5) to integer leads to incorrect rounding; "
       "consider using lround (#include <cmath>) instead");
}

} // namespace misc
} // namespace tidy
} // namespace clang
<|endoftext|>


<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, development version     *
*                (c) 2006-2016 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* 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.                   *
*******************************************************************************
*                            SOFA :: Applications                             *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/

#include <SofaTest/Mapping_test.h>
#include <SofaTest/MultiMapping_test.h>
#include <sofa/defaulttype/VecTypes.h>
#include <Compliant/mapping/SafeDistanceMapping.h>

namespace sofa {

/**  Test suite for SafeDistanceMapping
  */
template <typename Mapping>
struct SafeDistanceMappingTest : public Mapping_test<Mapping>
{

    typedef SafeDistanceMappingTest self;
    typedef Mapping_test<Mapping> base;

    typedef sofa::defaulttype::Vec<3,SReal> Vec3;

    Mapping* mapping;

    SafeDistanceMappingTest() {
        mapping = static_cast<Mapping*>(this->base::mapping);
    }

    bool test()
    {
        // we need to increase the error, the mapping is too much non-linear
        // and the finite differences are too different from the analytic Jacobian
        this->errorMax *= 200;

        // mapping parameters
        typename Mapping::pairs_type pairs(3);
        pairs[0][0] = 0; pairs[0][1] = 1;
        pairs[1][0] = 0; pairs[1][1] = 2;
        pairs[2][0] = 0; pairs[2][1] = 2;
        mapping->d_pairs.setValue(pairs);

        helper::vector<SReal> restLengths(3);
        restLengths[0] = 0;
        restLengths[1] = 0;
        restLengths[2] = 1;
        mapping->d_restLengths.setValue(restLengths);

        mapping->d_geometricStiffness.setValue(1); // exact

        // parents
        typename self::InVecCoord xin(3);
        xin[0] = typename self::InCoord(0,0,0);
        xin[1] = typename self::InCoord(325,23,-54);
        xin[2] = typename self::InCoord(1e-5,-1e-5,1e-7);

        typename self::OutVecCoord expected(5);
        expected[0] = typename self::OutCoord(xin[1].norm());
        expected[1] = typename self::OutCoord(xin[2][0]);
        expected[2] = typename self::OutCoord(xin[2][1]);
        expected[3] = typename self::OutCoord(xin[2][2]);
        expected[4] = typename self::OutCoord(xin[2].norm()-restLengths[2]);

        return this->runTest(xin, expected);
    }

};

// Define the list of types to instanciate. We do not necessarily need to test all combinations.
using testing::Types;
typedef Types<
    component::mapping::SafeDistanceMapping<defaulttype::Vec3Types, defaulttype::Vec1Types>
> DataTypes; // the types to instanciate.

// Test suite for all the instanciations
TYPED_TEST_CASE(SafeDistanceMappingTest, DataTypes);

TYPED_TEST( SafeDistanceMappingTest, test )
{
    ASSERT_TRUE( this->test() );
}

///////////////////////////

/**  Test suite for SafeDistanceFromTargetMapping
  */
template <typename Mapping>
struct SafeDistanceFromTargetMappingTest : public Mapping_test<Mapping>
{

    typedef SafeDistanceFromTargetMappingTest self;
    typedef Mapping_test<Mapping> base;

    typedef sofa::defaulttype::Vec<3,SReal> Vec3;

    Mapping* mapping;

    SafeDistanceFromTargetMappingTest() {
        mapping = static_cast<Mapping*>(this->base::mapping);
    }

    bool test()
    {
        // we need to increase the error, the mapping is too much non-linear
        // and the finite differences are too different from the analytic Jacobian
        this->errorMax *= 200;

        // mapping parameters
        helper::vector<unsigned> indices(3);
        indices[0] = 0;
        indices[1] = 1;
        indices[2] = 1;
        mapping->d_indices.setValue(indices);

        typename self::InVecCoord targets(3);
        targets[0] = typename self::InCoord(0,0,0);
        targets[1] = typename self::InCoord(0,0,0);
        targets[2] = typename self::InCoord(0,0,0);
        mapping->d_targetPositions.setValue(targets);

        helper::vector<SReal> restLengths(3);
        restLengths[0] = 0;
        restLengths[1] = 0;
        restLengths[2] = 1;
        mapping->d_restLengths.setValue(restLengths);

        mapping->d_geometricStiffness.setValue(1); // exact

        // parents
        typename self::InVecCoord xin(2);
        xin[0] = typename self::InCoord(325,23,-54);
        xin[1] = typename self::InCoord(1e-5,-1e-5,1e-7);

        typename self::OutVecCoord expected(5);
        expected[0] = typename self::OutCoord(xin[0].norm());
        expected[1] = typename self::OutCoord(xin[1][0]);
        expected[2] = typename self::OutCoord(xin[1][1]);
        expected[3] = typename self::OutCoord(xin[1][2]);
        expected[4] = typename self::OutCoord(xin[1].norm()-restLengths[2]);

        return this->runTest(xin, expected);
    }

};

// Define the list of types to instanciate. We do not necessarily need to test all combinations.
using testing::Types;
typedef Types<
    component::mapping::SafeDistanceFromTargetMapping<defaulttype::Vec3Types, defaulttype::Vec1Types>
> DataTypes2; // the types to instanciate.

// Test suite for all the instanciations
TYPED_TEST_CASE(SafeDistanceFromTargetMappingTest, DataTypes2);

TYPED_TEST( SafeDistanceFromTargetMappingTest, test )
{
    ASSERT_TRUE( this->test() );
}

} // namespace sofa
<commit_msg>[Compliant] increasing SafeDistanceMappingTest threshold<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, development version     *
*                (c) 2006-2016 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* 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.                   *
*******************************************************************************
*                            SOFA :: Applications                             *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/

#include <SofaTest/Mapping_test.h>
#include <SofaTest/MultiMapping_test.h>
#include <sofa/defaulttype/VecTypes.h>
#include <Compliant/mapping/SafeDistanceMapping.h>

namespace sofa {

/**  Test suite for SafeDistanceMapping
  */
template <typename Mapping>
struct SafeDistanceMappingTest : public Mapping_test<Mapping>
{

    typedef SafeDistanceMappingTest self;
    typedef Mapping_test<Mapping> base;

    typedef sofa::defaulttype::Vec<3,SReal> Vec3;

    Mapping* mapping;

    SafeDistanceMappingTest() {
        mapping = static_cast<Mapping*>(this->base::mapping);
    }

    bool test()
    {
        // we need to increase the error, the mapping is too much non-linear
        // and the finite differences are too different from the analytic Jacobian
        this->errorMax *= 300;

        // mapping parameters
        typename Mapping::pairs_type pairs(3);
        pairs[0][0] = 0; pairs[0][1] = 1;
        pairs[1][0] = 0; pairs[1][1] = 2;
        pairs[2][0] = 0; pairs[2][1] = 2;
        mapping->d_pairs.setValue(pairs);

        helper::vector<SReal> restLengths(3);
        restLengths[0] = 0;
        restLengths[1] = 0;
        restLengths[2] = 1;
        mapping->d_restLengths.setValue(restLengths);

        mapping->d_geometricStiffness.setValue(1); // exact

        // parents
        typename self::InVecCoord xin(3);
        xin[0] = typename self::InCoord(0,0,0);
        xin[1] = typename self::InCoord(325,23,-54);
        xin[2] = typename self::InCoord(1e-5,-1e-5,1e-7);

        typename self::OutVecCoord expected(5);
        expected[0] = typename self::OutCoord(xin[1].norm());
        expected[1] = typename self::OutCoord(xin[2][0]);
        expected[2] = typename self::OutCoord(xin[2][1]);
        expected[3] = typename self::OutCoord(xin[2][2]);
        expected[4] = typename self::OutCoord(xin[2].norm()-restLengths[2]);

        return this->runTest(xin, expected);
    }

};

// Define the list of types to instanciate. We do not necessarily need to test all combinations.
using testing::Types;
typedef Types<
    component::mapping::SafeDistanceMapping<defaulttype::Vec3Types, defaulttype::Vec1Types>
> DataTypes; // the types to instanciate.

// Test suite for all the instanciations
TYPED_TEST_CASE(SafeDistanceMappingTest, DataTypes);

TYPED_TEST( SafeDistanceMappingTest, test )
{
    ASSERT_TRUE( this->test() );
}

///////////////////////////

/**  Test suite for SafeDistanceFromTargetMapping
  */
template <typename Mapping>
struct SafeDistanceFromTargetMappingTest : public Mapping_test<Mapping>
{

    typedef SafeDistanceFromTargetMappingTest self;
    typedef Mapping_test<Mapping> base;

    typedef sofa::defaulttype::Vec<3,SReal> Vec3;

    Mapping* mapping;

    SafeDistanceFromTargetMappingTest() {
        mapping = static_cast<Mapping*>(this->base::mapping);
    }

    bool test()
    {
        // we need to increase the error, the mapping is too much non-linear
        // and the finite differences are too different from the analytic Jacobian
        this->errorMax *= 300;

        // mapping parameters
        helper::vector<unsigned> indices(3);
        indices[0] = 0;
        indices[1] = 1;
        indices[2] = 1;
        mapping->d_indices.setValue(indices);

        typename self::InVecCoord targets(3);
        targets[0] = typename self::InCoord(0,0,0);
        targets[1] = typename self::InCoord(0,0,0);
        targets[2] = typename self::InCoord(0,0,0);
        mapping->d_targetPositions.setValue(targets);

        helper::vector<SReal> restLengths(3);
        restLengths[0] = 0;
        restLengths[1] = 0;
        restLengths[2] = 1;
        mapping->d_restLengths.setValue(restLengths);

        mapping->d_geometricStiffness.setValue(1); // exact

        // parents
        typename self::InVecCoord xin(2);
        xin[0] = typename self::InCoord(325,23,-54);
        xin[1] = typename self::InCoord(1e-5,-1e-5,1e-7);

        typename self::OutVecCoord expected(5);
        expected[0] = typename self::OutCoord(xin[0].norm());
        expected[1] = typename self::OutCoord(xin[1][0]);
        expected[2] = typename self::OutCoord(xin[1][1]);
        expected[3] = typename self::OutCoord(xin[1][2]);
        expected[4] = typename self::OutCoord(xin[1].norm()-restLengths[2]);

        return this->runTest(xin, expected);
    }

};

// Define the list of types to instanciate. We do not necessarily need to test all combinations.
using testing::Types;
typedef Types<
    component::mapping::SafeDistanceFromTargetMapping<defaulttype::Vec3Types, defaulttype::Vec1Types>
> DataTypes2; // the types to instanciate.

// Test suite for all the instanciations
TYPED_TEST_CASE(SafeDistanceFromTargetMappingTest, DataTypes2);

TYPED_TEST( SafeDistanceFromTargetMappingTest, test )
{
    ASSERT_TRUE( this->test() );
}

} // namespace sofa
<|endoftext|>


<commit_before>/*
===========================================================================
Daemon BSD Source Code
Copyright (c) 2015, Daemon Developers
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 Daemon developers 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 DAEMON DEVELOPERS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
===========================================================================
*/

#include "common/System.h"
#include "common/String.h"
#include "Crypto.h"
#include <nettle/aes.h>
#include <nettle/base64.h>
#include <nettle/md5.h>
#include <nettle/sha2.h>
#include <nettle/version.h>

// Compatibility with old nettle versions
#if NETTLE_VERSION_MAJOR < 3

#ifndef AES256_KEY_SIZE
#	define AES256_KEY_SIZE 32
#endif

typedef aes_ctx compat_aes256_ctx;

static void nettle_compat_aes256_set_encrypt_key(compat_aes256_ctx *ctx, const uint8_t *key)
{
	nettle_aes_set_encrypt_key(ctx, AES256_KEY_SIZE, key);
}

static void nettle_compat_aes256_set_decrypt_key(compat_aes256_ctx *ctx, const uint8_t *key)
{
	nettle_aes_set_decrypt_key(ctx, AES256_KEY_SIZE, key);
}

static void nettle_compat_aes256_encrypt(const compat_aes256_ctx *ctx,
						   size_t length, uint8_t *dst,
						   const uint8_t *src)
{
	nettle_aes_encrypt(ctx, length, dst, src);
}

static void nettle_compat_aes256_decrypt(const compat_aes256_ctx *ctx,
						   size_t length, uint8_t *dst,
						   const uint8_t *src)
{
	nettle_aes_decrypt(ctx, length, dst, src);
}

static int nettle_compat_base64_decode_update(base64_decode_ctx *ctx,
		     size_t *dst_length,
		     uint8_t *dst,
		     size_t src_length,
		     const uint8_t *src)
{
	unsigned dst_length_uns = *dst_length;
	nettle_base64_decode_update(ctx, &dst_length_uns, dst, src_length, src);
}

#undef aes256_set_encrypt_key
#define nettle_aes256_set_encrypt_key nettle_compat_aes256_set_encrypt_key
#define nettle_aes256_set_decrypt_key nettle_compat_aes256_set_decrypt_key
#define nettle_aes256_invert_key      nettle_compat_aes256_invert_key
#define nettle_aes256_encrypt         nettle_compat_aes256_encrypt
#define nettle_aes256_decrypt         nettle_compat_aes256_decrypt
#define aes256_ctx compat_aes256_ctx
#define nettle_base64_decode_update nettle_compat_base64_decode_update

#endif // NETTLE_VERSION_MAJOR < 3

namespace Crypto {

Data RandomData( std::size_t bytes )
{
    Data data( bytes );
    Sys::GenRandomBytes(data.data(), data.size());
    return data;
}

namespace Encoding {

/*
 * Translates binary data into a hexadecimal string
 */
Data HexEncode( const Data& input )
{
    std::ostringstream stream;
    stream.setf(std::ios::hex, std::ios::basefield);
    stream.fill('0');
    for ( auto ch : input )
    {
        stream.width(2);
        stream << int( ch );
    }
    auto string = stream.str();
    return Data(string.begin(), string.end());
}

/*
 * Translates a hexadecimal string into binary data
 * PRE: input is a valid hexadecimal string
 * POST: output contains the decoded string
 * Returns true on success
 * Note: If the decoding fails, output is unchanged
 */
bool HexDecode( const Data& input, Data& output )
{
    if ( input.size() % 2 )
    {
		return false;
    }

    Data mid( input.size() / 2 );

    for ( std::size_t i = 0; i < input.size(); i += 2 )
    {
        if ( !Str::cisxdigit( input[i] ) || !Str::cisxdigit( input[i+1] ) )
        {
            return false;
        }

        mid[ i / 2 ] = ( Str::GetHex( input[i] ) << 4 ) | Str::GetHex( input[i+1] );
    }

    output = mid;
    return true;
}

/*
 * Translates binary data into a base64 encoded string
 */
Data Base64Encode( const Data& input )
{
    base64_encode_ctx ctx;
    nettle_base64_encode_init( &ctx );

    Data output( BASE64_ENCODE_LENGTH( input.size() ) + BASE64_ENCODE_FINAL_LENGTH );
    int encoded_bytes = nettle_base64_encode_update(
        &ctx, output.data(), input.size(), input.data()
    );
    encoded_bytes += nettle_base64_encode_final( &ctx, output.data() + encoded_bytes );
    output.erase( output.begin() + encoded_bytes, output.end() );
    return output;
}

/*
 * Translates a base64 encoded string into binary data
 * PRE: input is a valid Base64 string
 * POST: output contains the decoded string
 * Returns true on success
 * Note: If the decoding fails, output is unchanged
 */
bool Base64Decode( const Data& input, Data& output )
{
    base64_decode_ctx ctx;
    nettle_base64_decode_init( &ctx );

    Data temp( BASE64_DECODE_LENGTH( input.size() ) );
    std::size_t decoded_bytes = 0;
    if ( !nettle_base64_decode_update( &ctx, &decoded_bytes, temp.data(),
                                       input.size(), input.data() ) )
    {
        return false;
    }

    if ( !nettle_base64_decode_final( &ctx ) )
    {
        return false;
    }

    temp.erase( temp.begin() + decoded_bytes, temp.end() );
    output = temp;
    return true;
}

} // namespace Encoding

namespace Hash {

Data Sha256( const Data& input )
{
    sha256_ctx ctx;
    nettle_sha256_init( &ctx );
    nettle_sha256_update( &ctx, input.size(), input.data() );
    Data output( SHA256_DIGEST_SIZE  );
    nettle_sha256_digest( &ctx, SHA256_DIGEST_SIZE, output.data() );
    return output;
}

Data Md5( const Data& input )
{
    md5_ctx ctx;
    nettle_md5_init( &ctx );
    nettle_md5_update( &ctx, input.size(), input.data() );
    Data output( MD5_DIGEST_SIZE );
    nettle_md5_digest( &ctx, MD5_DIGEST_SIZE, output.data() );
    return output;
}

} // namespace Hash

/*
 * Adds PKCS#7 padding to the data
 */
void AddPadding( Data& target, std::size_t block_size )
{
    auto pad = block_size - target.size() % block_size;
    target.resize( target.size() + pad, pad );
}

/*
 * Encrypts using the AES256 algorthim
 * PRE: Key is 256-bit (32 octects) long
 * POST: output contains the encrypted data
 * Notes: plain_text will be padded using the PKCS#7 algorthm,
 *        if the decoding fails, output is unchanged
 * Returns true on success
 */
bool Aes256Encrypt( Data plain_text, const Data& key, Data& output )
{
    if ( key.size() != AES256_KEY_SIZE )
    {
        return false;
    }
    aes256_ctx ctx;
    nettle_aes256_set_encrypt_key( &ctx, key.data() );
    AddPadding( plain_text, AES_BLOCK_SIZE );
    output.resize( plain_text.size(), 0 );
    nettle_aes256_encrypt( &ctx, plain_text.size(),
        output.data(), plain_text.data() );
    nettle_aes256_decrypt( &ctx, plain_text.size(),
        plain_text.data(), output.data() );
    return true;
}

/*
 * Encrypts using the AES256 algorthim
 * PRE: Key is 256-bit (32 octects) long,
 *      cypher_text.size() is an integer multiple of the AES block size
 * POST: output contains the decrypted data
 * Note: If the decoding fails, output is unchanged
 * Returns true on success
 */
bool Aes256Decrypt( Data cypher_text, const Data& key, Data& output )
{
    if ( key.size() != AES256_KEY_SIZE || cypher_text.size() % AES_BLOCK_SIZE )
    {
        return true;
    }
    aes256_ctx ctx;
    nettle_aes256_set_decrypt_key( &ctx, key.data() );
    output.resize( cypher_text.size(), 0 );
    nettle_aes256_decrypt( &ctx, cypher_text.size(),
        output.data(), cypher_text.data() );
    return true;
}

} // namespace Crypto
<commit_msg>Use a different check to detect old Nettle versions<commit_after>/*
===========================================================================
Daemon BSD Source Code
Copyright (c) 2015, Daemon Developers
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 Daemon developers 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 DAEMON DEVELOPERS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
===========================================================================
*/

#include "common/System.h"
#include "common/String.h"
#include "Crypto.h"
#include <nettle/aes.h>
#include <nettle/base64.h>
#include <nettle/md5.h>
#include <nettle/sha2.h>
#include <nettle/version.h>

// Compatibility with old nettle versions
#if !defined(AES256_KEY_SIZE)

#define AES256_KEY_SIZE 32

typedef aes_ctx compat_aes256_ctx;

static void nettle_compat_aes256_set_encrypt_key(compat_aes256_ctx *ctx, const uint8_t *key)
{
	nettle_aes_set_encrypt_key(ctx, AES256_KEY_SIZE, key);
}

static void nettle_compat_aes256_set_decrypt_key(compat_aes256_ctx *ctx, const uint8_t *key)
{
	nettle_aes_set_decrypt_key(ctx, AES256_KEY_SIZE, key);
}

static void nettle_compat_aes256_encrypt(const compat_aes256_ctx *ctx,
						   size_t length, uint8_t *dst,
						   const uint8_t *src)
{
	nettle_aes_encrypt(ctx, length, dst, src);
}

static void nettle_compat_aes256_decrypt(const compat_aes256_ctx *ctx,
						   size_t length, uint8_t *dst,
						   const uint8_t *src)
{
	nettle_aes_decrypt(ctx, length, dst, src);
}

static int nettle_compat_base64_decode_update(base64_decode_ctx *ctx,
		     size_t *dst_length,
		     uint8_t *dst,
		     size_t src_length,
		     const uint8_t *src)
{
	unsigned dst_length_uns = *dst_length;
	nettle_base64_decode_update(ctx, &dst_length_uns, dst, src_length, src);
}

#undef aes256_set_encrypt_key
#define nettle_aes256_set_encrypt_key nettle_compat_aes256_set_encrypt_key
#define nettle_aes256_set_decrypt_key nettle_compat_aes256_set_decrypt_key
#define nettle_aes256_invert_key      nettle_compat_aes256_invert_key
#define nettle_aes256_encrypt         nettle_compat_aes256_encrypt
#define nettle_aes256_decrypt         nettle_compat_aes256_decrypt
#define aes256_ctx compat_aes256_ctx
#define nettle_base64_decode_update nettle_compat_base64_decode_update

#endif // NETTLE_VERSION_MAJOR < 3

namespace Crypto {

Data RandomData( std::size_t bytes )
{
    Data data( bytes );
    Sys::GenRandomBytes(data.data(), data.size());
    return data;
}

namespace Encoding {

/*
 * Translates binary data into a hexadecimal string
 */
Data HexEncode( const Data& input )
{
    std::ostringstream stream;
    stream.setf(std::ios::hex, std::ios::basefield);
    stream.fill('0');
    for ( auto ch : input )
    {
        stream.width(2);
        stream << int( ch );
    }
    auto string = stream.str();
    return Data(string.begin(), string.end());
}

/*
 * Translates a hexadecimal string into binary data
 * PRE: input is a valid hexadecimal string
 * POST: output contains the decoded string
 * Returns true on success
 * Note: If the decoding fails, output is unchanged
 */
bool HexDecode( const Data& input, Data& output )
{
    if ( input.size() % 2 )
    {
		return false;
    }

    Data mid( input.size() / 2 );

    for ( std::size_t i = 0; i < input.size(); i += 2 )
    {
        if ( !Str::cisxdigit( input[i] ) || !Str::cisxdigit( input[i+1] ) )
        {
            return false;
        }

        mid[ i / 2 ] = ( Str::GetHex( input[i] ) << 4 ) | Str::GetHex( input[i+1] );
    }

    output = mid;
    return true;
}

/*
 * Translates binary data into a base64 encoded string
 */
Data Base64Encode( const Data& input )
{
    base64_encode_ctx ctx;
    nettle_base64_encode_init( &ctx );

    Data output( BASE64_ENCODE_LENGTH( input.size() ) + BASE64_ENCODE_FINAL_LENGTH );
    int encoded_bytes = nettle_base64_encode_update(
        &ctx, output.data(), input.size(), input.data()
    );
    encoded_bytes += nettle_base64_encode_final( &ctx, output.data() + encoded_bytes );
    output.erase( output.begin() + encoded_bytes, output.end() );
    return output;
}

/*
 * Translates a base64 encoded string into binary data
 * PRE: input is a valid Base64 string
 * POST: output contains the decoded string
 * Returns true on success
 * Note: If the decoding fails, output is unchanged
 */
bool Base64Decode( const Data& input, Data& output )
{
    base64_decode_ctx ctx;
    nettle_base64_decode_init( &ctx );

    Data temp( BASE64_DECODE_LENGTH( input.size() ) );
    std::size_t decoded_bytes = 0;
    if ( !nettle_base64_decode_update( &ctx, &decoded_bytes, temp.data(),
                                       input.size(), input.data() ) )
    {
        return false;
    }

    if ( !nettle_base64_decode_final( &ctx ) )
    {
        return false;
    }

    temp.erase( temp.begin() + decoded_bytes, temp.end() );
    output = temp;
    return true;
}

} // namespace Encoding

namespace Hash {

Data Sha256( const Data& input )
{
    sha256_ctx ctx;
    nettle_sha256_init( &ctx );
    nettle_sha256_update( &ctx, input.size(), input.data() );
    Data output( SHA256_DIGEST_SIZE  );
    nettle_sha256_digest( &ctx, SHA256_DIGEST_SIZE, output.data() );
    return output;
}

Data Md5( const Data& input )
{
    md5_ctx ctx;
    nettle_md5_init( &ctx );
    nettle_md5_update( &ctx, input.size(), input.data() );
    Data output( MD5_DIGEST_SIZE );
    nettle_md5_digest( &ctx, MD5_DIGEST_SIZE, output.data() );
    return output;
}

} // namespace Hash

/*
 * Adds PKCS#7 padding to the data
 */
void AddPadding( Data& target, std::size_t block_size )
{
    auto pad = block_size - target.size() % block_size;
    target.resize( target.size() + pad, pad );
}

/*
 * Encrypts using the AES256 algorthim
 * PRE: Key is 256-bit (32 octects) long
 * POST: output contains the encrypted data
 * Notes: plain_text will be padded using the PKCS#7 algorthm,
 *        if the decoding fails, output is unchanged
 * Returns true on success
 */
bool Aes256Encrypt( Data plain_text, const Data& key, Data& output )
{
    if ( key.size() != AES256_KEY_SIZE )
    {
        return false;
    }
    aes256_ctx ctx;
    nettle_aes256_set_encrypt_key( &ctx, key.data() );
    AddPadding( plain_text, AES_BLOCK_SIZE );
    output.resize( plain_text.size(), 0 );
    nettle_aes256_encrypt( &ctx, plain_text.size(),
        output.data(), plain_text.data() );
    nettle_aes256_decrypt( &ctx, plain_text.size(),
        plain_text.data(), output.data() );
    return true;
}

/*
 * Encrypts using the AES256 algorthim
 * PRE: Key is 256-bit (32 octects) long,
 *      cypher_text.size() is an integer multiple of the AES block size
 * POST: output contains the decrypted data
 * Note: If the decoding fails, output is unchanged
 * Returns true on success
 */
bool Aes256Decrypt( Data cypher_text, const Data& key, Data& output )
{
    if ( key.size() != AES256_KEY_SIZE || cypher_text.size() % AES_BLOCK_SIZE )
    {
        return true;
    }
    aes256_ctx ctx;
    nettle_aes256_set_decrypt_key( &ctx, key.data() );
    output.resize( cypher_text.size(), 0 );
    nettle_aes256_decrypt( &ctx, cypher_text.size(),
        output.data(), cypher_text.data() );
    return true;
}

} // namespace Crypto
<|endoftext|>


<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: parsedFunction.C,v 1.4 2002/12/18 16:00:34 sturm Exp $

#include <BALL/MATHS/parsedFunction.h>

extern int parsedFunctionparse();
extern double parsedFunctionResult;
extern void parsedFunction_initBuffer(const char*);
extern void parsedFunction_delBuffer();

namespace BALL
{
	HashMap<String, double*> *parsedFunctionConstants;
	HashMap<String, double(*)(double)> *parsedFunctionFunctions;

	template <typename arg>
	ParsedFunction<arg>::ParsedFunction()
		throw()
		:	constants_(),
			functions_(),
			expression_("")
	{
		initTable();
	}

	template <typename arg>
	ParsedFunction<arg>::ParsedFunction(String expression)
		throw()
		:	constants_(),
			functions_(),
			expression_(expression)
	{
		initTable();
	}

	/** Strange... gcc-3.0.1 needs this constructor as a non-template version... **/
	template <>
	ParsedFunction<float>::ParsedFunction(String expression)
		throw()
		: constants_(),
			functions_(),
			expression_(expression)

	{
		initTable();
	}

	template <typename arg>
	ParsedFunction<arg>::ParsedFunction(const ParsedFunction& func)
		throw()
	{
		constants_ = func.constants_;
		functions_ = func.functions_;
		expression_ = func.expression_;
		initTable();
	}

	template <typename arg>
	ParsedFunction<arg>::~ParsedFunction()
		throw()
	{
	}

	/** Strange... gcc-3.0.1 needs this destructor in a non-template version... **/
	template <>
	ParsedFunction<float>::~ParsedFunction()
		throw()
	{
	}

	template <typename arg>
	double ParsedFunction<arg>::operator () (arg argument)
		throw(Exception::ParseError)
	{
		constants_["X"] = (double) &argument;
		parsedFunctionConstants = &constants_;
		parsedFunctionFunctions = &functions_;
		parsedFunction_initBuffer(expression_.c_str());
		parsedFunctionparse();
		parsedFunction_delBuffer();

		return parsedFunctionResult;
	}

	template <>
	double ParsedFunction<float>::operator () (float argument)
		throw(Exception::ParseError)
	{
		double arg = argument;
		constants_["X"] = &arg;
		parsedFunctionConstants = &constants_;
		parsedFunctionFunctions = &functions_;
		parsedFunction_initBuffer(expression_.c_str());
		parsedFunctionparse();
		parsedFunction_delBuffer();
		return parsedFunctionResult;
	}

	template <typename arg>
	void ParsedFunction<arg>::initTable()
		throw()
	{
		// initialize the functions table
		functions_["sin"] = (double(*)(double))&sin;
		functions_["cos"] = (double(*)(double))&cos;
		functions_["asin"] = (double(*)(double))&asin;
		functions_["acos"] = (double(*)(double))&acos;
		functions_["tan"] = (double(*)(double))&tan;
		functions_["atan"] = (double(*)(double))&atan;
		functions_["ln"] = (double(*)(double))&log;
		functions_["exp"] = (double(*)(double))&exp;
		functions_[""] = 0;
	}
}
<commit_msg>parsedFunction.C<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: parsedFunction.C,v 1.5 2002/12/20 21:00:57 anhi Exp $

#include <BALL/MATHS/parsedFunction.h>

extern int parsedFunctionparse();
extern double parsedFunctionResult;
extern void parsedFunction_initBuffer(const char*);
extern void parsedFunction_delBuffer();

namespace BALL
{
	HashMap<String, double*> *parsedFunctionConstants;
	HashMap<String, double(*)(double)> *parsedFunctionFunctions;

	template <typename arg>
	ParsedFunction<arg>::ParsedFunction()
		throw()
		:	constants_(),
			functions_(),
			expression_("")
	{
		initTable();
	}

	template <typename arg>
	ParsedFunction<arg>::ParsedFunction(const String& expression)
		throw()
		:	constants_(),
			functions_(),
			expression_(expression)
	{
		initTable();
	}

	/* Strange... gcc-3.0.1 needs this constructor as a non-template version... */
	template <>
	ParsedFunction<float>::ParsedFunction(const String& expression)
		throw()
		: constants_(),
			functions_(),
			expression_(expression)

	{
		initTable();
	}

	template <typename arg>
	ParsedFunction<arg>::ParsedFunction(const ParsedFunction& func)
		throw()
	{
		constants_ = func.constants_;
		functions_ = func.functions_;
		expression_ = func.expression_;
		initTable();
	}

	template <typename arg>
	ParsedFunction<arg>::~ParsedFunction()
		throw()
	{
	}

	/** Strange... gcc-3.0.1 needs this destructor in a non-template version... **/
	template <>
	ParsedFunction<float>::~ParsedFunction()
		throw()
	{
	}

	template <typename arg>
	double ParsedFunction<arg>::operator () (arg argument)
		throw(Exception::ParseError)
	{
		constants_["X"] = (double) &argument;
		parsedFunctionConstants = &constants_;
		parsedFunctionFunctions = &functions_;
		parsedFunction_initBuffer(expression_.c_str());
		parsedFunctionparse();
		parsedFunction_delBuffer();

		return parsedFunctionResult;
	}

	template <>
	double ParsedFunction<float>::operator () (float argument)
		throw(Exception::ParseError)
	{
		double arg = argument;
		constants_["X"] = &arg;
		parsedFunctionConstants = &constants_;
		parsedFunctionFunctions = &functions_;
		parsedFunction_initBuffer(expression_.c_str());
		parsedFunctionparse();
		parsedFunction_delBuffer();
		return parsedFunctionResult;
	}

	template <typename arg>
	void ParsedFunction<arg>::initTable()
		throw()
	{
		// initialize the functions table
		functions_["sin"] = (double(*)(double))&sin;
		functions_["cos"] = (double(*)(double))&cos;
		functions_["asin"] = (double(*)(double))&asin;
		functions_["acos"] = (double(*)(double))&acos;
		functions_["tan"] = (double(*)(double))&tan;
		functions_["atan"] = (double(*)(double))&atan;
		functions_["ln"] = (double(*)(double))&log;
		functions_["exp"] = (double(*)(double))&exp;
		functions_[""] = 0;
	}
}
<|endoftext|>


<commit_before>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/common/api/atom_api_clipboard.h"

#include "atom/common/native_mate_converters/image_converter.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "base/strings/utf_string_conversions.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/base/clipboard/scoped_clipboard_writer.h"

#include "atom/common/node_includes.h"

namespace atom {

namespace api {

ui::ClipboardType Clipboard::GetClipboardType(mate::Arguments* args) {
  std::string type;
  if (args->GetNext(&type) && type == "selection")
    return ui::CLIPBOARD_TYPE_SELECTION;
  else
    return ui::CLIPBOARD_TYPE_COPY_PASTE;
}

std::vector<base::string16> Clipboard::AvailableFormats(mate::Arguments* args) {
  std::vector<base::string16> format_types;
  bool ignore;
  ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
  clipboard->ReadAvailableTypes(GetClipboardType(args), &format_types, &ignore);
  return format_types;
}

bool Clipboard::Has(const std::string& format_string, mate::Arguments* args) {
  ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
  ui::Clipboard::FormatType format(ui::Clipboard::GetFormatType(format_string));
  return clipboard->IsFormatAvailable(format, GetClipboardType(args));
}

std::string Clipboard::Read(const std::string& format_string) {
  ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
  ui::Clipboard::FormatType format(ui::Clipboard::GetFormatType(format_string));

  std::string data;
  clipboard->ReadData(format, &data);
  return data;
}

v8::Local<v8::Value> Clipboard::ReadBuffer(const std::string& format_string,
                                           mate::Arguments* args) {
  std::string data = Read(format_string);
  return node::Buffer::Copy(
      args->isolate(), data.data(), data.length()).ToLocalChecked();
}

void Clipboard::WriteBuffer(const std::string& format,
                            const v8::Local<v8::Value> buffer,
                            mate::Arguments* args) {
  if (!node::Buffer::HasInstance(buffer)) {
    args->ThrowError("buffer must be a node Buffer");
    return;
  }

  ui::ScopedClipboardWriter writer(GetClipboardType(args));
  writer.WriteData(node::Buffer::Data(buffer), node::Buffer::Length(buffer),
                   ui::Clipboard::GetFormatType(format));
}

void Clipboard::Write(const mate::Dictionary& data, mate::Arguments* args) {
  ui::ScopedClipboardWriter writer(GetClipboardType(args));
  base::string16 text, html, bookmark;
  gfx::Image image;

  if (data.Get("text", &text)) {
    writer.WriteText(text);

    if (data.Get("bookmark", &bookmark))
      writer.WriteBookmark(bookmark, base::UTF16ToUTF8(text));
  }

  if (data.Get("rtf", &text)) {
    std::string rtf = base::UTF16ToUTF8(text);
    writer.WriteRTF(rtf);
  }

  if (data.Get("html", &html))
    writer.WriteHTML(html, std::string());

  if (data.Get("image", &image))
    writer.WriteImage(image.AsBitmap());
}

base::string16 Clipboard::ReadText(mate::Arguments* args) {
  base::string16 data;
  ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
  auto type = GetClipboardType(args);
  if (clipboard->IsFormatAvailable(
      ui::Clipboard::GetPlainTextWFormatType(), type)) {
    clipboard->ReadText(type, &data);
  } else if (clipboard->IsFormatAvailable(
             ui::Clipboard::GetPlainTextFormatType(), type)) {
    std::string result;
    clipboard->ReadAsciiText(type, &result);
    data = base::ASCIIToUTF16(result);
  }
  return data;
}

void Clipboard::WriteText(const base::string16& text, mate::Arguments* args) {
  ui::ScopedClipboardWriter writer(GetClipboardType(args));
  writer.WriteText(text);
}

base::string16 Clipboard::ReadRtf(mate::Arguments* args) {
  std::string data;
  ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
  clipboard->ReadRTF(GetClipboardType(args), &data);
  return base::UTF8ToUTF16(data);
}

void Clipboard::WriteRtf(const std::string& text, mate::Arguments* args) {
  ui::ScopedClipboardWriter writer(GetClipboardType(args));
  writer.WriteRTF(text);
}

base::string16 Clipboard::ReadHtml(mate::Arguments* args) {
  base::string16 data;
  base::string16 html;
  std::string url;
  uint32_t start;
  uint32_t end;
  ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
  clipboard->ReadHTML(GetClipboardType(args), &html, &url, &start, &end);
  data = html.substr(start, end - start);
  return data;
}

void Clipboard::WriteHtml(const base::string16& html, mate::Arguments* args) {
  ui::ScopedClipboardWriter writer(GetClipboardType(args));
  writer.WriteHTML(html, std::string());
}

v8::Local<v8::Value> Clipboard::ReadBookmark(mate::Arguments* args) {
  base::string16 title;
  std::string url;
  mate::Dictionary dict = mate::Dictionary::CreateEmpty(args->isolate());
  ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
  clipboard->ReadBookmark(&title, &url);
  dict.Set("title", title);
  dict.Set("url", url);
  return dict.GetHandle();
}

void Clipboard::WriteBookmark(const base::string16& title,
                              const std::string& url,
                              mate::Arguments* args) {
  ui::ScopedClipboardWriter writer(GetClipboardType(args));
  writer.WriteBookmark(title, url);
}

gfx::Image Clipboard::ReadImage(mate::Arguments* args) {
  ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
  SkBitmap bitmap = clipboard->ReadImage(GetClipboardType(args));
  return gfx::Image::CreateFrom1xBitmap(bitmap);
}

void Clipboard::WriteImage(const gfx::Image& image, mate::Arguments* args) {
  ui::ScopedClipboardWriter writer(GetClipboardType(args));
  SkBitmap bmp;
  if (image.AsBitmap().deepCopyTo(&bmp)) {
    writer.WriteImage(bmp);
  } else {
    writer.WriteImage(image.AsBitmap());
  }
}

#if !defined(OS_MACOSX)
void Clipboard::WriteFindText(const base::string16& text) {}
base::string16 Clipboard::ReadFindText() { return base::string16(); }
#endif

void Clipboard::Clear(mate::Arguments* args) {
  ui::Clipboard::GetForCurrentThread()->Clear(GetClipboardType(args));
}

}  // namespace api

}  // namespace atom

namespace {

void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
                v8::Local<v8::Context> context, void* priv) {
  mate::Dictionary dict(context->GetIsolate(), exports);
  dict.SetMethod("availableFormats", &atom::api::Clipboard::AvailableFormats);
  dict.SetMethod("has", &atom::api::Clipboard::Has);
  dict.SetMethod("read", &atom::api::Clipboard::Read);
  dict.SetMethod("write", &atom::api::Clipboard::Write);
  dict.SetMethod("readText", &atom::api::Clipboard::ReadText);
  dict.SetMethod("writeText", &atom::api::Clipboard::WriteText);
  dict.SetMethod("readRTF", &atom::api::Clipboard::ReadRtf);
  dict.SetMethod("writeRTF", &atom::api::Clipboard::WriteRtf);
  dict.SetMethod("readHTML", &atom::api::Clipboard::ReadHtml);
  dict.SetMethod("writeHTML", &atom::api::Clipboard::WriteHtml);
  dict.SetMethod("readBookmark", &atom::api::Clipboard::ReadBookmark);
  dict.SetMethod("writeBookmark", &atom::api::Clipboard::WriteBookmark);
  dict.SetMethod("readImage", &atom::api::Clipboard::ReadImage);
  dict.SetMethod("writeImage", &atom::api::Clipboard::WriteImage);
  dict.SetMethod("readFindText", &atom::api::Clipboard::ReadFindText);
  dict.SetMethod("writeFindText", &atom::api::Clipboard::WriteFindText);
  dict.SetMethod("readBuffer", &atom::api::Clipboard::ReadBuffer);
  dict.SetMethod("writeBuffer", &atom::api::Clipboard::WriteBuffer);
  dict.SetMethod("clear", &atom::api::Clipboard::Clear);

  // TODO(kevinsawicki): Remove in 2.0, deprecate before then with warnings
  dict.SetMethod("readRtf", &atom::api::Clipboard::ReadRtf);
  dict.SetMethod("writeRtf", &atom::api::Clipboard::WriteRtf);
  dict.SetMethod("readHtml", &atom::api::Clipboard::ReadHtml);
  dict.SetMethod("writeHtml", &atom::api::Clipboard::WriteHtml);
}

}  // namespace

NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_common_clipboard, Initialize)
<commit_msg>added comment to mention sk_tools_utils::copy_to<commit_after>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/common/api/atom_api_clipboard.h"

#include "atom/common/native_mate_converters/image_converter.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "base/strings/utf_string_conversions.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/base/clipboard/scoped_clipboard_writer.h"

#include "atom/common/node_includes.h"

namespace atom {

namespace api {

ui::ClipboardType Clipboard::GetClipboardType(mate::Arguments* args) {
  std::string type;
  if (args->GetNext(&type) && type == "selection")
    return ui::CLIPBOARD_TYPE_SELECTION;
  else
    return ui::CLIPBOARD_TYPE_COPY_PASTE;
}

std::vector<base::string16> Clipboard::AvailableFormats(mate::Arguments* args) {
  std::vector<base::string16> format_types;
  bool ignore;
  ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
  clipboard->ReadAvailableTypes(GetClipboardType(args), &format_types, &ignore);
  return format_types;
}

bool Clipboard::Has(const std::string& format_string, mate::Arguments* args) {
  ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
  ui::Clipboard::FormatType format(ui::Clipboard::GetFormatType(format_string));
  return clipboard->IsFormatAvailable(format, GetClipboardType(args));
}

std::string Clipboard::Read(const std::string& format_string) {
  ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
  ui::Clipboard::FormatType format(ui::Clipboard::GetFormatType(format_string));

  std::string data;
  clipboard->ReadData(format, &data);
  return data;
}

v8::Local<v8::Value> Clipboard::ReadBuffer(const std::string& format_string,
                                           mate::Arguments* args) {
  std::string data = Read(format_string);
  return node::Buffer::Copy(
      args->isolate(), data.data(), data.length()).ToLocalChecked();
}

void Clipboard::WriteBuffer(const std::string& format,
                            const v8::Local<v8::Value> buffer,
                            mate::Arguments* args) {
  if (!node::Buffer::HasInstance(buffer)) {
    args->ThrowError("buffer must be a node Buffer");
    return;
  }

  ui::ScopedClipboardWriter writer(GetClipboardType(args));
  writer.WriteData(node::Buffer::Data(buffer), node::Buffer::Length(buffer),
                   ui::Clipboard::GetFormatType(format));
}

void Clipboard::Write(const mate::Dictionary& data, mate::Arguments* args) {
  ui::ScopedClipboardWriter writer(GetClipboardType(args));
  base::string16 text, html, bookmark;
  gfx::Image image;

  if (data.Get("text", &text)) {
    writer.WriteText(text);

    if (data.Get("bookmark", &bookmark))
      writer.WriteBookmark(bookmark, base::UTF16ToUTF8(text));
  }

  if (data.Get("rtf", &text)) {
    std::string rtf = base::UTF16ToUTF8(text);
    writer.WriteRTF(rtf);
  }

  if (data.Get("html", &html))
    writer.WriteHTML(html, std::string());

  if (data.Get("image", &image))
    writer.WriteImage(image.AsBitmap());
}

base::string16 Clipboard::ReadText(mate::Arguments* args) {
  base::string16 data;
  ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
  auto type = GetClipboardType(args);
  if (clipboard->IsFormatAvailable(
      ui::Clipboard::GetPlainTextWFormatType(), type)) {
    clipboard->ReadText(type, &data);
  } else if (clipboard->IsFormatAvailable(
             ui::Clipboard::GetPlainTextFormatType(), type)) {
    std::string result;
    clipboard->ReadAsciiText(type, &result);
    data = base::ASCIIToUTF16(result);
  }
  return data;
}

void Clipboard::WriteText(const base::string16& text, mate::Arguments* args) {
  ui::ScopedClipboardWriter writer(GetClipboardType(args));
  writer.WriteText(text);
}

base::string16 Clipboard::ReadRtf(mate::Arguments* args) {
  std::string data;
  ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
  clipboard->ReadRTF(GetClipboardType(args), &data);
  return base::UTF8ToUTF16(data);
}

void Clipboard::WriteRtf(const std::string& text, mate::Arguments* args) {
  ui::ScopedClipboardWriter writer(GetClipboardType(args));
  writer.WriteRTF(text);
}

base::string16 Clipboard::ReadHtml(mate::Arguments* args) {
  base::string16 data;
  base::string16 html;
  std::string url;
  uint32_t start;
  uint32_t end;
  ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
  clipboard->ReadHTML(GetClipboardType(args), &html, &url, &start, &end);
  data = html.substr(start, end - start);
  return data;
}

void Clipboard::WriteHtml(const base::string16& html, mate::Arguments* args) {
  ui::ScopedClipboardWriter writer(GetClipboardType(args));
  writer.WriteHTML(html, std::string());
}

v8::Local<v8::Value> Clipboard::ReadBookmark(mate::Arguments* args) {
  base::string16 title;
  std::string url;
  mate::Dictionary dict = mate::Dictionary::CreateEmpty(args->isolate());
  ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
  clipboard->ReadBookmark(&title, &url);
  dict.Set("title", title);
  dict.Set("url", url);
  return dict.GetHandle();
}

void Clipboard::WriteBookmark(const base::string16& title,
                              const std::string& url,
                              mate::Arguments* args) {
  ui::ScopedClipboardWriter writer(GetClipboardType(args));
  writer.WriteBookmark(title, url);
}

gfx::Image Clipboard::ReadImage(mate::Arguments* args) {
  ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
  SkBitmap bitmap = clipboard->ReadImage(GetClipboardType(args));
  return gfx::Image::CreateFrom1xBitmap(bitmap);
}

void Clipboard::WriteImage(const gfx::Image& image, mate::Arguments* args) {
  ui::ScopedClipboardWriter writer(GetClipboardType(args));
  SkBitmap bmp;
  // TODO(ferreus): Replace with sk_tools_utils::copy_to (chrome60)
  if (image.AsBitmap().deepCopyTo(&bmp)) {
    writer.WriteImage(bmp);
  } else {
    writer.WriteImage(image.AsBitmap());
  }
}

#if !defined(OS_MACOSX)
void Clipboard::WriteFindText(const base::string16& text) {}
base::string16 Clipboard::ReadFindText() { return base::string16(); }
#endif

void Clipboard::Clear(mate::Arguments* args) {
  ui::Clipboard::GetForCurrentThread()->Clear(GetClipboardType(args));
}

}  // namespace api

}  // namespace atom

namespace {

void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
                v8::Local<v8::Context> context, void* priv) {
  mate::Dictionary dict(context->GetIsolate(), exports);
  dict.SetMethod("availableFormats", &atom::api::Clipboard::AvailableFormats);
  dict.SetMethod("has", &atom::api::Clipboard::Has);
  dict.SetMethod("read", &atom::api::Clipboard::Read);
  dict.SetMethod("write", &atom::api::Clipboard::Write);
  dict.SetMethod("readText", &atom::api::Clipboard::ReadText);
  dict.SetMethod("writeText", &atom::api::Clipboard::WriteText);
  dict.SetMethod("readRTF", &atom::api::Clipboard::ReadRtf);
  dict.SetMethod("writeRTF", &atom::api::Clipboard::WriteRtf);
  dict.SetMethod("readHTML", &atom::api::Clipboard::ReadHtml);
  dict.SetMethod("writeHTML", &atom::api::Clipboard::WriteHtml);
  dict.SetMethod("readBookmark", &atom::api::Clipboard::ReadBookmark);
  dict.SetMethod("writeBookmark", &atom::api::Clipboard::WriteBookmark);
  dict.SetMethod("readImage", &atom::api::Clipboard::ReadImage);
  dict.SetMethod("writeImage", &atom::api::Clipboard::WriteImage);
  dict.SetMethod("readFindText", &atom::api::Clipboard::ReadFindText);
  dict.SetMethod("writeFindText", &atom::api::Clipboard::WriteFindText);
  dict.SetMethod("readBuffer", &atom::api::Clipboard::ReadBuffer);
  dict.SetMethod("writeBuffer", &atom::api::Clipboard::WriteBuffer);
  dict.SetMethod("clear", &atom::api::Clipboard::Clear);

  // TODO(kevinsawicki): Remove in 2.0, deprecate before then with warnings
  dict.SetMethod("readRtf", &atom::api::Clipboard::ReadRtf);
  dict.SetMethod("writeRtf", &atom::api::Clipboard::WriteRtf);
  dict.SetMethod("readHtml", &atom::api::Clipboard::ReadHtml);
  dict.SetMethod("writeHtml", &atom::api::Clipboard::WriteHtml);
}

}  // namespace

NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_common_clipboard, Initialize)
<|endoftext|>


<commit_before>// This class
#include <Internal/ParticleClasses/ParticleEmitter.hpp>
//#include <FluidManager.hpp> // Included for the sake of particle data. Kinda silly, really
#include <Internal/PhysicsModuleImplementation.hpp>

using namespace DirectX;
using namespace physx;
namespace DoremiEngine
{
    namespace Physics
    {
        ParticleEmitter::ParticleEmitter(ParticleEmitterData p_data, InternalPhysicsUtils& p_utils)
            : m_this(p_data), m_utils(p_utils), m_timeSinceLast(0)
        {
            m_nextIndex = 0;
            m_particleSystem = m_utils.m_physics->createParticleSystem(PARTICLE_MAX_COUNT);
            m_particleSystem->setMaxMotionDistance(PARTICLE_MAX_MOTION_DISTANCE);
            m_utils.m_worldScene->addActor(*m_particleSystem);
            // Might be necessary to set flag to collide with dynamics
            // m_particleSystem->setParticleBaseFlag(PxParticleBaseFlag::eCOLLISION_WITH_DYNAMIC_ACTORS, true);
            m_particleSystem->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, true); // Should not be here
        }
        ParticleEmitter::~ParticleEmitter() {}

        void ParticleEmitter::SetPosition(XMFLOAT3 p_position) { m_this.m_position = p_position; }
        void ParticleEmitter::SetDirection(XMFLOAT4 p_direction) { m_this.m_direction = p_direction; }
        void ParticleEmitter::SetGravity(bool p_gravity) { m_particleSystem->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, p_gravity); }

        void ParticleEmitter::GetPositions(vector<XMFLOAT3>& o_positions)
        {
            // This is a bit harder than it really ought to be...
            PxParticleReadData* readData = m_particleSystem->lockParticleReadData();
            PxStrideIterator<const PxVec3> positions = readData->positionBuffer;
            PxStrideIterator<const PxVec3> velocities = readData->velocityBuffer;
            PxStrideIterator<const PxParticleFlags> flags = readData->flagsBuffer;
            vector<XMFLOAT3> velocitiesVector;

            vector<int> indicesOfParticlesToBeReleased;

            uint32_t numParticles = readData->validParticleRange;
            for(uint32_t i = 0; i < numParticles; i++)
            {
                // Check if particles are supposed to be removed

                if(flags[i] & (PxParticleFlag::eCOLLISION_WITH_DRAIN)) // | PxParticleFlag::eVALID))
                {
                    indicesOfParticlesToBeReleased.push_back(i);
                }
                else if(flags[i] & PxParticleFlag::eVALID)
                {
                    o_positions.push_back(XMFLOAT3(positions[i].x, positions[i].y, positions[i].z));
                }
            }
            readData->unlock();
            if(indicesOfParticlesToBeReleased.size() != 0)
            {
                PxStrideIterator<const PxU32> inicesPX(reinterpret_cast<PxU32*>(&indicesOfParticlesToBeReleased[0]));
                m_particleSystem->releaseParticles(indicesOfParticlesToBeReleased.size(), inicesPX);
            }
        }

        void ParticleEmitter::SetData(ParticleEmitterData p_data) { m_this = p_data; }

        void ParticleEmitter::Update(float p_dt)
        {
            if(m_this.m_active)
            {
                // Update time since last particle wave was spawned
                m_timeSinceLast += p_dt;
                if(m_timeSinceLast > m_this.m_emissionRate)
                {
                    m_timeSinceLast = 0;
                    vector<XMFLOAT3> velocities;
                    vector<XMFLOAT3> positions;
                    vector<int> indices;
                    /// Time for more particles!
                    /// These particles will be spawned in a sort of grid (atm)
                    for(int x = -m_this.m_density; x < m_this.m_density * 2 - 1; x++)
                    {
                        for(int y = -m_this.m_density; y < m_this.m_density * 2; y++)
                        {
                            // Calculate angles in local space
                            float xAngle = (x / m_this.m_density) * m_this.m_emissionAreaDimensions.x;
                            float yAngle = (y / m_this.m_density) * m_this.m_emissionAreaDimensions.y;
                            // Define standard target in local space
                            XMVECTOR particleVelocityVec = XMLoadFloat3(&XMFLOAT3(0, 0, 1));
                            XMMATRIX rotMatLocal = XMMatrixRotationRollPitchYaw(xAngle, yAngle, 0);
                            particleVelocityVec = XMVector3Transform(particleVelocityVec, rotMatLocal);
                            // Move velocity vector into world space
                            XMMATRIX rotMatWorld = XMMatrixRotationQuaternion(XMLoadFloat4(&m_this.m_direction));
                            particleVelocityVec = XMVector3Transform(particleVelocityVec, rotMatWorld);
                            // Multiply with pressure
                            particleVelocityVec *= m_this.m_launchPressure;
                            // Store in vector
                            XMFLOAT3 velocity;
                            XMStoreFloat3(&velocity, particleVelocityVec);
                            velocities.push_back(velocity);

                            // Add position (only emitts from the center of the emitter atm
                            float launchOffset = 0.1;
                            XMVECTOR positionVec = XMLoadFloat3(&m_this.m_position);
                            positionVec += launchOffset * particleVelocityVec;
                            XMFLOAT3 position;
                            XMStoreFloat3(&position, positionVec);

                            positions.push_back(position);

                            // Add index (silly way just to make it work atm)
                            indices.push_back(m_nextIndex);
                            m_nextIndex++;
                        }
                    }

                    if(positions.size() > 0 && !(m_nextIndex > PARTICLE_MAX_COUNT)) // no point doing things if there's no new particles
                    {
                        // Cast into PhysX datatypes
                        PxVec3* positionsPX = reinterpret_cast<PxVec3*>(&positions[0]);
                        PxVec3* velocitiesPX = reinterpret_cast<PxVec3*>(&velocities[0]);
                        PxU32* indicesPX = reinterpret_cast<PxU32*>(&indices[0]);

                        // Create the particles
                        PxParticleCreationData newParticlesData;
                        newParticlesData.numParticles = positions.size();
                        newParticlesData.positionBuffer = PxStrideIterator<const PxVec3>(positionsPX);
                        newParticlesData.velocityBuffer = PxStrideIterator<const PxVec3>(velocitiesPX);
                        newParticlesData.indexBuffer = PxStrideIterator<const PxU32>(indicesPX);
                        m_particleSystem->createParticles(newParticlesData);
                    }
                    else
                    {
                        // No new particles. Do nothing
                    }
                }
            }
        }
    }
}<commit_msg>Fixed float warning in ParticleEmitter.cpp DoremiEngine/Physics/Source/ParticleClasses/ParticleEmitter.cpp<commit_after>// This class
#include <Internal/ParticleClasses/ParticleEmitter.hpp>
//#include <FluidManager.hpp> // Included for the sake of particle data. Kinda silly, really
#include <Internal/PhysicsModuleImplementation.hpp>

using namespace DirectX;
using namespace physx;
namespace DoremiEngine
{
    namespace Physics
    {
        ParticleEmitter::ParticleEmitter(ParticleEmitterData p_data, InternalPhysicsUtils& p_utils)
            : m_this(p_data), m_utils(p_utils), m_timeSinceLast(0)
        {
            m_nextIndex = 0;
            m_particleSystem = m_utils.m_physics->createParticleSystem(PARTICLE_MAX_COUNT);
            m_particleSystem->setMaxMotionDistance(PARTICLE_MAX_MOTION_DISTANCE);
            m_utils.m_worldScene->addActor(*m_particleSystem);
            // Might be necessary to set flag to collide with dynamics
            // m_particleSystem->setParticleBaseFlag(PxParticleBaseFlag::eCOLLISION_WITH_DYNAMIC_ACTORS, true);
            m_particleSystem->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, true); // Should not be here
        }
        ParticleEmitter::~ParticleEmitter() {}

        void ParticleEmitter::SetPosition(XMFLOAT3 p_position) { m_this.m_position = p_position; }
        void ParticleEmitter::SetDirection(XMFLOAT4 p_direction) { m_this.m_direction = p_direction; }
        void ParticleEmitter::SetGravity(bool p_gravity) { m_particleSystem->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, p_gravity); }

        void ParticleEmitter::GetPositions(vector<XMFLOAT3>& o_positions)
        {
            // This is a bit harder than it really ought to be...
            PxParticleReadData* readData = m_particleSystem->lockParticleReadData();
            PxStrideIterator<const PxVec3> positions = readData->positionBuffer;
            PxStrideIterator<const PxVec3> velocities = readData->velocityBuffer;
            PxStrideIterator<const PxParticleFlags> flags = readData->flagsBuffer;
            vector<XMFLOAT3> velocitiesVector;

            vector<int> indicesOfParticlesToBeReleased;

            uint32_t numParticles = readData->validParticleRange;
            for(uint32_t i = 0; i < numParticles; i++)
            {
                // Check if particles are supposed to be removed

                if(flags[i] & (PxParticleFlag::eCOLLISION_WITH_DRAIN)) // | PxParticleFlag::eVALID))
                {
                    indicesOfParticlesToBeReleased.push_back(i);
                }
                else if(flags[i] & PxParticleFlag::eVALID)
                {
                    o_positions.push_back(XMFLOAT3(positions[i].x, positions[i].y, positions[i].z));
                }
            }
            readData->unlock();
            if(indicesOfParticlesToBeReleased.size() != 0)
            {
                PxStrideIterator<const PxU32> inicesPX(reinterpret_cast<PxU32*>(&indicesOfParticlesToBeReleased[0]));
                m_particleSystem->releaseParticles(indicesOfParticlesToBeReleased.size(), inicesPX);
            }
        }

        void ParticleEmitter::SetData(ParticleEmitterData p_data) { m_this = p_data; }

        void ParticleEmitter::Update(float p_dt)
        {
            if(m_this.m_active)
            {
                // Update time since last particle wave was spawned
                m_timeSinceLast += p_dt;
                if(m_timeSinceLast > m_this.m_emissionRate)
                {
                    m_timeSinceLast = 0;
                    vector<XMFLOAT3> velocities;
                    vector<XMFLOAT3> positions;
                    vector<int> indices;
                    /// Time for more particles!
                    /// These particles will be spawned in a sort of grid (atm)
                    for(int x = -m_this.m_density; x < m_this.m_density * 2 - 1; x++)
                    {
                        for(int y = -m_this.m_density; y < m_this.m_density * 2; y++)
                        {
                            // Calculate angles in local space
                            float xAngle = (x / m_this.m_density) * m_this.m_emissionAreaDimensions.x;
                            float yAngle = (y / m_this.m_density) * m_this.m_emissionAreaDimensions.y;
                            // Define standard target in local space
                            XMVECTOR particleVelocityVec = XMLoadFloat3(&XMFLOAT3(0, 0, 1));
                            XMMATRIX rotMatLocal = XMMatrixRotationRollPitchYaw(xAngle, yAngle, 0);
                            particleVelocityVec = XMVector3Transform(particleVelocityVec, rotMatLocal);
                            // Move velocity vector into world space
                            XMMATRIX rotMatWorld = XMMatrixRotationQuaternion(XMLoadFloat4(&m_this.m_direction));
                            particleVelocityVec = XMVector3Transform(particleVelocityVec, rotMatWorld);
                            // Multiply with pressure
                            particleVelocityVec *= m_this.m_launchPressure;
                            // Store in vector
                            XMFLOAT3 velocity;
                            XMStoreFloat3(&velocity, particleVelocityVec);
                            velocities.push_back(velocity);

                            // Add position (only emitts from the center of the emitter atm
                            float launchOffset = 0.1f;
                            XMVECTOR positionVec = XMLoadFloat3(&m_this.m_position);
                            positionVec += launchOffset * particleVelocityVec;
                            XMFLOAT3 position;
                            XMStoreFloat3(&position, positionVec);

                            positions.push_back(position);

                            // Add index (silly way just to make it work atm)
                            indices.push_back(m_nextIndex);
                            m_nextIndex++;
                        }
                    }

                    if(positions.size() > 0 && !(m_nextIndex > PARTICLE_MAX_COUNT)) // no point doing things if there's no new particles
                    {
                        // Cast into PhysX datatypes
                        PxVec3* positionsPX = reinterpret_cast<PxVec3*>(&positions[0]);
                        PxVec3* velocitiesPX = reinterpret_cast<PxVec3*>(&velocities[0]);
                        PxU32* indicesPX = reinterpret_cast<PxU32*>(&indices[0]);

                        // Create the particles
                        PxParticleCreationData newParticlesData;
                        newParticlesData.numParticles = positions.size();
                        newParticlesData.positionBuffer = PxStrideIterator<const PxVec3>(positionsPX);
                        newParticlesData.velocityBuffer = PxStrideIterator<const PxVec3>(velocitiesPX);
                        newParticlesData.indexBuffer = PxStrideIterator<const PxU32>(indicesPX);
                        m_particleSystem->createParticles(newParticlesData);
                    }
                    else
                    {
                        // No new particles. Do nothing
                    }
                }
            }
        }
    }
}<|endoftext|>