<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#ifndef INCLUDED_FORMS_SOURCE_XFORMS_NAMEDCOLLECTION_HXX
#define INCLUDED_FORMS_SOURCE_XFORMS_NAMEDCOLLECTION_HXX

#include <collection.hxx>
#include <cppuhelper/implbase1.hxx>
#include <com/sun/star/container/XNameAccess.hpp>

#include <algorithm>

template<class T>
class NamedCollection : public cppu::ImplInheritanceHelper1<
                            Collection<T>,
                            com::sun::star::container::XNameAccess>
{
    using Collection<T>::maItems;
    using Collection<T>::getItem;
    using Collection<T>::hasItem;

public:
    NamedCollection() {}
    virtual ~NamedCollection() {}

    const T& getItem( const OUString& rName ) const
    {
        OSL_ENSURE( hasItem( rName ), "invalid name" );
        return *findItem( rName );
    }

    bool hasItem( const OUString& rName ) const
    {
        return findItem( rName ) != maItems.end();
    }

    typedef com::sun::star::uno::Sequence<OUString> Names_t;
    Names_t getNames() const
    {
        // iterate over members, and collect all those that have names
        std::vector<OUString> aNames;
        for( typename std::vector<T>::const_iterator aIter = maItems.begin();
             aIter != maItems.end();
             ++aIter )
        {
            com::sun::star::uno::Reference<com::sun::star::container::XNamed>
                xNamed( *aIter, com::sun::star::uno::UNO_QUERY );
            if( xNamed.is() )
                aNames.push_back( xNamed->getName() );
        }

        // copy names to Sequence and return
        Names_t aResult( aNames.size() );
        OUString* pStrings = aResult.getArray();
        std::copy( aNames.begin(), aNames.end(), pStrings );

        return aResult;
    }

protected:
    typename std::vector<T>::const_iterator findItem( const OUString& rName ) const
    {
        for( typename std::vector<T>::const_iterator aIter = maItems.begin();
             aIter != maItems.end();
             ++aIter )
        {
            com::sun::star::uno::Reference<com::sun::star::container::XNamed>
                xNamed( *aIter, com::sun::star::uno::UNO_QUERY );
            if( xNamed.is()  &&  xNamed->getName() == rName )
                return aIter;
        }
        return maItems.end();
    }

public:

    // XElementAccess
    virtual typename Collection<T>::Type_t SAL_CALL getElementType()
        throw( typename Collection<T>::RuntimeException_t )
    {
        return Collection<T>::getElementType();
    }

    virtual sal_Bool SAL_CALL hasElements()
        throw( typename Collection<T>::RuntimeException_t )
    {
        return Collection<T>::hasElements();
    }

    // XNameAccess : XElementAccess
    virtual typename Collection<T>::Any_t SAL_CALL getByName(
        const OUString& aName )
        throw( typename Collection<T>::NoSuchElementException_t,
               typename Collection<T>::WrappedTargetException_t,
               typename Collection<T>::RuntimeException_t )
    {
        if( hasItem( aName ) )
            return com::sun::star::uno::makeAny( getItem( aName ) );
        else
            throw typename Collection<T>::NoSuchElementException_t();

    }

    virtual Names_t SAL_CALL getElementNames()
        throw( typename Collection<T>::RuntimeException_t )
    {
        return getNames();
    }

    virtual sal_Bool SAL_CALL hasByName(
        const OUString& aName )
        throw( typename Collection<T>::RuntimeException_t )
    {
        return hasItem( aName ) ? sal_True : sal_False;
    }
};

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Mark template member fns that are supposed to override as SAL_OVERRIDE<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#ifndef INCLUDED_FORMS_SOURCE_XFORMS_NAMEDCOLLECTION_HXX
#define INCLUDED_FORMS_SOURCE_XFORMS_NAMEDCOLLECTION_HXX

#include <collection.hxx>
#include <cppuhelper/implbase1.hxx>
#include <com/sun/star/container/XNameAccess.hpp>

#include <algorithm>

template<class T>
class NamedCollection : public cppu::ImplInheritanceHelper1<
                            Collection<T>,
                            com::sun::star::container::XNameAccess>
{
    using Collection<T>::maItems;
    using Collection<T>::getItem;
    using Collection<T>::hasItem;

public:
    NamedCollection() {}
    virtual ~NamedCollection() {}

    const T& getItem( const OUString& rName ) const
    {
        OSL_ENSURE( hasItem( rName ), "invalid name" );
        return *findItem( rName );
    }

    bool hasItem( const OUString& rName ) const
    {
        return findItem( rName ) != maItems.end();
    }

    typedef com::sun::star::uno::Sequence<OUString> Names_t;
    Names_t getNames() const
    {
        // iterate over members, and collect all those that have names
        std::vector<OUString> aNames;
        for( typename std::vector<T>::const_iterator aIter = maItems.begin();
             aIter != maItems.end();
             ++aIter )
        {
            com::sun::star::uno::Reference<com::sun::star::container::XNamed>
                xNamed( *aIter, com::sun::star::uno::UNO_QUERY );
            if( xNamed.is() )
                aNames.push_back( xNamed->getName() );
        }

        // copy names to Sequence and return
        Names_t aResult( aNames.size() );
        OUString* pStrings = aResult.getArray();
        std::copy( aNames.begin(), aNames.end(), pStrings );

        return aResult;
    }

protected:
    typename std::vector<T>::const_iterator findItem( const OUString& rName ) const
    {
        for( typename std::vector<T>::const_iterator aIter = maItems.begin();
             aIter != maItems.end();
             ++aIter )
        {
            com::sun::star::uno::Reference<com::sun::star::container::XNamed>
                xNamed( *aIter, com::sun::star::uno::UNO_QUERY );
            if( xNamed.is()  &&  xNamed->getName() == rName )
                return aIter;
        }
        return maItems.end();
    }

public:

    // XElementAccess
    virtual typename Collection<T>::Type_t SAL_CALL getElementType()
        throw( typename Collection<T>::RuntimeException_t ) SAL_OVERRIDE
    {
        return Collection<T>::getElementType();
    }

    virtual sal_Bool SAL_CALL hasElements()
        throw( typename Collection<T>::RuntimeException_t ) SAL_OVERRIDE
    {
        return Collection<T>::hasElements();
    }

    // XNameAccess : XElementAccess
    virtual typename Collection<T>::Any_t SAL_CALL getByName(
        const OUString& aName )
        throw( typename Collection<T>::NoSuchElementException_t,
               typename Collection<T>::WrappedTargetException_t,
               typename Collection<T>::RuntimeException_t ) SAL_OVERRIDE
    {
        if( hasItem( aName ) )
            return com::sun::star::uno::makeAny( getItem( aName ) );
        else
            throw typename Collection<T>::NoSuchElementException_t();

    }

    virtual Names_t SAL_CALL getElementNames()
        throw( typename Collection<T>::RuntimeException_t ) SAL_OVERRIDE
    {
        return getNames();
    }

    virtual sal_Bool SAL_CALL hasByName(
        const OUString& aName )
        throw( typename Collection<T>::RuntimeException_t ) SAL_OVERRIDE
    {
        return hasItem( aName ) ? sal_True : sal_False;
    }
};

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#include "Sky.hpp"
#include "Game.hpp"

static const float g_basicQuad[] = {
     20.f,  20.f, 0.0f,   1.0f, 1.0f,
     20.f, -20.f, 0.0f,   1.0f, 0.0f,
    -20.f, -20.f, 0.0f,   0.0f, 0.0f,
    -20.f,  20.f, 0.0f,   0.0f, 1.0f
};

GLushort g_basicQuadIndices[] = {
    0, 1, 3,
    1, 2, 3
};

SkyManager::SkyManager() {
    glGenBuffers(1, &m_quadVbo);
    glBindBuffer(GL_ARRAY_BUFFER, m_quadVbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(g_basicQuad), g_basicQuad, GL_STATIC_DRAW);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glGenBuffers(1, &m_quadEbo);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_quadEbo);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(g_basicQuadIndices), g_basicQuadIndices, GL_STATIC_DRAW);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}

void SkyManager::Update(const glm::vec3 & cameraPos, const glm::vec3 & viewDir) {
    m_sunPos = cameraPos - glm::vec3{0, 0, 400};
    m_sunPos.y = 160;
    m_sunVisible = IntersectsFrustum(m_sunPos, cameraPos, viewDir);
}

void SkyManager::Display(const GLuint) {
    if (m_sunVisible) {
	const GLuint textrdQuadProg =
	    GetGame().GetAssets().GetShaderProgram(ShaderProgramId::GenericTextured);
	glUseProgram(textrdQuadProg);
	glActiveTexture(GL_TEXTURE1);
	glUniform1i(glGetUniformLocation(textrdQuadProg, "tex"), 1);
	glBindTexture(GL_TEXTURE_2D, GetGame().GetAssets().GetTexture(TextureId::Sun)->GetId());
	const GLint modelLoc = glGetUniformLocation(textrdQuadProg, "model");
	GLint posAttrib = glGetAttribLocation(textrdQuadProg, "position");
	GLint texAttrib = glGetAttribLocation(textrdQuadProg, "texCoord");
	glm::mat4 model;
	model = glm::translate(model, m_sunPos);
	glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
	glBindBuffer(GL_ARRAY_BUFFER, m_quadVbo);
	glVertexAttribPointer(posAttrib, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), 0);
	glVertexAttribPointer(texAttrib, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void *)(3 * sizeof(float)));
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_quadEbo);
	glBlendFunc(GL_ONE, GL_ONE);
	glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0);
	glBlendFunc(GL_ONE, GL_ZERO);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glBindTexture(GL_TEXTURE_2D, 0);
    }
}
<commit_msg>Increased sun elevation<commit_after>#include "Sky.hpp"
#include "Game.hpp"

static const float g_basicQuad[] = {
     20.f,  20.f, 0.0f,   1.0f, 1.0f,
     20.f, -20.f, 0.0f,   1.0f, 0.0f,
    -20.f, -20.f, 0.0f,   0.0f, 0.0f,
    -20.f,  20.f, 0.0f,   0.0f, 1.0f
};

GLushort g_basicQuadIndices[] = {
    0, 1, 3,
    1, 2, 3
};

SkyManager::SkyManager() {
    glGenBuffers(1, &m_quadVbo);
    glBindBuffer(GL_ARRAY_BUFFER, m_quadVbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(g_basicQuad), g_basicQuad, GL_STATIC_DRAW);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glGenBuffers(1, &m_quadEbo);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_quadEbo);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(g_basicQuadIndices), g_basicQuadIndices, GL_STATIC_DRAW);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}

void SkyManager::Update(const glm::vec3 & cameraPos, const glm::vec3 & viewDir) {
    m_sunPos = cameraPos - glm::vec3{0, 0, 400};
    m_sunPos.y = 180;
    m_sunVisible = IntersectsFrustum(m_sunPos, cameraPos, viewDir);
}

void SkyManager::Display(const GLuint) {
    if (m_sunVisible) {
	const GLuint textrdQuadProg =
	    GetGame().GetAssets().GetShaderProgram(ShaderProgramId::GenericTextured);
	glUseProgram(textrdQuadProg);
	glActiveTexture(GL_TEXTURE1);
	glUniform1i(glGetUniformLocation(textrdQuadProg, "tex"), 1);
	glBindTexture(GL_TEXTURE_2D, GetGame().GetAssets().GetTexture(TextureId::Sun)->GetId());
	const GLint modelLoc = glGetUniformLocation(textrdQuadProg, "model");
	GLint posAttrib = glGetAttribLocation(textrdQuadProg, "position");
	GLint texAttrib = glGetAttribLocation(textrdQuadProg, "texCoord");
	glm::mat4 model;
	model = glm::translate(model, m_sunPos);
	glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
	glBindBuffer(GL_ARRAY_BUFFER, m_quadVbo);
	glVertexAttribPointer(posAttrib, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), 0);
	glVertexAttribPointer(texAttrib, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void *)(3 * sizeof(float)));
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_quadEbo);
	glBlendFunc(GL_ONE, GL_ONE);
	glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0);
	glBlendFunc(GL_ONE, GL_ZERO);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glBindTexture(GL_TEXTURE_2D, 0);
    }
}
<|endoftext|>


<commit_before>/****************************************************************************
 *
 *   Copyright (C) 2013 PX4 Development Team. All rights reserved.
 *   Author: Pavel Kirienko <pavel.kirienko@gmail.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 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 <ch.h>
#include <hal.h>
#include <assert.h>
#include <errno.h>
#include <math.h>
#include <unistd.h>
#include <config/config.h>
#include <sys.h>
#include <led.h>
#include <console.h>
#include <watchdog.h>
#include <pwm_input.h>
#include <motor/motor.h>
#include <uavcan_node/uavcan_node.hpp>

namespace
{

int init()
{
	int res = 0;

	/*
	 * Indication
	 */
	led_init();
	led_set_rgb(0.05, 0.05, 0.05);

	/*
	 * Config
	 */
	res = config_init();
	if (res) {
		return res;
	}

	/*
	 * Safety
	 */
	watchdog_init();

	/*
	 * Motor control (must be initialized earlier than communicaton interfaces)
	 */
	res = motor_init();
	if (res) {
		return res;
	}

	/*
	 * PWM input
	 */
	pwm_input_init();

	/*
	 * UAVCAN node
	 */
	res = uavcan_node::init();
	if (res) {
		return res;
	}

	/*
	 * Self test
	 */
	res = motor_test_hardware();
	if (res) {
		return res;
	}
	lowsyslog("Power stage OK\n");

	if (motor_test_motor()) {
		lowsyslog("Motor is not connected or damaged\n");
	} else {
		lowsyslog("Motor OK\n");
	}
	return 0;
}

__attribute__((noreturn))
void die(int status)
{
	::usleep(100000);
	lowsyslog("Init failed (%i)\n", status);
	// Really there is nothing left to do; just sit there and beep sadly:
	while (1) {
		motor_beep(100, 400);
		uavcan_node::set_node_status_critical();
		led_set_rgb(1, 0, 0);
		sleep(3);
	}
}

void do_startup_beep()
{
	motor_beep(1000, 100);
	::usleep(200 * 1000);
	motor_beep(1000, 100);
}

void print_banner()
{
	lowsyslog("\n\n\n");
	lowsyslog("\x1b\x5b\x48");      // Home sweet home
	lowsyslog("\x1b\x5b\x32\x4a");  // Clear
	lowsyslog("PX4ESC\n");
	lowsyslog("Git commit hash 0x%08x\n", GIT_HASH);
}

}

void application_halt_hook(void)
{
	motor_emergency();
	led_set_rgb(1, 0, 0);
}

int main()
{
	halInit();
	chSysInit();
	sdStart(&STDOUT_SD, NULL);

	usleep(300000);
	print_banner();

	const int init_status = init();

	const int watchdog_id = watchdog_create(10000);

	console_init();

	if (init_status) {
		die(init_status);
	}

	do_startup_beep();

	motor_confirm_initialization();

	chThdSetPriority(LOWPRIO);

	uavcan_node::set_node_status_ok();

	/*
	 * Here we run some high-level self diagnostics
	 */
	while (1) {
		watchdog_reset(watchdog_id);

		if (motor_is_blocked()) {
			uavcan_node::set_node_status_critical();
		} else {
			uavcan_node::set_node_status_ok();
		}
		::usleep(100 * 1000);
	}

	return 0;
}
<commit_msg>Startup CLI print fix<commit_after>/****************************************************************************
 *
 *   Copyright (C) 2013 PX4 Development Team. All rights reserved.
 *   Author: Pavel Kirienko <pavel.kirienko@gmail.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 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 <ch.h>
#include <hal.h>
#include <assert.h>
#include <errno.h>
#include <math.h>
#include <unistd.h>
#include <config/config.h>
#include <sys.h>
#include <led.h>
#include <console.h>
#include <watchdog.h>
#include <pwm_input.h>
#include <motor/motor.h>
#include <uavcan_node/uavcan_node.hpp>

namespace
{

int init()
{
	int res = 0;

	/*
	 * Indication
	 */
	led_init();
	led_set_rgb(0.05, 0.05, 0.05);

	/*
	 * Config
	 */
	res = config_init();
	if (res) {
		return res;
	}

	/*
	 * Safety
	 */
	watchdog_init();

	/*
	 * Motor control (must be initialized earlier than communicaton interfaces)
	 */
	res = motor_init();
	if (res) {
		return res;
	}

	/*
	 * PWM input
	 */
	pwm_input_init();

	/*
	 * UAVCAN node
	 */
	res = uavcan_node::init();
	if (res) {
		return res;
	}

	/*
	 * Self test
	 */
	res = motor_test_hardware();
	if (res) {
		return res;
	}
	lowsyslog("Hardware OK\n");

	if (motor_test_motor()) {
		lowsyslog("Motor is not connected or damaged\n");
	} else {
		lowsyslog("Motor OK\n");
	}
	return 0;
}

__attribute__((noreturn))
void die(int status)
{
	::usleep(100000);
	lowsyslog("Init failed (%i)\n", status);
	// Really there is nothing left to do; just sit there and beep sadly:
	while (1) {
		motor_beep(100, 400);
		uavcan_node::set_node_status_critical();
		led_set_rgb(1, 0, 0);
		sleep(3);
	}
}

void do_startup_beep()
{
	motor_beep(1000, 100);
	::usleep(200 * 1000);
	motor_beep(1000, 100);
}

void print_banner()
{
	lowsyslog("\n\n\n");
	lowsyslog("\x1b\x5b\x48");      // Home sweet home
	lowsyslog("\x1b\x5b\x32\x4a");  // Clear
	lowsyslog("PX4ESC\n");
	lowsyslog("Git commit hash 0x%08x\n", GIT_HASH);
}

}

void application_halt_hook(void)
{
	motor_emergency();
	led_set_rgb(1, 0, 0);
}

int main()
{
	halInit();
	chSysInit();
	sdStart(&STDOUT_SD, NULL);

	usleep(300000);
	print_banner();

	const int init_status = init();

	const int watchdog_id = watchdog_create(10000);

	console_init();

	if (init_status) {
		die(init_status);
	}

	do_startup_beep();

	motor_confirm_initialization();

	chThdSetPriority(LOWPRIO);

	uavcan_node::set_node_status_ok();

	/*
	 * Here we run some high-level self diagnostics
	 */
	while (1) {
		watchdog_reset(watchdog_id);

		if (motor_is_blocked()) {
			uavcan_node::set_node_status_critical();
		} else {
			uavcan_node::set_node_status_ok();
		}
		::usleep(100 * 1000);
	}

	return 0;
}
<|endoftext|>


<commit_before>//! \file
/*
**  Copyright (C) - Triton
**
**  This program is under the terms of the BSD License.
*/

#include <triton/ast.hpp>
#include <triton/astRepresentation.hpp>
#include <triton/exceptions.hpp>
#include <triton/solverEngine.hpp>
#include <triton/tritonToZ3Ast.hpp>

/*! \page solver_interface_page SMT Solver Interface
    \brief [**internal**] All information about the SMT solver interface.

\tableofcontents

\section solver_interface_description Description

The solver engine is the interface between an SMT solver and **Triton** itself. All requests are sent to the SMT solver
as Triton AST (See: \ref py_AstContext_page). The AST representation as string looks like a manually crafted SMT2-LIB script.

Example:

~~~~~~~~~~~~~
; Declaration of the theory
(set-logic QF_AUFBV)

; Utility function
(define-fun parity ((x!1 (_ BitVec 8))) (_ BitVec 1)
  ; x ^= x >> 4;
  ; v &= 0xf;
  ; return (0x6996 >> v) & 1;

  ((_ extract 0 0)
    (bvlshr
       (_ bv27030 16)
       ((_ zero_extend 8)
        (bvand
          (bvxor
            x!1
            (bvlshr x!1 (_ bv4 8)))
          (_ bv15 8)))))
)

; Declaration of the free variables
(declare-fun SymVar_0 () (_ BitVec 8))

; Formula
(assert (= (ite ...)))
~~~~~~~~~~~~~

\section solver_interface_examples C++ example

Let assume that the \f$rax\f$'s symbolic expression contains a symbolic variable \f$x_0 \in X\f$ which has been instantiated previously. At
this program point, we want that \f$rax = 0\f$. We first get the symbolic expression id corresponding to the \f$rax\f$ register, then, its AST.
When the AST has been got, we are able to build our constraint such that \f$ AST_{constraint} = assert(AST_{rax} == 0) \f$.

The solver interface triton::API::getModel() gets as parameter a triton::ast::AbstractNode which corresponds to the \f$ AST_{constraint} \f$ and
returns a list of triton::engines::solver::SolverModel. Each model for a symbolic variable \f$x \in X\f$ is represented by a triton::engines::solver::SolverModel.
For example, if there are two symbolic variables in your constraint, the triton::API::getModel() function will return a list of two items.

~~~~~~~~~~~~~{cpp}
// Get the symbolic id of RAX
auto raxSymId = api.getSymbolicRegisterId(TRITON_X86_REG_RAX);

// Get the full AST of RAX
auto raxFullAst = api.getFullAstFromId(raxSymId);

// Modify the AST of RAX to build the constraint
auto constraint = triton::ast::equal(raxFullAst, triton::ast::bv(0, raxFullAst->getBitvectorSize()));

// Ask a model
auto model = api.getModel(constraint);

// Display all symbolic variable value contained in the model
std::cout << "Model:" << std::endl;
for (auto it = model.begin(); it != model.end(); it++) {
  std::cout << "  - Variable: " << it->getName() << std::endl;
  std::cout << "  - Value   : " << std::hex << it->getValue() << std::endl;
}
~~~~~~~~~~~~~

*/

namespace triton {
  namespace engines {
    namespace solver {

      //! Wrapper to handle variadict number of arguments or'd togethers
      // FIXME : It is already implemented in the new Z3 interface.
      z3::expr mk_or(z3::expr_vector args) {
        std::vector<Z3_ast> array;

        for (triton::uint32 i = 0; i < args.size(); i++)
          array.push_back(args[i]);

        return to_expr(args.ctx(), Z3_mk_or(args.ctx(), static_cast<triton::uint32>(array.size()), &(array[0])));
      }

      SolverEngine::SolverEngine(triton::engines::symbolic::SymbolicEngine* symbolicEngine) {
        if (symbolicEngine == nullptr)
          throw triton::exceptions::SolverEngine("SolverEngine::SolverEngine(): The symbolicEngine API cannot be null.");
        this->symbolicEngine = symbolicEngine;
      }

      std::list<std::map<triton::uint32, SolverModel>> SolverEngine::getModels(triton::ast::AbstractNode* node, triton::uint32 limit) const {
        std::list<std::map<triton::uint32, SolverModel>> ret;
        triton::ast::TritonToZ3Ast z3Ast{this->symbolicEngine, false};

        z3::expr      expr = z3Ast.convert(node);
        z3::context&  ctx  = expr.ctx();
        z3::solver    solver(ctx);

        if (node == nullptr)
          throw triton::exceptions::SolverEngine("SolverEngine::getModels(): node cannot be null.");

        /* Create a solver and add the expression */
        solver.add(expr);

        /* Check if it is sat */
        while (solver.check() == z3::sat && limit >= 1) {

          /* Get model */
          z3::model m = solver.get_model();

          /* Traversing the model */
          std::map<triton::uint32, SolverModel> smodel;
          z3::expr_vector args(ctx);
          for (triton::uint32 i = 0; i < m.size(); i++) {

            /* Get the z3 variable */
            z3::func_decl z3Variable = m[i];

            /* Get the name as std::string from a z3 variable */
            std::string varName = z3Variable.name().str();

            /* Get z3 expr */
            z3::expr exp = m.get_const_interp(z3Variable);

            /* Get the size of a z3 expr */
            triton::uint32 bvSize = exp.get_sort().bv_size();

            /* Get the value of a z3 expr */
            std::string svalue = Z3_get_numeral_string(ctx, exp);

            /* Convert a string value to a integer value */
            triton::uint512 value = triton::uint512(svalue);

            /* Create a triton model */
            SolverModel trionModel = SolverModel(varName, value);

            /* Map the result */
            smodel[trionModel.getId()] = trionModel;

            /* Uniq result */
            if (exp.get_sort().is_bv())
              args.push_back(ctx.bv_const(varName.c_str(), bvSize) != ctx.bv_val(svalue.c_str(), bvSize));

          }

          /* Escape last models */
          solver.add(triton::engines::solver::mk_or(args));

          /* If there is model available */
          if (smodel.size() > 0)
            ret.push_back(smodel);

          /* Decrement the limit */
          limit--;
        }

        return ret;
      }

      std::map<triton::uint32, SolverModel> SolverEngine::getModel(triton::ast::AbstractNode* node) const {
        std::map<triton::uint32, SolverModel> ret;
        std::list<std::map<triton::uint32, SolverModel>> allModels;

        allModels = this->getModels(node, 1);
        if (allModels.size() > 0)
          ret = allModels.front();

        return ret;
      }

    };
  };
};
<commit_msg>Fix #600: Exception when using getModel on a non logical node<commit_after>//! \file
/*
**  Copyright (C) - Triton
**
**  This program is under the terms of the BSD License.
*/

#include <triton/ast.hpp>
#include <triton/astRepresentation.hpp>
#include <triton/exceptions.hpp>
#include <triton/solverEngine.hpp>
#include <triton/tritonToZ3Ast.hpp>

/*! \page solver_interface_page SMT Solver Interface
    \brief [**internal**] All information about the SMT solver interface.

\tableofcontents

\section solver_interface_description Description

The solver engine is the interface between an SMT solver and **Triton** itself. All requests are sent to the SMT solver
as Triton AST (See: \ref py_AstContext_page). The AST representation as string looks like a manually crafted SMT2-LIB script.

Example:

~~~~~~~~~~~~~
; Declaration of the theory
(set-logic QF_AUFBV)

; Utility function
(define-fun parity ((x!1 (_ BitVec 8))) (_ BitVec 1)
  ; x ^= x >> 4;
  ; v &= 0xf;
  ; return (0x6996 >> v) & 1;

  ((_ extract 0 0)
    (bvlshr
       (_ bv27030 16)
       ((_ zero_extend 8)
        (bvand
          (bvxor
            x!1
            (bvlshr x!1 (_ bv4 8)))
          (_ bv15 8)))))
)

; Declaration of the free variables
(declare-fun SymVar_0 () (_ BitVec 8))

; Formula
(assert (= (ite ...)))
~~~~~~~~~~~~~

\section solver_interface_examples C++ example

Let assume that the \f$rax\f$'s symbolic expression contains a symbolic variable \f$x_0 \in X\f$ which has been instantiated previously. At
this program point, we want that \f$rax = 0\f$. We first get the symbolic expression id corresponding to the \f$rax\f$ register, then, its AST.
When the AST has been got, we are able to build our constraint such that \f$ AST_{constraint} = assert(AST_{rax} == 0) \f$.

The solver interface triton::API::getModel() gets as parameter a triton::ast::AbstractNode which corresponds to the \f$ AST_{constraint} \f$ and
returns a list of triton::engines::solver::SolverModel. Each model for a symbolic variable \f$x \in X\f$ is represented by a triton::engines::solver::SolverModel.
For example, if there are two symbolic variables in your constraint, the triton::API::getModel() function will return a list of two items.

~~~~~~~~~~~~~{cpp}
// Get the symbolic id of RAX
auto raxSymId = api.getSymbolicRegisterId(TRITON_X86_REG_RAX);

// Get the full AST of RAX
auto raxFullAst = api.getFullAstFromId(raxSymId);

// Modify the AST of RAX to build the constraint
auto constraint = triton::ast::equal(raxFullAst, triton::ast::bv(0, raxFullAst->getBitvectorSize()));

// Ask a model
auto model = api.getModel(constraint);

// Display all symbolic variable value contained in the model
std::cout << "Model:" << std::endl;
for (auto it = model.begin(); it != model.end(); it++) {
  std::cout << "  - Variable: " << it->getName() << std::endl;
  std::cout << "  - Value   : " << std::hex << it->getValue() << std::endl;
}
~~~~~~~~~~~~~

*/

namespace triton {
  namespace engines {
    namespace solver {

      //! Wrapper to handle variadict number of arguments or'd togethers
      // FIXME : It is already implemented in the new Z3 interface.
      z3::expr mk_or(z3::expr_vector args) {
        std::vector<Z3_ast> array;

        for (triton::uint32 i = 0; i < args.size(); i++)
          array.push_back(args[i]);

        return to_expr(args.ctx(), Z3_mk_or(args.ctx(), static_cast<triton::uint32>(array.size()), &(array[0])));
      }

      SolverEngine::SolverEngine(triton::engines::symbolic::SymbolicEngine* symbolicEngine) {
        if (symbolicEngine == nullptr)
          throw triton::exceptions::SolverEngine("SolverEngine::SolverEngine(): The symbolicEngine API cannot be null.");
        this->symbolicEngine = symbolicEngine;
      }

      std::list<std::map<triton::uint32, SolverModel>> SolverEngine::getModels(triton::ast::AbstractNode* node, triton::uint32 limit) const {
        std::list<std::map<triton::uint32, SolverModel>> ret;
        triton::ast::TritonToZ3Ast z3Ast{this->symbolicEngine, false};

        z3::expr      expr = z3Ast.convert(node);
        z3::context&  ctx  = expr.ctx();
        z3::solver    solver(ctx);

        if (node == nullptr)
          throw triton::exceptions::SolverEngine("SolverEngine::getModels(): node cannot be null.");

        if (node->isLogical() == false)
          throw triton::exceptions::SolverEngine("SolverEngine::getModels(): Must be a logical node.");

        /* Create a solver and add the expression */
        solver.add(expr);

        /* Check if it is sat */
        while (solver.check() == z3::sat && limit >= 1) {

          /* Get model */
          z3::model m = solver.get_model();

          /* Traversing the model */
          std::map<triton::uint32, SolverModel> smodel;
          z3::expr_vector args(ctx);
          for (triton::uint32 i = 0; i < m.size(); i++) {

            /* Get the z3 variable */
            z3::func_decl z3Variable = m[i];

            /* Get the name as std::string from a z3 variable */
            std::string varName = z3Variable.name().str();

            /* Get z3 expr */
            z3::expr exp = m.get_const_interp(z3Variable);

            /* Get the size of a z3 expr */
            triton::uint32 bvSize = exp.get_sort().bv_size();

            /* Get the value of a z3 expr */
            std::string svalue = Z3_get_numeral_string(ctx, exp);

            /* Convert a string value to a integer value */
            triton::uint512 value = triton::uint512(svalue);

            /* Create a triton model */
            SolverModel trionModel = SolverModel(varName, value);

            /* Map the result */
            smodel[trionModel.getId()] = trionModel;

            /* Uniq result */
            if (exp.get_sort().is_bv())
              args.push_back(ctx.bv_const(varName.c_str(), bvSize) != ctx.bv_val(svalue.c_str(), bvSize));

          }

          /* Escape last models */
          solver.add(triton::engines::solver::mk_or(args));

          /* If there is model available */
          if (smodel.size() > 0)
            ret.push_back(smodel);

          /* Decrement the limit */
          limit--;
        }

        return ret;
      }

      std::map<triton::uint32, SolverModel> SolverEngine::getModel(triton::ast::AbstractNode* node) const {
        std::map<triton::uint32, SolverModel> ret;
        std::list<std::map<triton::uint32, SolverModel>> allModels;

        allModels = this->getModels(node, 1);
        if (allModels.size() > 0)
          ret = allModels.front();

        return ret;
      }

    };
  };
};
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: xsecsign.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-03-29 13:22:58 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <xsecctl.hxx>

#ifndef _TOOLS_DEBUG_HXX //autogen wg. DBG_ASSERT
#include <tools/debug.hxx>
#endif

#include <com/sun/star/xml/crypto/sax/XKeyCollector.hpp>
#include <com/sun/star/xml/crypto/sax/ElementMarkPriority.hpp>
#include <com/sun/star/xml/crypto/sax/XReferenceResolvedBroadcaster.hpp>
#include <com/sun/star/xml/crypto/sax/XBlockerMonitor.hpp>
#include <com/sun/star/xml/crypto/sax/XReferenceCollector.hpp>
#include <com/sun/star/xml/crypto/sax/XSignatureCreationResultBroadcaster.hpp>
#include <com/sun/star/io/XActiveDataSource.hpp>

#ifndef _RTL_UUID_H_
#include <rtl/uuid.h>
#endif

#include <stdio.h>

namespace cssu = com::sun::star::uno;
namespace cssl = com::sun::star::lang;
namespace cssxc = com::sun::star::xml::crypto;
namespace cssxs = com::sun::star::xml::sax;

/* xml security framework components */
#define SIGNATURECREATOR_COMPONENT "com.sun.star.xml.crypto.sax.SignatureCreator"

/* protected: for signature generation */
rtl::OUString XSecController::createId()
{
    cssu::Sequence< sal_Int8 > aSeq( 16 );
    rtl_createUuid ((sal_uInt8 *)aSeq.getArray(), 0, sal_True);

    char str[68]="ID_";
    int length = 3;
    for (int i=0; i<16; ++i)
    {
        length += sprintf(str+length, "%04x", (unsigned char)aSeq[i]);
    }

    return rtl::OUString::createFromAscii(str);
}

cssu::Reference< cssxc::sax::XReferenceResolvedListener > XSecController::prepareSignatureToWrite(
    InternalSignatureInformation& internalSignatureInfor )
{
    sal_Int32 nSecurityId = internalSignatureInfor.signatureInfor.nSecurityId;
    SignatureReferenceInformations& vReferenceInfors = internalSignatureInfor.signatureInfor.vSignatureReferenceInfors;

    sal_Int32 nIdOfSignatureElementCollector;
    cssu::Reference< cssxc::sax::XReferenceResolvedListener > xReferenceResolvedListener;

    nIdOfSignatureElementCollector =
        m_xSAXEventKeeper->addSecurityElementCollector( cssxc::sax::ElementMarkPriority_AFTERMODIFY, sal_True );

    m_xSAXEventKeeper->setSecurityId(nIdOfSignatureElementCollector, nSecurityId);

        /*
         * create a SignatureCreator
         */
    xReferenceResolvedListener = cssu::Reference< cssxc::sax::XReferenceResolvedListener >(
        mxMSF->createInstance(
            rtl::OUString::createFromAscii(SIGNATURECREATOR_COMPONENT)),
        cssu::UNO_QUERY);

    cssu::Reference<cssl::XInitialization> xInitialization(xReferenceResolvedListener, cssu::UNO_QUERY);

    cssu::Sequence<cssu::Any> args(5);
    args[0] = cssu::makeAny(rtl::OUString::valueOf(nSecurityId));
    args[1] = cssu::makeAny(m_xSAXEventKeeper);
    args[2] = cssu::makeAny(rtl::OUString::valueOf(nIdOfSignatureElementCollector));

    //i39448 : for nss, the internal module is used for signing, which needs to be improved later
    sal_Int32 nEnvIndex = internalSignatureInfor.signatureInfor.nSecurityEnvironmentIndex;
    if( nEnvIndex < 0 || nEnvIndex >= m_xSecurityContext->getSecurityEnvironmentNumber())
    {// set defaultEnv
        args[3] = cssu::makeAny(m_xSecurityContext->getSecurityEnvironment());
    }
    else
    {
        args[3] = cssu::makeAny(m_xSecurityContext->getSecurityEnvironmentByIndex(nEnvIndex));
    }

    args[4] = cssu::makeAny(m_xXMLSignature);
    xInitialization->initialize(args);

    sal_Int32 nBlockerId = m_xSAXEventKeeper->addBlocker();
    m_xSAXEventKeeper->setSecurityId(nBlockerId, nSecurityId);

    cssu::Reference<cssxc::sax::XBlockerMonitor> xBlockerMonitor(xReferenceResolvedListener, cssu::UNO_QUERY);
    xBlockerMonitor->setBlockerId(nBlockerId);

    cssu::Reference< cssxc::sax::XSignatureCreationResultBroadcaster >
        xSignatureCreationResultBroadcaster(xReferenceResolvedListener, cssu::UNO_QUERY);

    xSignatureCreationResultBroadcaster->addSignatureCreationResultListener( this );

    cssu::Reference<cssxc::sax::XReferenceResolvedBroadcaster>
        xReferenceResolvedBroadcaster
        (m_xSAXEventKeeper,
        cssu::UNO_QUERY);

    xReferenceResolvedBroadcaster->addReferenceResolvedListener(
        nIdOfSignatureElementCollector,
        xReferenceResolvedListener);

    cssu::Reference<cssxc::sax::XReferenceCollector> xReferenceCollector
        (xReferenceResolvedListener, cssu::UNO_QUERY);

    int i;
    int size = vReferenceInfors.size();
    sal_Int32 nReferenceCount = 0;

    for(i=0; i<size; ++i)
    {
        sal_Int32 keeperId = internalSignatureInfor.vKeeperIds[i];

        if ( keeperId != -1)
        {
            m_xSAXEventKeeper->setSecurityId(keeperId, nSecurityId);
            xReferenceResolvedBroadcaster->addReferenceResolvedListener( keeperId, xReferenceResolvedListener);
            xReferenceCollector->setReferenceId( keeperId );
            nReferenceCount++;
        }
    }

    xReferenceCollector->setReferenceCount( nReferenceCount );

    /*
     * adds all URI binding
     */
    cssu::Reference<cssxc::XUriBinding> xUriBinding
        (xReferenceResolvedListener, cssu::UNO_QUERY);

    for(i=0; i<size; ++i)
    {
        const SignatureReferenceInformation& refInfor = vReferenceInfors[i];

        cssu::Reference< com::sun::star::io::XInputStream > xInputStream
            = getObjectInputStream( refInfor.ouURI );

        if (xInputStream.is())
        {
            xUriBinding->setUriBinding(refInfor.ouURI,xInputStream);
        }
    }

    cssu::Reference<cssxc::sax::XKeyCollector> keyCollector (xReferenceResolvedListener, cssu::UNO_QUERY);
    keyCollector->setKeyId(0);

    internalSignatureInfor.signatureInfor.ouSignatureId = createId();
    internalSignatureInfor.signatureInfor.ouPropertyId = createId();
    internalSignatureInfor.addReference(TYPE_SAMEDOCUMENT_REFERENCE, internalSignatureInfor.signatureInfor.ouPropertyId, -1 );
    size++;

    /*
     * replace both digestValues and signatueValue to " "
     */
    for(i=0; i<size; ++i)
    {
        SignatureReferenceInformation& refInfor = vReferenceInfors[i];
        refInfor.ouDigestValue = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(CHAR_BLANK));
    }

    internalSignatureInfor.signatureInfor.ouSignatureValue = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(CHAR_BLANK));

    return xReferenceResolvedListener;
}

/* public: for signature generation */
void XSecController::collectToSign( sal_Int32 securityId, const rtl::OUString& referenceId )
{
    /* DBG_ASSERT( m_xSAXEventKeeper.is(), "the SAXEventKeeper is NULL" ); */

    chainOn(true);

    if ( m_nStatusOfSecurityComponents == INITIALIZED )
    /*
     * if all security components are ready, add a signature.
     */
    {
        sal_Int32 nKeeperId = m_xSAXEventKeeper->addSecurityElementCollector(
            cssxc::sax::ElementMarkPriority_AFTERMODIFY, sal_False);

        int index = findSignatureInfor( securityId );

        if ( index == -1 )
        {
            InternalSignatureInformation isi(securityId, NULL);
            isi.addReference(TYPE_SAMEDOCUMENT_REFERENCE, referenceId, nKeeperId );
            m_vInternalSignatureInformations.push_back( isi );
        }
        else
        {
            m_vInternalSignatureInformations[index].addReference(TYPE_SAMEDOCUMENT_REFERENCE, referenceId, nKeeperId );
        }
    }
}

void XSecController::signAStream( sal_Int32 securityId, const rtl::OUString& uri, const rtl::OUString& objectURL, sal_Bool isBinary)
{
        sal_Int32 type = ((isBinary==sal_True)?TYPE_BINARYSTREAM_REFERENCE:TYPE_XMLSTREAM_REFERENCE);

    int index = findSignatureInfor( securityId );

    if (index == -1)
    {
        InternalSignatureInformation isi(securityId, NULL);
        isi.addReference(type, uri, -1);
        m_vInternalSignatureInformations.push_back( isi );
    }
    else
    {
        m_vInternalSignatureInformations[index].addReference(type, uri, -1);
    }
}

void XSecController::setX509Certificate(
    sal_Int32 nSecurityId,
    const rtl::OUString& ouX509IssuerName,
    const rtl::OUString& ouX509SerialNumber)
{
    setX509Certificate(nSecurityId, -1, ouX509IssuerName, ouX509SerialNumber);
}

void XSecController::setX509Certificate(
    sal_Int32 nSecurityId,
    const sal_Int32 nSecurityEnvironmentIndex,
    const rtl::OUString& ouX509IssuerName,
    const rtl::OUString& ouX509SerialNumber)
{
    int index = findSignatureInfor( nSecurityId );

    if ( index == -1 )
    {
        InternalSignatureInformation isi(nSecurityId, NULL);
        isi.signatureInfor.nSecurityEnvironmentIndex = nSecurityEnvironmentIndex;
        isi.signatureInfor.ouX509IssuerName = ouX509IssuerName;
        isi.signatureInfor.ouX509SerialNumber = ouX509SerialNumber;
        m_vInternalSignatureInformations.push_back( isi );
    }
    else
    {
        SignatureInformation &si
            = m_vInternalSignatureInformations[index].signatureInfor;
        si.ouX509IssuerName = ouX509IssuerName;
        si.ouX509SerialNumber = ouX509SerialNumber;
        si.nSecurityEnvironmentIndex = nSecurityEnvironmentIndex;
    }
}

void XSecController::setDate(
    sal_Int32 nSecurityId,
    const ::com::sun::star::util::DateTime& rDateTime )
{
    int index = findSignatureInfor( nSecurityId );

    if ( index == -1 )
    {
        InternalSignatureInformation isi(nSecurityId, NULL);
        isi.signatureInfor.stDateTime = rDateTime;
        m_vInternalSignatureInformations.push_back( isi );
    }
    else
    {
        SignatureInformation &si
            = m_vInternalSignatureInformations[index].signatureInfor;
        si.stDateTime = rDateTime;
    }
}

bool XSecController::WriteSignature(
    const cssu::Reference<cssxs::XDocumentHandler>& xDocumentHandler )
{
    bool rc = false;

    DBG_ASSERT( xDocumentHandler.is(), "I really need a document handler!" );

    /*
     * chain the SAXEventKeeper to the SAX chain
     */
    chainOn(true);

    if ( m_nStatusOfSecurityComponents == INITIALIZED )
    /*
     * if all security components are ready, add the signature
     * stream.
     */
    {
        m_bIsSAXEventKeeperSticky = true;
        m_xSAXEventKeeper->setNextHandler(xDocumentHandler);

        try
        {
            /*
             * export the signature template
             */
            cssu::Reference<cssxs::XDocumentHandler> xSEKHandler( m_xSAXEventKeeper,cssu::UNO_QUERY);

            int i;
            int sigNum = m_vInternalSignatureInformations.size();

            for (i=0; i<sigNum; ++i)
            {
                InternalSignatureInformation &isi = m_vInternalSignatureInformations[i];

                /*
                 * prepare the signature creator
                 */
                isi.xReferenceResolvedListener
                    = prepareSignatureToWrite( isi );

                exportSignature( xSEKHandler, isi.signatureInfor );
            }

            m_bIsSAXEventKeeperSticky = false;
            chainOff();

            rc = true;
        }
        catch( cssxs::SAXException& )
        {
            m_pErrorMessage = ERROR_SAXEXCEPTIONDURINGCREATION;
        }
        catch( com::sun::star::io::IOException& )
        {
            m_pErrorMessage = ERROR_IOEXCEPTIONDURINGCREATION;
        }
        catch( cssu::Exception& )
        {
            m_pErrorMessage = ERROR_EXCEPTIONDURINGCREATION;
        }

        m_xSAXEventKeeper->setNextHandler( NULL );
        m_bIsSAXEventKeeperSticky = false;
    }
    else
    {
        m_pErrorMessage = ERROR_CANNOTCREATEXMLSECURITYCOMPONENT;
    }

    return rc;
}

<commit_msg>INTEGRATION: CWS ooo19126 (1.6.48); FILE MERGED 2005/09/05 17:01:51 rt 1.6.48.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xsecsign.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 17:24:01 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <xsecctl.hxx>

#ifndef _TOOLS_DEBUG_HXX //autogen wg. DBG_ASSERT
#include <tools/debug.hxx>
#endif

#include <com/sun/star/xml/crypto/sax/XKeyCollector.hpp>
#include <com/sun/star/xml/crypto/sax/ElementMarkPriority.hpp>
#include <com/sun/star/xml/crypto/sax/XReferenceResolvedBroadcaster.hpp>
#include <com/sun/star/xml/crypto/sax/XBlockerMonitor.hpp>
#include <com/sun/star/xml/crypto/sax/XReferenceCollector.hpp>
#include <com/sun/star/xml/crypto/sax/XSignatureCreationResultBroadcaster.hpp>
#include <com/sun/star/io/XActiveDataSource.hpp>

#ifndef _RTL_UUID_H_
#include <rtl/uuid.h>
#endif

#include <stdio.h>

namespace cssu = com::sun::star::uno;
namespace cssl = com::sun::star::lang;
namespace cssxc = com::sun::star::xml::crypto;
namespace cssxs = com::sun::star::xml::sax;

/* xml security framework components */
#define SIGNATURECREATOR_COMPONENT "com.sun.star.xml.crypto.sax.SignatureCreator"

/* protected: for signature generation */
rtl::OUString XSecController::createId()
{
    cssu::Sequence< sal_Int8 > aSeq( 16 );
    rtl_createUuid ((sal_uInt8 *)aSeq.getArray(), 0, sal_True);

    char str[68]="ID_";
    int length = 3;
    for (int i=0; i<16; ++i)
    {
        length += sprintf(str+length, "%04x", (unsigned char)aSeq[i]);
    }

    return rtl::OUString::createFromAscii(str);
}

cssu::Reference< cssxc::sax::XReferenceResolvedListener > XSecController::prepareSignatureToWrite(
    InternalSignatureInformation& internalSignatureInfor )
{
    sal_Int32 nSecurityId = internalSignatureInfor.signatureInfor.nSecurityId;
    SignatureReferenceInformations& vReferenceInfors = internalSignatureInfor.signatureInfor.vSignatureReferenceInfors;

    sal_Int32 nIdOfSignatureElementCollector;
    cssu::Reference< cssxc::sax::XReferenceResolvedListener > xReferenceResolvedListener;

    nIdOfSignatureElementCollector =
        m_xSAXEventKeeper->addSecurityElementCollector( cssxc::sax::ElementMarkPriority_AFTERMODIFY, sal_True );

    m_xSAXEventKeeper->setSecurityId(nIdOfSignatureElementCollector, nSecurityId);

        /*
         * create a SignatureCreator
         */
    xReferenceResolvedListener = cssu::Reference< cssxc::sax::XReferenceResolvedListener >(
        mxMSF->createInstance(
            rtl::OUString::createFromAscii(SIGNATURECREATOR_COMPONENT)),
        cssu::UNO_QUERY);

    cssu::Reference<cssl::XInitialization> xInitialization(xReferenceResolvedListener, cssu::UNO_QUERY);

    cssu::Sequence<cssu::Any> args(5);
    args[0] = cssu::makeAny(rtl::OUString::valueOf(nSecurityId));
    args[1] = cssu::makeAny(m_xSAXEventKeeper);
    args[2] = cssu::makeAny(rtl::OUString::valueOf(nIdOfSignatureElementCollector));

    //i39448 : for nss, the internal module is used for signing, which needs to be improved later
    sal_Int32 nEnvIndex = internalSignatureInfor.signatureInfor.nSecurityEnvironmentIndex;
    if( nEnvIndex < 0 || nEnvIndex >= m_xSecurityContext->getSecurityEnvironmentNumber())
    {// set defaultEnv
        args[3] = cssu::makeAny(m_xSecurityContext->getSecurityEnvironment());
    }
    else
    {
        args[3] = cssu::makeAny(m_xSecurityContext->getSecurityEnvironmentByIndex(nEnvIndex));
    }

    args[4] = cssu::makeAny(m_xXMLSignature);
    xInitialization->initialize(args);

    sal_Int32 nBlockerId = m_xSAXEventKeeper->addBlocker();
    m_xSAXEventKeeper->setSecurityId(nBlockerId, nSecurityId);

    cssu::Reference<cssxc::sax::XBlockerMonitor> xBlockerMonitor(xReferenceResolvedListener, cssu::UNO_QUERY);
    xBlockerMonitor->setBlockerId(nBlockerId);

    cssu::Reference< cssxc::sax::XSignatureCreationResultBroadcaster >
        xSignatureCreationResultBroadcaster(xReferenceResolvedListener, cssu::UNO_QUERY);

    xSignatureCreationResultBroadcaster->addSignatureCreationResultListener( this );

    cssu::Reference<cssxc::sax::XReferenceResolvedBroadcaster>
        xReferenceResolvedBroadcaster
        (m_xSAXEventKeeper,
        cssu::UNO_QUERY);

    xReferenceResolvedBroadcaster->addReferenceResolvedListener(
        nIdOfSignatureElementCollector,
        xReferenceResolvedListener);

    cssu::Reference<cssxc::sax::XReferenceCollector> xReferenceCollector
        (xReferenceResolvedListener, cssu::UNO_QUERY);

    int i;
    int size = vReferenceInfors.size();
    sal_Int32 nReferenceCount = 0;

    for(i=0; i<size; ++i)
    {
        sal_Int32 keeperId = internalSignatureInfor.vKeeperIds[i];

        if ( keeperId != -1)
        {
            m_xSAXEventKeeper->setSecurityId(keeperId, nSecurityId);
            xReferenceResolvedBroadcaster->addReferenceResolvedListener( keeperId, xReferenceResolvedListener);
            xReferenceCollector->setReferenceId( keeperId );
            nReferenceCount++;
        }
    }

    xReferenceCollector->setReferenceCount( nReferenceCount );

    /*
     * adds all URI binding
     */
    cssu::Reference<cssxc::XUriBinding> xUriBinding
        (xReferenceResolvedListener, cssu::UNO_QUERY);

    for(i=0; i<size; ++i)
    {
        const SignatureReferenceInformation& refInfor = vReferenceInfors[i];

        cssu::Reference< com::sun::star::io::XInputStream > xInputStream
            = getObjectInputStream( refInfor.ouURI );

        if (xInputStream.is())
        {
            xUriBinding->setUriBinding(refInfor.ouURI,xInputStream);
        }
    }

    cssu::Reference<cssxc::sax::XKeyCollector> keyCollector (xReferenceResolvedListener, cssu::UNO_QUERY);
    keyCollector->setKeyId(0);

    internalSignatureInfor.signatureInfor.ouSignatureId = createId();
    internalSignatureInfor.signatureInfor.ouPropertyId = createId();
    internalSignatureInfor.addReference(TYPE_SAMEDOCUMENT_REFERENCE, internalSignatureInfor.signatureInfor.ouPropertyId, -1 );
    size++;

    /*
     * replace both digestValues and signatueValue to " "
     */
    for(i=0; i<size; ++i)
    {
        SignatureReferenceInformation& refInfor = vReferenceInfors[i];
        refInfor.ouDigestValue = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(CHAR_BLANK));
    }

    internalSignatureInfor.signatureInfor.ouSignatureValue = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(CHAR_BLANK));

    return xReferenceResolvedListener;
}

/* public: for signature generation */
void XSecController::collectToSign( sal_Int32 securityId, const rtl::OUString& referenceId )
{
    /* DBG_ASSERT( m_xSAXEventKeeper.is(), "the SAXEventKeeper is NULL" ); */

    chainOn(true);

    if ( m_nStatusOfSecurityComponents == INITIALIZED )
    /*
     * if all security components are ready, add a signature.
     */
    {
        sal_Int32 nKeeperId = m_xSAXEventKeeper->addSecurityElementCollector(
            cssxc::sax::ElementMarkPriority_AFTERMODIFY, sal_False);

        int index = findSignatureInfor( securityId );

        if ( index == -1 )
        {
            InternalSignatureInformation isi(securityId, NULL);
            isi.addReference(TYPE_SAMEDOCUMENT_REFERENCE, referenceId, nKeeperId );
            m_vInternalSignatureInformations.push_back( isi );
        }
        else
        {
            m_vInternalSignatureInformations[index].addReference(TYPE_SAMEDOCUMENT_REFERENCE, referenceId, nKeeperId );
        }
    }
}

void XSecController::signAStream( sal_Int32 securityId, const rtl::OUString& uri, const rtl::OUString& objectURL, sal_Bool isBinary)
{
        sal_Int32 type = ((isBinary==sal_True)?TYPE_BINARYSTREAM_REFERENCE:TYPE_XMLSTREAM_REFERENCE);

    int index = findSignatureInfor( securityId );

    if (index == -1)
    {
        InternalSignatureInformation isi(securityId, NULL);
        isi.addReference(type, uri, -1);
        m_vInternalSignatureInformations.push_back( isi );
    }
    else
    {
        m_vInternalSignatureInformations[index].addReference(type, uri, -1);
    }
}

void XSecController::setX509Certificate(
    sal_Int32 nSecurityId,
    const rtl::OUString& ouX509IssuerName,
    const rtl::OUString& ouX509SerialNumber)
{
    setX509Certificate(nSecurityId, -1, ouX509IssuerName, ouX509SerialNumber);
}

void XSecController::setX509Certificate(
    sal_Int32 nSecurityId,
    const sal_Int32 nSecurityEnvironmentIndex,
    const rtl::OUString& ouX509IssuerName,
    const rtl::OUString& ouX509SerialNumber)
{
    int index = findSignatureInfor( nSecurityId );

    if ( index == -1 )
    {
        InternalSignatureInformation isi(nSecurityId, NULL);
        isi.signatureInfor.nSecurityEnvironmentIndex = nSecurityEnvironmentIndex;
        isi.signatureInfor.ouX509IssuerName = ouX509IssuerName;
        isi.signatureInfor.ouX509SerialNumber = ouX509SerialNumber;
        m_vInternalSignatureInformations.push_back( isi );
    }
    else
    {
        SignatureInformation &si
            = m_vInternalSignatureInformations[index].signatureInfor;
        si.ouX509IssuerName = ouX509IssuerName;
        si.ouX509SerialNumber = ouX509SerialNumber;
        si.nSecurityEnvironmentIndex = nSecurityEnvironmentIndex;
    }
}

void XSecController::setDate(
    sal_Int32 nSecurityId,
    const ::com::sun::star::util::DateTime& rDateTime )
{
    int index = findSignatureInfor( nSecurityId );

    if ( index == -1 )
    {
        InternalSignatureInformation isi(nSecurityId, NULL);
        isi.signatureInfor.stDateTime = rDateTime;
        m_vInternalSignatureInformations.push_back( isi );
    }
    else
    {
        SignatureInformation &si
            = m_vInternalSignatureInformations[index].signatureInfor;
        si.stDateTime = rDateTime;
    }
}

bool XSecController::WriteSignature(
    const cssu::Reference<cssxs::XDocumentHandler>& xDocumentHandler )
{
    bool rc = false;

    DBG_ASSERT( xDocumentHandler.is(), "I really need a document handler!" );

    /*
     * chain the SAXEventKeeper to the SAX chain
     */
    chainOn(true);

    if ( m_nStatusOfSecurityComponents == INITIALIZED )
    /*
     * if all security components are ready, add the signature
     * stream.
     */
    {
        m_bIsSAXEventKeeperSticky = true;
        m_xSAXEventKeeper->setNextHandler(xDocumentHandler);

        try
        {
            /*
             * export the signature template
             */
            cssu::Reference<cssxs::XDocumentHandler> xSEKHandler( m_xSAXEventKeeper,cssu::UNO_QUERY);

            int i;
            int sigNum = m_vInternalSignatureInformations.size();

            for (i=0; i<sigNum; ++i)
            {
                InternalSignatureInformation &isi = m_vInternalSignatureInformations[i];

                /*
                 * prepare the signature creator
                 */
                isi.xReferenceResolvedListener
                    = prepareSignatureToWrite( isi );

                exportSignature( xSEKHandler, isi.signatureInfor );
            }

            m_bIsSAXEventKeeperSticky = false;
            chainOff();

            rc = true;
        }
        catch( cssxs::SAXException& )
        {
            m_pErrorMessage = ERROR_SAXEXCEPTIONDURINGCREATION;
        }
        catch( com::sun::star::io::IOException& )
        {
            m_pErrorMessage = ERROR_IOEXCEPTIONDURINGCREATION;
        }
        catch( cssu::Exception& )
        {
            m_pErrorMessage = ERROR_EXCEPTIONDURINGCREATION;
        }

        m_xSAXEventKeeper->setNextHandler( NULL );
        m_bIsSAXEventKeeperSticky = false;
    }
    else
    {
        m_pErrorMessage = ERROR_CANNOTCREATEXMLSECURITYCOMPONENT;
    }

    return rc;
}

<|endoftext|>


<commit_before>#include "gjk2d.hpp"
#include "g.hpp"
#include "segment2d.hpp"
#include "circle2d.hpp"
#include "aabb2d.hpp"
#include "point2d.hpp"

namespace beat {
	namespace g2 {
		float GetRatio(const Vec2& v0, const Vec2& v1, const Vec2& pos) {
			if(std::abs(v0.x - v1.x) > std::abs(v0.y - v1.y))
				return (pos.x - v0.x) / (v1.x - v0.x);
			return (pos.y - v0.y) / (v1.y - v0.y);
		}

		void GSimplex::_minkowskiSub(const Vec2& dir, const int n) {
			_posA[n] = _m0.im_support(dir);
			_tri.pos[n] = _posA[n] - _m1.im_support(-dir);
		}
		void GSimplex::_setAsHit(const int nv, const Vec2& inner) {
			_nVtx = nv;
			_bHit = true;
			_inner = inner;
		}
		void GSimplex::_setAsNotHit(const int nv) {
			_nVtx = nv;
			_bHit = false;
		}
		GSimplex::GSimplex(const IModel& m0, const IModel& m1):
			_m0(m0),
			_m1(m1)
		{
			_gjkMethod();
		}
		bool GSimplex::getResult() const {
			return _bHit;
		}
		const Vec2& GSimplex::getInner() const {
			return _inner;
		}
		namespace {
			// [中心となる頂点] -> [その前の頂点, 現在の頂点, 次の頂点]
			constexpr int NeighborIndex[3][3] = {
				{2,0,1},
				{0,1,2},
				{1,2,0}
			};
		}
		void GSimplex::_gjkMethod() {
			// とりあえず物体の中心位置でサポートベクトルを決める
			Vec2 dir(_m1.im_getCenter() - _m0.im_getCenter());
			float lens = dir.len_sq();
			if(lens < NEAR_THRESHOLD_SQ)
				dir = Vec2(1,0);
			else
				dir /= std::sqrt(lens);

			_minkowskiSub(dir, 0);
			if(dir.dot(_tri.pos[0]) < 0)
				return _setAsNotHit(1);

			// 原点と重なっていたら終了 = 内部点
			lens = _tri.pos[0].len_sq();
			if(lens < NEAR_THRESHOLD_SQ)
				return _setAsHit(1, _posA[0]);

			dir = _tri.pos[0] / std::sqrt(lens) * -1.f;
			_minkowskiSub(dir, 1);

			// 2つのミンコフスキー頂点から次の方向を決定(Segmentの最短距離)
			{
				Vec2 sdir = _tri.pos[1] - _tri.pos[0];
				const float dirLen = sdir.normalize();
				const float r = sdir.dot(-_tri.pos[0]);
				D_Assert(r >= 0, "expect: r>=0, actual: r=%f", r);
				if(r > dirLen)
					return _setAsNotHit(2);
				if(r >= dirLen-1e-5f) {
					std::swap(_posA[0], _posA[1]);
					std::swap(_tri.pos[0], _tri.pos[1]);
					return _setAsHit(1, _posA[0]);
				}
				Vec2 cp = _tri.pos[0] + sdir*r;
				const float len = cp.normalize();
				if(len < ZEROVEC_LENGTH) {
					// ライン上に原点がある
					// 90度回転
					Vec2 ldir = Vec2{sdir.y, -sdir.x};
					const Vec2 v0 = _m0.im_support(ldir) - _m1.im_support(-ldir);
					// 更に反転(-90)
					ldir *= -1;
					const Vec2 v1 = _m0.im_support(ldir) - _m1.im_support(-ldir);
					if((v1-_tri.pos[0]).cw(v0-_tri.pos[0]) >= 0) {
						const Vec2 pos = _posA[0].l_intp(_posA[1], r / dirLen);
						return _setAsHit(2, pos);
					}
					return _setAsNotHit(2);
				}
				dir = cp;
			}
			// 次に探索する方向
			LNear res(dir, LinePos::OnLine);
			// 今までの最短距離
			constexpr float DistMax = std::numeric_limits<float>::max();
			float minDist = DistMax;
			// 次の探索結果を書き込むインデックス
			int idx = 2;
			for(;;) {
				// 新たな頂点を追加
				dir = res.first.normalization() * -1.f;
				_minkowskiSub(dir, idx);
				if(dir.dot(_tri.pos[idx]) < 0)
					return _setAsNotHit(3);

				// 既存の頂点と同じ座標だったらこれ以上進展はないということで、終了
				const auto& nei = NeighborIndex[idx];
				auto &rV0 = _tri.pos[nei[0]],
						&rV1 = _tri.pos[nei[1]],
						&rV2 = _tri.pos[nei[2]];
				{
					const float d1 = rV1.dot(dir),
							  d0 = rV0.dot(dir),
							  d2 = rV2.dot(dir);
					if(d1-NEAR_THRESHOLD < d0 || d1-NEAR_THRESHOLD < d2)
						return _setAsNotHit(3);
				}

				const Vec2 ori(0);
				// 現時点で三角形が原点を含んでいるか
				{
					bool bIn;
					if(_tri.isClockwise())
						bIn = _tri.hit({0,0});
					else {
						_tri.flip();
						bIn = _tri.hit({0,0});
						_tri.flip();
					}
					if(bIn) {
						// 交差領域の1点を算出
						float cf[3];
						BarycentricCoord(cf, _tri.pos[0], _tri.pos[1], _tri.pos[2], ori);
						const auto v = MixVector(cf, _posA[0], _posA[1], _posA[2]);
						return _setAsHit(3, v);
					}
				}
				float dist = DistMax;
				idx = -1;
				// nei[0], nei[1], dist&, idx&, res&, rV0, rV1 -> bool
				res = Segment(_tri.pos[nei[0]], _tri.pos[nei[1]]).nearest(ori);
				if(res.second == LinePos::OnLine) {
					const float td = res.first.len_sq();
					if(td < 1e-7f) {
						const float r = GetRatio(rV0, rV1, res.first);
						const auto in = _posA[nei[0]]*(1-r) + _posA[nei[1]]*r;
						return _setAsHit(3, in);
					}
					if(dist > td) {
						dist = td;
						// この辺について調べる
						idx = nei[2];
					}
				}
				{
					auto res2 = Segment(_tri.pos[nei[1]], _tri.pos[nei[2]]).nearest(ori);
					if(res2.second == LinePos::OnLine) {
						const float td = res2.first.len_sq();
						if(td < 1e-7f) {
							const float r = GetRatio(rV1, rV2, res.first);
							const auto in = _posA[nei[1]]*(1-r) + _posA[nei[2]]*r;
							return _setAsHit(3, in);
						}
						if(dist > td) {
							dist = td;
							// この辺について調べる
							idx = nei[0];
							res = res2;
						}
					}
				}
				if(dist > minDist)
					return _setAsNotHit(3);
				minDist = dist;
				if(idx < 0)
					return _setAsNotHit(3);
			}
		}
	}
}
<commit_msg>GSimplex: 探索終了条件の調整<commit_after>#include "gjk2d.hpp"
#include "g.hpp"
#include "segment2d.hpp"
#include "circle2d.hpp"
#include "aabb2d.hpp"
#include "point2d.hpp"

namespace beat {
	namespace g2 {
		float GetRatio(const Vec2& v0, const Vec2& v1, const Vec2& pos) {
			if(std::abs(v0.x - v1.x) > std::abs(v0.y - v1.y))
				return (pos.x - v0.x) / (v1.x - v0.x);
			return (pos.y - v0.y) / (v1.y - v0.y);
		}

		void GSimplex::_minkowskiSub(const Vec2& dir, const int n) {
			_posA[n] = _m0.im_support(dir);
			_tri.pos[n] = _posA[n] - _m1.im_support(-dir);
		}
		void GSimplex::_setAsHit(const int nv, const Vec2& inner) {
			_nVtx = nv;
			_bHit = true;
			_inner = inner;
		}
		void GSimplex::_setAsNotHit(const int nv) {
			_nVtx = nv;
			_bHit = false;
		}
		GSimplex::GSimplex(const IModel& m0, const IModel& m1):
			_m0(m0),
			_m1(m1)
		{
			_gjkMethod();
		}
		bool GSimplex::getResult() const {
			return _bHit;
		}
		const Vec2& GSimplex::getInner() const {
			return _inner;
		}
		namespace {
			// [中心となる頂点] -> [その前の頂点, 現在の頂点, 次の頂点]
			constexpr int NeighborIndex[3][3] = {
				{2,0,1},
				{0,1,2},
				{1,2,0}
			};
		}
		void GSimplex::_gjkMethod() {
			// とりあえず物体の中心位置でサポートベクトルを決める
			Vec2 dir(_m1.im_getCenter() - _m0.im_getCenter());
			float lens = dir.len_sq();
			if(lens < NEAR_THRESHOLD_SQ)
				dir = Vec2(1,0);
			else
				dir /= std::sqrt(lens);

			_minkowskiSub(dir, 0);
			if(dir.dot(_tri.pos[0]) < 0)
				return _setAsNotHit(1);

			// 原点と重なっていたら終了 = 内部点
			lens = _tri.pos[0].len_sq();
			if(lens < NEAR_THRESHOLD_SQ)
				return _setAsHit(1, _posA[0]);

			dir = _tri.pos[0] / std::sqrt(lens) * -1.f;
			_minkowskiSub(dir, 1);

			// 2つのミンコフスキー頂点から次の方向を決定(Segmentの最短距離)
			{
				Vec2 sdir = _tri.pos[1] - _tri.pos[0];
				const float dirLen = sdir.normalize();
				const float r = sdir.dot(-_tri.pos[0]);
				D_Assert(r >= 0, "expect: r>=0, actual: r=%f", r);
				if(r > dirLen)
					return _setAsNotHit(2);
				if(r >= dirLen-1e-5f) {
					std::swap(_posA[0], _posA[1]);
					std::swap(_tri.pos[0], _tri.pos[1]);
					return _setAsHit(1, _posA[0]);
				}
				Vec2 cp = _tri.pos[0] + sdir*r;
				const float len = cp.normalize();
				if(len < 1e-4f) {
					// ライン上に原点がある
					// 90度回転
					Vec2 ldir = Vec2{sdir.y, -sdir.x};
					const Vec2 v0 = _m0.im_support(ldir) - _m1.im_support(-ldir);
					// 更に反転(-90)
					ldir *= -1;
					const Vec2 v1 = _m0.im_support(ldir) - _m1.im_support(-ldir);
					if((v1-_tri.pos[0]).cw(v0-_tri.pos[0]) >= 0) {
						const Vec2 pos = _posA[0].l_intp(_posA[1], r / dirLen);
						return _setAsHit(2, pos);
					}
					return _setAsNotHit(2);
				}
				dir = cp;
			}
			// 次に探索する方向
			LNear res(dir, LinePos::OnLine);
			// 今までの最短距離
			constexpr float DistMax = std::numeric_limits<float>::max();
			float minDist = DistMax;
			// 次の探索結果を書き込むインデックス
			int idx = 2;
			for(;;) {
				// 新たな頂点を追加
				dir = res.first.normalization() * -1.f;
				_minkowskiSub(dir, idx);
				if(dir.dot(_tri.pos[idx]) < 0)
					return _setAsNotHit(3);

				// 既存の頂点と同じ座標だったらこれ以上進展はないということで、終了
				const auto& nei = NeighborIndex[idx];
				auto &rV0 = _tri.pos[nei[0]],
						&rV1 = _tri.pos[nei[1]],
						&rV2 = _tri.pos[nei[2]];
				{
					const float d1 = rV1.dot(dir),
							  d0 = rV0.dot(dir),
							  d2 = rV2.dot(dir);
					if(
						d1 < d0
						|| d1 < d2
						|| rV1 == rV0
						|| rV1 == rV2
					)
						return _setAsNotHit(3);
				}

				const Vec2 ori(0);
				// 現時点で三角形が原点を含んでいるか
				{
					bool bIn;
					if(_tri.isClockwise())
						bIn = _tri.hit({0,0});
					else {
						_tri.flip();
						bIn = _tri.hit({0,0});
						_tri.flip();
					}
					if(bIn) {
						// 交差領域の1点を算出
						float cf[3];
						BarycentricCoord(cf, _tri.pos[0], _tri.pos[1], _tri.pos[2], ori);
						const auto v = MixVector(cf, _posA[0], _posA[1], _posA[2]);
						return _setAsHit(3, v);
					}
				}
				float dist = DistMax;
				idx = -1;
				// nei[0], nei[1], dist&, idx&, res&, rV0, rV1 -> bool
				res = Segment(_tri.pos[nei[0]], _tri.pos[nei[1]]).nearest(ori);
				if(res.second == LinePos::OnLine) {
					const float td = res.first.len_sq();
					if(td < 1e-7f) {
						const float r = GetRatio(rV0, rV1, res.first);
						const auto in = _posA[nei[0]]*(1-r) + _posA[nei[1]]*r;
						return _setAsHit(3, in);
					}
					if(dist > td) {
						dist = td;
						// この辺について調べる
						idx = nei[2];
					}
				}
				{
					auto res2 = Segment(_tri.pos[nei[1]], _tri.pos[nei[2]]).nearest(ori);
					if(res2.second == LinePos::OnLine) {
						const float td = res2.first.len_sq();
						if(td < 1e-7f) {
							const float r = GetRatio(rV1, rV2, res.first);
							const auto in = _posA[nei[1]]*(1-r) + _posA[nei[2]]*r;
							return _setAsHit(3, in);
						}
						if(dist > td) {
							dist = td;
							// この辺について調べる
							idx = nei[0];
							res = res2;
						}
					}
				}
				if(dist > minDist)
					return _setAsNotHit(3);
				minDist = dist;
				if(idx < 0)
					return _setAsNotHit(3);
			}
		}
	}
}
<|endoftext|>


<commit_before>AliAnalysisTask *AddTaskHFEtpctofv2(Int_t tpcCls=110, Double_t tpcClsr=50, Int_t tpcClspid=60, Double_t tpcsharedfraction=95, Int_t itsCls=4, Double_t chi2peritscl=36, Int_t pixellayer=2, Double_t dcaxy=100,Double_t dcaz=200, Double_t tofsig=30., Double_t tpcdedx0=0.0, Double_t tpcdedx1=0.0, Double_t tpcdedx2=0.0, Double_t tpcdedx3=0.0, Double_t tpcdedx4=0.0, Int_t vzero=3, Int_t debuglevel=2){

  //set config file name
  TString configFile("$ALICE_ROOT/PWGHF/hfe/macros/configs/PbPb/ConfigHFE_FLOW_TOFTPC.C");
  TString checkconfig="ConfigHFE_FLOW_TOFTPC";
  if (!gROOT->GetListOfGlobalFunctions()->FindObject(checkconfig.Data()))
    gROOT->LoadMacro(configFile.Data());

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  AliAnalysisDataContainer *cinput  = mgr->GetCommonInputContainer();
  AliAnalysisTaskHFEFlow *task = ConfigHFE_FLOW_TOFTPC(kFALSE, tpcCls, tpcClsr, tpcClspid, tpcsharedfraction, itsCls, chi2peritscl, pixellayer, dcaxy, dcaz,tofsig,tpcdedx0,tpcdedx1,tpcdedx2,tpcdedx3,tpcdedx4,vzero,debuglevel);

  task->SetNbBinsCentralityQCumulant(5);
  //task->SetBinCentralityLess(0,0.0);
  task->SetBinCentralityLess(0,0.0);
  task->SetBinCentralityLess(1,10.0);
  task->SetBinCentralityLess(2,20.0);
  task->SetBinCentralityLess(3,40.0);
  task->SetBinCentralityLess(4,50.0);
  task->SetBinCentralityLess(5,60.0);
  //task->SetBinCentralityLess(7,80.0);

  TString appendixx(TString::Format("TPC%dTPCr%dTPCpid%dTPCShared%dITScl%dChi2perITS%dPixelLayer%dDCAr%dz%dTOFsig%dTPCmindedx0%dTPCmindedx1%dTPCmindedx2%dTPCmindedx3%dTPCmindedx4%dVZERO%dDebugLevel%decorr%d",tpcCls,(Int_t)tpcClsr,tpcClspid,(Int_t) tpcsharedfraction,itsCls,(Int_t) chi2peritscl,(Int_t) pixellayer,(Int_t) dcaxy,(Int_t)dcaz,(Int_t) tofsig,(Int_t)tpcdedx0,(Int_t)tpcdedx1,(Int_t)tpcdedx2,(Int_t)tpcdedx3,(Int_t)tpcdedx4,vzero,debuglevel));
  printf("appendixx %s\n", appendixx.Data());

  task->SetHFEVZEROEventPlane(0x0);

  mgr->AddTask(task);

  TString containerName = mgr->GetCommonFileName();
  containerName += ":";
  containerName += appendixx.Data();

  AliAnalysisDataContainer *cinput  = mgr->GetCommonInputContainer();
  mgr->ConnectOutput(task,1, mgr->CreateContainer(Form("bailhach_HFEv2EP_%s", appendixx.Data()), TList::Class(),AliAnalysisManager::kOutputContainer,containerName.Data()));
  mgr->ConnectInput(task,0, cinput );

}
<commit_msg>return value<commit_after>AliAnalysisTask *AddTaskHFEtpctofv2(Int_t tpcCls=110, Double_t tpcClsr=50, Int_t tpcClspid=60, Double_t tpcsharedfraction=95, Int_t itsCls=4, Double_t chi2peritscl=36, Int_t pixellayer=2, Double_t dcaxy=100,Double_t dcaz=200, Double_t tofsig=30., Double_t tpcdedx0=0.0, Double_t tpcdedx1=0.0, Double_t tpcdedx2=0.0, Double_t tpcdedx3=0.0, Double_t tpcdedx4=0.0, Int_t vzero=3, Int_t debuglevel=2){

  //set config file name
  TString configFile("$ALICE_ROOT/PWGHF/hfe/macros/configs/PbPb/ConfigHFE_FLOW_TOFTPC.C");
  TString checkconfig="ConfigHFE_FLOW_TOFTPC";
  if (!gROOT->GetListOfGlobalFunctions()->FindObject(checkconfig.Data()))
    gROOT->LoadMacro(configFile.Data());

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  AliAnalysisDataContainer *cinput  = mgr->GetCommonInputContainer();
  AliAnalysisTaskHFEFlow *task = ConfigHFE_FLOW_TOFTPC(kFALSE, tpcCls, tpcClsr, tpcClspid, tpcsharedfraction, itsCls, chi2peritscl, pixellayer, dcaxy, dcaz,tofsig,tpcdedx0,tpcdedx1,tpcdedx2,tpcdedx3,tpcdedx4,vzero,debuglevel);

  task->SetNbBinsCentralityQCumulant(5);
  //task->SetBinCentralityLess(0,0.0);
  task->SetBinCentralityLess(0,0.0);
  task->SetBinCentralityLess(1,10.0);
  task->SetBinCentralityLess(2,20.0);
  task->SetBinCentralityLess(3,40.0);
  task->SetBinCentralityLess(4,50.0);
  task->SetBinCentralityLess(5,60.0);
  //task->SetBinCentralityLess(7,80.0);

  TString appendixx(TString::Format("TPC%dTPCr%dTPCpid%dTPCShared%dITScl%dChi2perITS%dPixelLayer%dDCAr%dz%dTOFsig%dTPCmindedx0%dTPCmindedx1%dTPCmindedx2%dTPCmindedx3%dTPCmindedx4%dVZERO%dDebugLevel%decorr%d",tpcCls,(Int_t)tpcClsr,tpcClspid,(Int_t) tpcsharedfraction,itsCls,(Int_t) chi2peritscl,(Int_t) pixellayer,(Int_t) dcaxy,(Int_t)dcaz,(Int_t) tofsig,(Int_t)tpcdedx0,(Int_t)tpcdedx1,(Int_t)tpcdedx2,(Int_t)tpcdedx3,(Int_t)tpcdedx4,vzero,debuglevel));
  printf("appendixx %s\n", appendixx.Data());

  task->SetHFEVZEROEventPlane(0x0);

  mgr->AddTask(task);

  TString containerName = mgr->GetCommonFileName();
  containerName += ":";
  containerName += appendixx.Data();

  AliAnalysisDataContainer *cinput  = mgr->GetCommonInputContainer();
  mgr->ConnectOutput(task,1, mgr->CreateContainer(Form("bailhach_HFEv2EP_%s", appendixx.Data()), TList::Class(),AliAnalysisManager::kOutputContainer,containerName.Data()));
  mgr->ConnectInput(task,0, cinput );

  return task;

}
<|endoftext|>


<commit_before>#ifndef _CZAR_HH_
#define _CZAR_HH_

//#define DEBUG
#ifdef DEBUG
#  define D(x) x
#else
#  define D(x)
#endif

#include <Arduino.h>

#include <lwm/sys/sysConfig.h>
#include <lwm/phy/phy.h>
#include <lwm/hal/hal.h>
#include <lwm/sys/sys.h>
#include <lwm/nwk/nwk.h>
#include <lwm/sys/sysTimer.h>
#include <lwm/phy/atmegarfr2.h>

class CzarController {

  public:
    CzarController();
    ~CzarController();

    void setup();
    void loop();

  protected:
    // Name of the sketch (e.g. "Bootstrap")
    const char *sketchName;
};

extern CzarController Czar;

#endif
<commit_msg>Changing inheritance<commit_after><|endoftext|>