<commit_before>#include "SettingsUI.h"
#include <CommCtrl.h>
#pragma comment(lib, "comctl32.lib")

/* DLGTEMPLATEEX Structure */
#include <pshpack1.h>
typedef struct DLGTEMPLATEEX
{
    WORD dlgVer;
    WORD signature;
    DWORD helpID;
    DWORD exStyle;
    DWORD style;
    WORD cDlgItems;
    short x;
    short y;
    short cx;
    short cy;
} DLGTEMPLATEEX, *LPDLGTEMPLATEEX;
#include <poppack.h>

/* Needed to determine whether the Apply button is enabled/disabled */
#define IDD_APPLYNOW 0x3021

#include "../3RVX/3RVX.h"
#include "../3RVX/LanguageTranslator.h"
#include "../3RVX/Logger.h"
#include "../3RVX/Settings.h"
#include "UITranslator.h"

/* Tabs*/
#include "Tab.h"
#include "General.h"
#include "Display.h"
#include "Hotkeys.h"
General general;
Display display;
Hotkeys hotkeys;
Tab *tabs[] = { &general, &display, &hotkeys };

/* Startup x/y location offsets */
#define XOFFSET 70
#define YOFFSET 20

HINSTANCE hInstance = NULL;
HWND mainWnd = NULL;

int APIENTRY wWinMain(
        _In_ HINSTANCE hInstance,
        _In_opt_ HINSTANCE hPrevInstance,
        _In_ LPTSTR lpCmdLine,
        _In_ int nCmdShow) {

	UNREFERENCED_PARAMETER(hPrevInstance);
	UNREFERENCED_PARAMETER(lpCmdLine);

    Logger::Start();
    CLOG(L"Starting SettingsUI...");
    Settings *settings = Settings::Instance();
    settings->Load();

    hInstance = hInstance;

    WNDCLASSEX wcex;
    wcex.cbSize = sizeof(WNDCLASSEX);
    wcex.style = NULL;
    wcex.lpfnWndProc = WndProc;
    wcex.cbClsExtra = NULL;
    wcex.cbWndExtra = NULL;
    wcex.hInstance = hInstance;
    wcex.hIcon = LoadIcon(NULL, MAKEINTRESOURCE(IDI_SETTINGS));
    wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
    wcex.hbrBackground = (HBRUSH) (COLOR_WINDOW);
    wcex.lpszMenuName = NULL;
    wcex.lpszClassName = L"3RVX SettingsUI";
    wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION);

    if (!RegisterClassEx(&wcex)) {
        CLOG(L"Could not register class");
        return EXIT_FAILURE;
    }

    mainWnd = CreateWindowEx(
        NULL, L"3RVX SettingsUI", L"3RVX SettingsUI", NULL,
        0, 0, 0, 0, NULL, NULL, hInstance, NULL);

    PROPSHEETPAGE psp[4];

    LanguageTranslator *lt = settings->Translator();
    std::wstring genTitle = lt->Translate(std::wstring(L"General"));
    std::wstring dispTitle = lt->Translate(std::wstring(L"Display"));
    std::wstring hkTitle = lt->Translate(std::wstring(L"Hotkeys"));
    std::wstring aboutTitle = lt->Translate(std::wstring(L"About"));

    psp[0] = { 0 };
    psp[0].dwSize = sizeof(PROPSHEETPAGE);
    psp[0].dwFlags = PSP_USETITLE;
    psp[0].hInstance = hInstance;
    psp[0].pszTemplate = MAKEINTRESOURCE(IDD_GENERAL);
    psp[0].pszIcon = NULL;
    psp[0].pfnDlgProc = (DLGPROC) GeneralTabProc;
    psp[0].pszTitle = &genTitle[0];
    psp[0].lParam = NULL;

    psp[1] = { 0 };
    psp[1].dwSize = sizeof(PROPSHEETPAGE);
    psp[1].dwFlags = PSP_USETITLE;
    psp[1].hInstance = hInstance;
    psp[1].pszTemplate = MAKEINTRESOURCE(IDD_DISPLAY);
    psp[1].pszIcon = NULL;
    psp[1].pfnDlgProc = (DLGPROC) DisplayTabProc;
    psp[1].pszTitle = &dispTitle[0];
    psp[1].lParam = 0;

    psp[2] = { 0 };
    psp[2].dwSize = sizeof(PROPSHEETPAGE);
    psp[2].dwFlags = PSP_USETITLE;
    psp[2].hInstance = hInstance;
    psp[2].pszTemplate = MAKEINTRESOURCE(IDD_HOTKEYS);
    psp[2].pszIcon = NULL;
    psp[2].pfnDlgProc = (DLGPROC) HotkeyTabProc;
    psp[2].pszTitle = &hkTitle[0];
    psp[2].lParam = 0;

    psp[3] = { 0 };
    psp[3].dwSize = sizeof(PROPSHEETPAGE);
    psp[3].dwFlags = PSP_USETITLE;
    psp[3].hInstance = hInstance;
    psp[3].pszTemplate = MAKEINTRESOURCE(IDD_ABOUT);
    psp[3].pszIcon = NULL;
    psp[3].pfnDlgProc = (DLGPROC) AboutTabProc;
    psp[3].pszTitle = &aboutTitle[0];
    psp[3].lParam = 0;

    PROPSHEETHEADER psh = { 0 };
    psh.dwSize = sizeof(PROPSHEETHEADER);
    psh.dwFlags = PSH_PROPSHEETPAGE | PSH_USEICONID | PSH_USECALLBACK;
    psh.hwndParent = mainWnd;
    psh.hInstance = hInstance;
    psh.pszIcon = MAKEINTRESOURCE(IDI_SETTINGS);
    psh.pszCaption = L"3RVX Settings";
    psh.nStartPage = 0;
    psh.nPages = sizeof(psp) / sizeof(PROPSHEETPAGE);
    psh.ppsp = (LPCPROPSHEETPAGE) &psp;
    psh.pfnCallback = (PFNPROPSHEETCALLBACK) PropSheetProc;

    /* Position the window */
    POINT pt = { 0 };
    GetCursorPos(&pt);
    MoveWindow(mainWnd, pt.x - XOFFSET, pt.y - YOFFSET, 0, 0, TRUE);

    CLOG(L"Launching modal property sheet.");
    return PropertySheet(&psh);
}

LRESULT CALLBACK WndProc(
        HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {

    PAINTSTRUCT ps;
    HDC hdc;

    switch (message) {
    case WM_PAINT:
        hdc = BeginPaint(hWnd, &ps);
        EndPaint(hWnd, &ps);
        break;

    case WM_DESTROY:
        PostQuitMessage(0);
        break;

    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }

    return 0;
}

int CALLBACK PropSheetProc(HWND hWnd, UINT msg, LPARAM lParam) {
    switch (msg) {
    case PSCB_PRECREATE:
        /* Disable the help button: */
        if (((LPDLGTEMPLATEEX) lParam)->signature == 0xFFFF) {
            ((LPDLGTEMPLATEEX) lParam)->style &= ~DS_CONTEXTHELP;
        } else {
            ((LPDLGTEMPLATE) lParam)->style &= ~DS_CONTEXTHELP;
        }

        /* Show window in the taskbar: */
        ((LPDLGTEMPLATE) lParam)->dwExtendedStyle |= WS_EX_APPWINDOW;
        break;

    case PSCB_INITIALIZED:
        UITranslator::TranslateWindowText(hWnd);

        /* These values are hard-coded in case the user has a non-english GUI
           but wants to change the program language */
        UITranslator::TranslateControlText(
            hWnd, IDOK, std::wstring(L"OK"));
        UITranslator::TranslateControlText(
            hWnd, IDCANCEL, std::wstring(L"Cancel"));
        UITranslator::TranslateControlText(
            hWnd, IDD_APPLYNOW, std::wstring(L"Apply"));
        break;

    case PSCB_BUTTONPRESSED:
        if (lParam == PSBTN_OK || lParam == PSBTN_APPLYNOW) {
            HWND hApply = GetDlgItem(hWnd, IDD_APPLYNOW);
            if (IsWindowEnabled(hApply)) {
                /* Save settings*/
                CLOG(L"Saving settings...");
                for (Tab *tab : tabs) {
                    tab->SaveSettings();
                }
                Settings::Instance()->Save();

                CLOG(L"Notifying 3RVX process of settings change");
                HWND masterWnd = FindWindow(L"3RVXv3", L"3RVXv3");
                SendMessage(masterWnd, WM_3RVX_CONTROL, MSG_LOAD, NULL);
            }
        }
        break;
    }

    return TRUE;
}

DLGPROC GeneralTabProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) {
    return general.TabProc(hDlg, message, wParam, lParam);
}

DLGPROC DisplayTabProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) {
    return display.TabProc(hDlg, message, wParam, lParam);
}

DLGPROC HotkeyTabProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) {
    return hotkeys.TabProc(hDlg, message, wParam, lParam);
}

DLGPROC AboutTabProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) {
    return FALSE;
}<commit_msg>Don't set small icon<commit_after>#include "SettingsUI.h"
#include <CommCtrl.h>
#pragma comment(lib, "comctl32.lib")

/* DLGTEMPLATEEX Structure */
#include <pshpack1.h>
typedef struct DLGTEMPLATEEX
{
    WORD dlgVer;
    WORD signature;
    DWORD helpID;
    DWORD exStyle;
    DWORD style;
    WORD cDlgItems;
    short x;
    short y;
    short cx;
    short cy;
} DLGTEMPLATEEX, *LPDLGTEMPLATEEX;
#include <poppack.h>

/* Needed to determine whether the Apply button is enabled/disabled */
#define IDD_APPLYNOW 0x3021

#include "../3RVX/3RVX.h"
#include "../3RVX/LanguageTranslator.h"
#include "../3RVX/Logger.h"
#include "../3RVX/Settings.h"
#include "UITranslator.h"

/* Tabs*/
#include "Tab.h"
#include "General.h"
#include "Display.h"
#include "Hotkeys.h"
General general;
Display display;
Hotkeys hotkeys;
Tab *tabs[] = { &general, &display, &hotkeys };

/* Startup x/y location offsets */
#define XOFFSET 70
#define YOFFSET 20

HINSTANCE hInstance = NULL;
HWND mainWnd = NULL;

int APIENTRY wWinMain(
        _In_ HINSTANCE hInstance,
        _In_opt_ HINSTANCE hPrevInstance,
        _In_ LPTSTR lpCmdLine,
        _In_ int nCmdShow) {

	UNREFERENCED_PARAMETER(hPrevInstance);
	UNREFERENCED_PARAMETER(lpCmdLine);

    Logger::Start();
    CLOG(L"Starting SettingsUI...");
    Settings *settings = Settings::Instance();
    settings->Load();

    hInstance = hInstance;

    WNDCLASSEX wcex;
    wcex.cbSize = sizeof(WNDCLASSEX);
    wcex.style = NULL;
    wcex.lpfnWndProc = WndProc;
    wcex.cbClsExtra = NULL;
    wcex.cbWndExtra = NULL;
    wcex.hInstance = hInstance;
    wcex.hIcon = LoadIcon(NULL, MAKEINTRESOURCE(IDI_SETTINGS));
    wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
    wcex.hbrBackground = (HBRUSH) (COLOR_WINDOW);
    wcex.lpszMenuName = NULL;
    wcex.lpszClassName = L"3RVX SettingsUI";

    if (!RegisterClassEx(&wcex)) {
        CLOG(L"Could not register class");
        return EXIT_FAILURE;
    }

    mainWnd = CreateWindowEx(
        NULL, L"3RVX SettingsUI", L"3RVX SettingsUI", NULL,
        0, 0, 0, 0, NULL, NULL, hInstance, NULL);

    PROPSHEETPAGE psp[4];

    LanguageTranslator *lt = settings->Translator();
    std::wstring genTitle = lt->Translate(std::wstring(L"General"));
    std::wstring dispTitle = lt->Translate(std::wstring(L"Display"));
    std::wstring hkTitle = lt->Translate(std::wstring(L"Hotkeys"));
    std::wstring aboutTitle = lt->Translate(std::wstring(L"About"));

    psp[0] = { 0 };
    psp[0].dwSize = sizeof(PROPSHEETPAGE);
    psp[0].dwFlags = PSP_USETITLE;
    psp[0].hInstance = hInstance;
    psp[0].pszTemplate = MAKEINTRESOURCE(IDD_GENERAL);
    psp[0].pszIcon = NULL;
    psp[0].pfnDlgProc = (DLGPROC) GeneralTabProc;
    psp[0].pszTitle = &genTitle[0];
    psp[0].lParam = NULL;

    psp[1] = { 0 };
    psp[1].dwSize = sizeof(PROPSHEETPAGE);
    psp[1].dwFlags = PSP_USETITLE;
    psp[1].hInstance = hInstance;
    psp[1].pszTemplate = MAKEINTRESOURCE(IDD_DISPLAY);
    psp[1].pszIcon = NULL;
    psp[1].pfnDlgProc = (DLGPROC) DisplayTabProc;
    psp[1].pszTitle = &dispTitle[0];
    psp[1].lParam = 0;

    psp[2] = { 0 };
    psp[2].dwSize = sizeof(PROPSHEETPAGE);
    psp[2].dwFlags = PSP_USETITLE;
    psp[2].hInstance = hInstance;
    psp[2].pszTemplate = MAKEINTRESOURCE(IDD_HOTKEYS);
    psp[2].pszIcon = NULL;
    psp[2].pfnDlgProc = (DLGPROC) HotkeyTabProc;
    psp[2].pszTitle = &hkTitle[0];
    psp[2].lParam = 0;

    psp[3] = { 0 };
    psp[3].dwSize = sizeof(PROPSHEETPAGE);
    psp[3].dwFlags = PSP_USETITLE;
    psp[3].hInstance = hInstance;
    psp[3].pszTemplate = MAKEINTRESOURCE(IDD_ABOUT);
    psp[3].pszIcon = NULL;
    psp[3].pfnDlgProc = (DLGPROC) AboutTabProc;
    psp[3].pszTitle = &aboutTitle[0];
    psp[3].lParam = 0;

    PROPSHEETHEADER psh = { 0 };
    psh.dwSize = sizeof(PROPSHEETHEADER);
    psh.dwFlags = PSH_PROPSHEETPAGE | PSH_USEICONID | PSH_USECALLBACK;
    psh.hwndParent = mainWnd;
    psh.hInstance = hInstance;
    psh.pszIcon = MAKEINTRESOURCE(IDI_SETTINGS);
    psh.pszCaption = L"3RVX Settings";
    psh.nStartPage = 0;
    psh.nPages = sizeof(psp) / sizeof(PROPSHEETPAGE);
    psh.ppsp = (LPCPROPSHEETPAGE) &psp;
    psh.pfnCallback = (PFNPROPSHEETCALLBACK) PropSheetProc;

    /* Position the window */
    POINT pt = { 0 };
    GetCursorPos(&pt);
    MoveWindow(mainWnd, pt.x - XOFFSET, pt.y - YOFFSET, 0, 0, TRUE);

    CLOG(L"Launching modal property sheet.");
    return PropertySheet(&psh);
}

LRESULT CALLBACK WndProc(
        HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {

    PAINTSTRUCT ps;
    HDC hdc;

    switch (message) {
    case WM_PAINT:
        hdc = BeginPaint(hWnd, &ps);
        EndPaint(hWnd, &ps);
        break;

    case WM_DESTROY:
        PostQuitMessage(0);
        break;

    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }

    return 0;
}

int CALLBACK PropSheetProc(HWND hWnd, UINT msg, LPARAM lParam) {
    switch (msg) {
    case PSCB_PRECREATE:
        /* Disable the help button: */
        if (((LPDLGTEMPLATEEX) lParam)->signature == 0xFFFF) {
            ((LPDLGTEMPLATEEX) lParam)->style &= ~DS_CONTEXTHELP;
        } else {
            ((LPDLGTEMPLATE) lParam)->style &= ~DS_CONTEXTHELP;
        }

        /* Show window in the taskbar: */
        ((LPDLGTEMPLATE) lParam)->dwExtendedStyle |= WS_EX_APPWINDOW;
        break;

    case PSCB_INITIALIZED:
        UITranslator::TranslateWindowText(hWnd);

        /* These values are hard-coded in case the user has a non-english GUI
           but wants to change the program language */
        UITranslator::TranslateControlText(
            hWnd, IDOK, std::wstring(L"OK"));
        UITranslator::TranslateControlText(
            hWnd, IDCANCEL, std::wstring(L"Cancel"));
        UITranslator::TranslateControlText(
            hWnd, IDD_APPLYNOW, std::wstring(L"Apply"));
        break;

    case PSCB_BUTTONPRESSED:
        if (lParam == PSBTN_OK || lParam == PSBTN_APPLYNOW) {
            HWND hApply = GetDlgItem(hWnd, IDD_APPLYNOW);
            if (IsWindowEnabled(hApply)) {
                /* Save settings*/
                CLOG(L"Saving settings...");
                for (Tab *tab : tabs) {
                    tab->SaveSettings();
                }
                Settings::Instance()->Save();

                CLOG(L"Notifying 3RVX process of settings change");
                HWND masterWnd = FindWindow(L"3RVXv3", L"3RVXv3");
                SendMessage(masterWnd, WM_3RVX_CONTROL, MSG_LOAD, NULL);
            }
        }
        break;
    }

    return TRUE;
}

DLGPROC GeneralTabProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) {
    return general.TabProc(hDlg, message, wParam, lParam);
}

DLGPROC DisplayTabProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) {
    return display.TabProc(hDlg, message, wParam, lParam);
}

DLGPROC HotkeyTabProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) {
    return hotkeys.TabProc(hDlg, message, wParam, lParam);
}

DLGPROC AboutTabProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) {
    return FALSE;
}<|endoftext|>


<commit_before>#if defined(__EMSCRIPTEN__)
#include "miniqbt/MiniQbt.hpp"
#include <emscripten/bind.h>
/**
 * When the emscripten compiler is doing it's thing.
 * Expose the QasmAsyncInterpreter
 */

std::string getName() {
    return MiniQbt::NAME;
}

std::string getVersion() {
    return MiniQbt::VERSION;
}

EMSCRIPTEN_BINDINGS(MiniQbt) {

    //register_vector<std::string>("VectorString");
    //register_vector<int>("QuantumResult");
    emscripten::class_<MiniQbt::QasmAsyncInterpreter>("QasmAsyncInterpreter").
    constructor().
    function("interpret", &MiniQbt::QasmAsyncInterpreter::interpret ).
    function("doesRegisterExists", &MiniQbt::QasmAsyncInterpreter::doesRegisterExists).
    function("getQuantumRegisters", &MiniQbt::QasmAsyncInterpreter::getQuantumRegisters).
    function("resetSuperPosition", &MiniQbt::QasmAsyncInterpreter::resetSuperPosition).
    function("readClassicRegister", &MiniQbt::QasmAsyncInterpreter::readClassicRegister).
    function("doesRegisterExists", &MiniQbt::QasmAsyncInterpreter::doesRegisterExists).
    function("getRegisters",  &MiniQbt::QasmAsyncInterpreter::getRegisters).
    function("getError",  &MiniQbt::QasmAsyncInterpreter::getError).
    function("hasErrors", &MiniQbt::QasmAsyncInterpreter::hasErrors );

    emscripten::function("getName", &getName);
    emscripten::function("getVersion", &getVersion);
}

#endif
<commit_msg>Name and versions are now constants<commit_after>#if defined(__EMSCRIPTEN__)
#include "miniqbt/MiniQbt.hpp"
#include <emscripten/bind.h>
/**
 * When the emscripten compiler is doing it's thing.
 * Expose the QasmAsyncInterpreter
 */
EMSCRIPTEN_BINDINGS(MiniQbt) {

    //register_vector<std::string>("VectorString");
    //register_vector<int>("QuantumResult");
    emscripten::class_<MiniQbt::QasmAsyncInterpreter>("QasmAsyncInterpreter").
    constructor().
    function("interpret", &MiniQbt::QasmAsyncInterpreter::interpret ).
    function("doesRegisterExists", &MiniQbt::QasmAsyncInterpreter::doesRegisterExists).
    function("getQuantumRegisters", &MiniQbt::QasmAsyncInterpreter::getQuantumRegisters).
    function("resetSuperPosition", &MiniQbt::QasmAsyncInterpreter::resetSuperPosition).
    function("readClassicRegister", &MiniQbt::QasmAsyncInterpreter::readClassicRegister).
    function("doesRegisterExists", &MiniQbt::QasmAsyncInterpreter::doesRegisterExists).
    function("getRegisters",  &MiniQbt::QasmAsyncInterpreter::getRegisters).
    function("getError",  &MiniQbt::QasmAsyncInterpreter::getError).
    function("hasErrors", &MiniQbt::QasmAsyncInterpreter::hasErrors );

    emscripten::constant("NAME", std::string(MiniQbt::NAME));
    emscripten::constant("VERSION", std::string(MiniQbt::VERSION));
}

#endif
<|endoftext|>


<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                        Intel License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of Intel Corporation may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#include "precomp.hpp"

using namespace std;

const int draw_shift_bits = 4;
const int draw_multiplier = 1 << draw_shift_bits;

namespace cv
{

/*
 * Functions to draw keypoints and matches.
 */
static inline void _drawKeypoint( Mat& img, const KeyPoint& p, const Scalar& color, int flags )
{
    CV_Assert( !img.empty() );
    Point center( cvRound(p.pt.x * draw_multiplier), cvRound(p.pt.y * draw_multiplier) );

    if( flags & DrawMatchesFlags::DRAW_RICH_KEYPOINTS )
    {
        int radius = cvRound(p.size/2 * draw_multiplier); // KeyPoint::size is a diameter

        // draw the circles around keypoints with the keypoints size
        circle( img, center, radius, color, 1, CV_AA, draw_shift_bits );

        // draw orientation of the keypoint, if it is applicable
        if( p.angle != -1 )
        {
            float srcAngleRad = p.angle*(float)CV_PI/180.f;
            Point orient( cvRound(cos(srcAngleRad)*radius ),
                          cvRound(sin(srcAngleRad)*radius )
                        );
            line( img, center, center+orient, color, 1, CV_AA, draw_shift_bits );
        }
#if 0
        else
        {
            // draw center with R=1
            int radius = 1 * draw_multiplier;
            circle( img, center, radius, color, 1, CV_AA, draw_shift_bits );
        }
#endif
    }
    else
    {
        // draw center with R=3
        int radius = 3 * draw_multiplier;
        circle( img, center, radius, color, 1, CV_AA, draw_shift_bits );
    }
}

void drawKeypoints( const Mat& image, const vector<KeyPoint>& keypoints, Mat& outImage,
                    const Scalar& _color, int flags )
{
    if( !(flags & DrawMatchesFlags::DRAW_OVER_OUTIMG) )
    {
        if( image.type() == CV_8UC3 )
        {
            image.copyTo( outImage );
        }
        else if( image.type() == CV_8UC1 )
        {
            cvtColor( image, outImage, CV_GRAY2BGR );
        }
        else
        {
            CV_Error( CV_StsBadArg, "Incorrect type of input image.\n" );
        }
    }

    RNG& rng=theRNG();
    bool isRandColor = _color == Scalar::all(-1);

    CV_Assert( !outImage.empty() );
    vector<KeyPoint>::const_iterator it = keypoints.begin(),
                                     end = keypoints.end();
    for( ; it != end; ++it )
    {
        Scalar color = isRandColor ? Scalar(rng(256), rng(256), rng(256)) : _color;
        _drawKeypoint( outImage, *it, color, flags );
    }
}

static void _prepareImgAndDrawKeypoints( const Mat& img1, const vector<KeyPoint>& keypoints1,
                                         const Mat& img2, const vector<KeyPoint>& keypoints2,
                                         Mat& outImg, Mat& outImg1, Mat& outImg2,
                                         const Scalar& singlePointColor, int flags )
{
    Size size( img1.cols + img2.cols, MAX(img1.rows, img2.rows) );
    if( flags & DrawMatchesFlags::DRAW_OVER_OUTIMG )
    {
        if( size.width > outImg.cols || size.height > outImg.rows )
            CV_Error( CV_StsBadSize, "outImg has size less than need to draw img1 and img2 together" );
        outImg1 = outImg( Rect(0, 0, img1.cols, img1.rows) );
        outImg2 = outImg( Rect(img1.cols, 0, img2.cols, img2.rows) );
    }
    else
    {
        outImg.create( size, CV_MAKETYPE(img1.depth(), 3) );
        outImg = Scalar::all(0);
        outImg1 = outImg( Rect(0, 0, img1.cols, img1.rows) );
        outImg2 = outImg( Rect(img1.cols, 0, img2.cols, img2.rows) );

        if( img1.type() == CV_8U )
            cvtColor( img1, outImg1, CV_GRAY2BGR );
        else
            img1.copyTo( outImg1 );

        if( img2.type() == CV_8U )
            cvtColor( img2, outImg2, CV_GRAY2BGR );
        else
            img2.copyTo( outImg2 );
    }

    // draw keypoints
    if( !(flags & DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS) )
    {
        Mat _outImg1 = outImg( Rect(0, 0, img1.cols, img1.rows) );
        drawKeypoints( _outImg1, keypoints1, _outImg1, singlePointColor, flags + DrawMatchesFlags::DRAW_OVER_OUTIMG );

        Mat _outImg2 = outImg( Rect(img1.cols, 0, img2.cols, img2.rows) );
        drawKeypoints( _outImg2, keypoints2, _outImg2, singlePointColor, flags + DrawMatchesFlags::DRAW_OVER_OUTIMG );
    }
}

static inline void _drawMatch( Mat& outImg, Mat& outImg1, Mat& outImg2 ,
                          const KeyPoint& kp1, const KeyPoint& kp2, const Scalar& matchColor, int flags )
{
    RNG& rng = theRNG();
    bool isRandMatchColor = matchColor == Scalar::all(-1);
    Scalar color = isRandMatchColor ? Scalar( rng(256), rng(256), rng(256) ) : matchColor;

    _drawKeypoint( outImg1, kp1, color, flags );
    _drawKeypoint( outImg2, kp2, color, flags );

    Point2f pt1 = kp1.pt,
            pt2 = kp2.pt,
            dpt2 = Point2f( std::min(pt2.x+outImg1.cols, float(outImg.cols-1)), pt2.y );

    line( outImg,
          Point(cvRound(pt1.x*draw_multiplier), cvRound(pt1.y*draw_multiplier)),
          Point(cvRound(dpt2.x*draw_multiplier), cvRound(dpt2.y*draw_multiplier)),
          color, 1, CV_AA, draw_shift_bits );
}

void drawMatches( const Mat& img1, const vector<KeyPoint>& keypoints1,
                  const Mat& img2, const vector<KeyPoint>& keypoints2,
                  const vector<DMatch>& matches1to2, Mat& outImg,
                  const Scalar& matchColor, const Scalar& singlePointColor,
                  const vector<char>& matchesMask, int flags )
{
    if( !matchesMask.empty() && matchesMask.size() != matches1to2.size() )
        CV_Error( CV_StsBadSize, "matchesMask must have the same size as matches1to2" );

    Mat outImg1, outImg2;
    _prepareImgAndDrawKeypoints( img1, keypoints1, img2, keypoints2,
                                 outImg, outImg1, outImg2, singlePointColor, flags );

    // draw matches
    for( size_t m = 0; m < matches1to2.size(); m++ )
    {
        int i1 = matches1to2[m].queryIdx;
        int i2 = matches1to2[m].trainIdx;
        if( matchesMask.empty() || matchesMask[m] )
        {
            const KeyPoint &kp1 = keypoints1[i1], &kp2 = keypoints2[i2];
            _drawMatch( outImg, outImg1, outImg2, kp1, kp2, matchColor, flags );
        }
    }
}

void drawMatches( const Mat& img1, const vector<KeyPoint>& keypoints1,
                  const Mat& img2, const vector<KeyPoint>& keypoints2,
                  const vector<vector<DMatch> >& matches1to2, Mat& outImg,
                  const Scalar& matchColor, const Scalar& singlePointColor,
                  const vector<vector<char> >& matchesMask, int flags )
{
    if( !matchesMask.empty() && matchesMask.size() != matches1to2.size() )
        CV_Error( CV_StsBadSize, "matchesMask must have the same size as matches1to2" );

    Mat outImg1, outImg2;
    _prepareImgAndDrawKeypoints( img1, keypoints1, img2, keypoints2,
                                 outImg, outImg1, outImg2, singlePointColor, flags );

    // draw matches
    for( size_t i = 0; i < matches1to2.size(); i++ )
    {
        for( size_t j = 0; j < matches1to2[i].size(); j++ )
        {
            int i1 = matches1to2[i][j].queryIdx;
            int i2 = matches1to2[i][j].trainIdx;
            if( matchesMask.empty() || matchesMask[i][j] )
            {
                const KeyPoint &kp1 = keypoints1[i1], &kp2 = keypoints2[i2];
                _drawMatch( outImg, outImg1, outImg2, kp1, kp2, matchColor, flags );
            }
        }
    }
}
}
<commit_msg>check of keypoint index range in drawMatches<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                        Intel License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of Intel Corporation may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#include "precomp.hpp"

using namespace std;

const int draw_shift_bits = 4;
const int draw_multiplier = 1 << draw_shift_bits;

namespace cv
{

/*
 * Functions to draw keypoints and matches.
 */
static inline void _drawKeypoint( Mat& img, const KeyPoint& p, const Scalar& color, int flags )
{
    CV_Assert( !img.empty() );
    Point center( cvRound(p.pt.x * draw_multiplier), cvRound(p.pt.y * draw_multiplier) );

    if( flags & DrawMatchesFlags::DRAW_RICH_KEYPOINTS )
    {
        int radius = cvRound(p.size/2 * draw_multiplier); // KeyPoint::size is a diameter

        // draw the circles around keypoints with the keypoints size
        circle( img, center, radius, color, 1, CV_AA, draw_shift_bits );

        // draw orientation of the keypoint, if it is applicable
        if( p.angle != -1 )
        {
            float srcAngleRad = p.angle*(float)CV_PI/180.f;
            Point orient( cvRound(cos(srcAngleRad)*radius ),
                          cvRound(sin(srcAngleRad)*radius )
                        );
            line( img, center, center+orient, color, 1, CV_AA, draw_shift_bits );
        }
#if 0
        else
        {
            // draw center with R=1
            int radius = 1 * draw_multiplier;
            circle( img, center, radius, color, 1, CV_AA, draw_shift_bits );
        }
#endif
    }
    else
    {
        // draw center with R=3
        int radius = 3 * draw_multiplier;
        circle( img, center, radius, color, 1, CV_AA, draw_shift_bits );
    }
}

void drawKeypoints( const Mat& image, const vector<KeyPoint>& keypoints, Mat& outImage,
                    const Scalar& _color, int flags )
{
    if( !(flags & DrawMatchesFlags::DRAW_OVER_OUTIMG) )
    {
        if( image.type() == CV_8UC3 )
        {
            image.copyTo( outImage );
        }
        else if( image.type() == CV_8UC1 )
        {
            cvtColor( image, outImage, CV_GRAY2BGR );
        }
        else
        {
            CV_Error( CV_StsBadArg, "Incorrect type of input image.\n" );
        }
    }

    RNG& rng=theRNG();
    bool isRandColor = _color == Scalar::all(-1);

    CV_Assert( !outImage.empty() );
    vector<KeyPoint>::const_iterator it = keypoints.begin(),
                                     end = keypoints.end();
    for( ; it != end; ++it )
    {
        Scalar color = isRandColor ? Scalar(rng(256), rng(256), rng(256)) : _color;
        _drawKeypoint( outImage, *it, color, flags );
    }
}

static void _prepareImgAndDrawKeypoints( const Mat& img1, const vector<KeyPoint>& keypoints1,
                                         const Mat& img2, const vector<KeyPoint>& keypoints2,
                                         Mat& outImg, Mat& outImg1, Mat& outImg2,
                                         const Scalar& singlePointColor, int flags )
{
    Size size( img1.cols + img2.cols, MAX(img1.rows, img2.rows) );
    if( flags & DrawMatchesFlags::DRAW_OVER_OUTIMG )
    {
        if( size.width > outImg.cols || size.height > outImg.rows )
            CV_Error( CV_StsBadSize, "outImg has size less than need to draw img1 and img2 together" );
        outImg1 = outImg( Rect(0, 0, img1.cols, img1.rows) );
        outImg2 = outImg( Rect(img1.cols, 0, img2.cols, img2.rows) );
    }
    else
    {
        outImg.create( size, CV_MAKETYPE(img1.depth(), 3) );
        outImg = Scalar::all(0);
        outImg1 = outImg( Rect(0, 0, img1.cols, img1.rows) );
        outImg2 = outImg( Rect(img1.cols, 0, img2.cols, img2.rows) );

        if( img1.type() == CV_8U )
            cvtColor( img1, outImg1, CV_GRAY2BGR );
        else
            img1.copyTo( outImg1 );

        if( img2.type() == CV_8U )
            cvtColor( img2, outImg2, CV_GRAY2BGR );
        else
            img2.copyTo( outImg2 );
    }

    // draw keypoints
    if( !(flags & DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS) )
    {
        Mat _outImg1 = outImg( Rect(0, 0, img1.cols, img1.rows) );
        drawKeypoints( _outImg1, keypoints1, _outImg1, singlePointColor, flags + DrawMatchesFlags::DRAW_OVER_OUTIMG );

        Mat _outImg2 = outImg( Rect(img1.cols, 0, img2.cols, img2.rows) );
        drawKeypoints( _outImg2, keypoints2, _outImg2, singlePointColor, flags + DrawMatchesFlags::DRAW_OVER_OUTIMG );
    }
}

static inline void _drawMatch( Mat& outImg, Mat& outImg1, Mat& outImg2 ,
                          const KeyPoint& kp1, const KeyPoint& kp2, const Scalar& matchColor, int flags )
{
    RNG& rng = theRNG();
    bool isRandMatchColor = matchColor == Scalar::all(-1);
    Scalar color = isRandMatchColor ? Scalar( rng(256), rng(256), rng(256) ) : matchColor;

    _drawKeypoint( outImg1, kp1, color, flags );
    _drawKeypoint( outImg2, kp2, color, flags );

    Point2f pt1 = kp1.pt,
            pt2 = kp2.pt,
            dpt2 = Point2f( std::min(pt2.x+outImg1.cols, float(outImg.cols-1)), pt2.y );

    line( outImg,
          Point(cvRound(pt1.x*draw_multiplier), cvRound(pt1.y*draw_multiplier)),
          Point(cvRound(dpt2.x*draw_multiplier), cvRound(dpt2.y*draw_multiplier)),
          color, 1, CV_AA, draw_shift_bits );
}

void drawMatches( const Mat& img1, const vector<KeyPoint>& keypoints1,
                  const Mat& img2, const vector<KeyPoint>& keypoints2,
                  const vector<DMatch>& matches1to2, Mat& outImg,
                  const Scalar& matchColor, const Scalar& singlePointColor,
                  const vector<char>& matchesMask, int flags )
{
    if( !matchesMask.empty() && matchesMask.size() != matches1to2.size() )
        CV_Error( CV_StsBadSize, "matchesMask must have the same size as matches1to2" );

    Mat outImg1, outImg2;
    _prepareImgAndDrawKeypoints( img1, keypoints1, img2, keypoints2,
                                 outImg, outImg1, outImg2, singlePointColor, flags );

    // draw matches
    for( size_t m = 0; m < matches1to2.size(); m++ )
    {
        if( matchesMask.empty() || matchesMask[m] )
        {
            int i1 = matches1to2[m].queryIdx;
            int i2 = matches1to2[m].trainIdx;
            CV_Assert(i1 >= 0 && i1 < static_cast<int>(keypoints1.size()));
            CV_Assert(i2 >= 0 && i2 < static_cast<int>(keypoints2.size()));

            const KeyPoint &kp1 = keypoints1[i1], &kp2 = keypoints2[i2];
            _drawMatch( outImg, outImg1, outImg2, kp1, kp2, matchColor, flags );
        }
    }
}

void drawMatches( const Mat& img1, const vector<KeyPoint>& keypoints1,
                  const Mat& img2, const vector<KeyPoint>& keypoints2,
                  const vector<vector<DMatch> >& matches1to2, Mat& outImg,
                  const Scalar& matchColor, const Scalar& singlePointColor,
                  const vector<vector<char> >& matchesMask, int flags )
{
    if( !matchesMask.empty() && matchesMask.size() != matches1to2.size() )
        CV_Error( CV_StsBadSize, "matchesMask must have the same size as matches1to2" );

    Mat outImg1, outImg2;
    _prepareImgAndDrawKeypoints( img1, keypoints1, img2, keypoints2,
                                 outImg, outImg1, outImg2, singlePointColor, flags );

    // draw matches
    for( size_t i = 0; i < matches1to2.size(); i++ )
    {
        for( size_t j = 0; j < matches1to2[i].size(); j++ )
        {
            int i1 = matches1to2[i][j].queryIdx;
            int i2 = matches1to2[i][j].trainIdx;
            if( matchesMask.empty() || matchesMask[i][j] )
            {
                const KeyPoint &kp1 = keypoints1[i1], &kp2 = keypoints2[i2];
                _drawMatch( outImg, outImg1, outImg2, kp1, kp2, matchColor, flags );
            }
        }
    }
}
}
<|endoftext|>


<commit_before>void AddTask_dNdPtpPb(UInt_t uTriggerMask = AliVEvent::kINT7, Int_t iCutMode = 2014 )
{
/*
CheckLoadLibrary("libPWG0base");
CheckLoadLibrary("libPWG0dep");
CheckLoadLibrary("libPWG0selectors");
*/

  //Get current Analysis Manager
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();

  if (!mgr) {
    Error("AddTask_dNdPtAnalysis_TPCITS", "No analysis manager found.");
    return 0;
  }

  // Switch off all AliInfo (too much output!!!)
//  AliLog::SetGlobalLogLevel(AliLog::kError);
//  mgr->SetDebugLevel(0);

  //
  // Create event cuts
  //
  Float_t zvWindow = 30. ;

  AlidNdPtEventCuts *evtCuts = new AlidNdPtEventCuts("AlidNdPtEventCuts","Event cuts");
  evtCuts->SetZvRange(-zvWindow,zvWindow);
  evtCuts->SetMeanXYZv(0.0,0.0,0.0);
  evtCuts->SetSigmaMeanXYZv(1.0,1.0,10.0);
  evtCuts->SetTriggerRequired(kTRUE);
  //evtCuts->SetTriggerRequired(kFALSE);

  //
  // Create geom. acceptance cuts
  //
  //Float_t etaWindow = 1.0;
  eta1 = -0.765409; eta2 = -0.165409;
  Float_t ptMin = 0.1 ;

  AlidNdPtAcceptanceCuts *accCuts = new AlidNdPtAcceptanceCuts("AlidNdPtAcceptanceCuts","Geom. acceptance cuts");
  accCuts->SetEtaRange(eta1,eta2);
  accCuts->SetPtRange(ptMin,1.e10);

  //
  // Create standard esd track cuts
  //
  Int_t cutMode = iCutMode;

  gROOT->LoadMacro("$ALICE_ROOT/PWGLF/SPECTRA/ChargedHadrons/dNdPt/macros/CreatedNdPtTrackCuts.C");
  //gROOT->LoadMacro("./CreatedNdPtTrackCuts.C");
  AliESDtrackCuts* esdTrackCuts = CreatedNdPtTrackCuts(cutMode);
  if (!esdTrackCuts) {
    printf("ERROR: esdTrackCuts could not be created\n")
    return;
  } else {
    //esdTrackCuts->SetHistogramsOn(kTRUE);
    esdTrackCuts->SetHistogramsOn(kTRUE);
  }

  Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0);

  //
  // Create task
  //
  AlidNdPtTask *task = new AlidNdPtTask("AlidNdPtTask_TPCITS");
  task->SetUseMCInfo(hasMC);

  // trigger
  task->SelectCollisionCandidates(uTriggerMask);

  //
  // set analysis options from the Helper here !!!
  //

  //AliTriggerAnalysis::Trigger trigger = AliTriggerAnalysis::kMB1;
  AlidNdPtHelper::AnalysisMode analysisMode = AlidNdPtHelper::kTPCITS;
  AlidNdPtHelper::ParticleMode particleMode = AlidNdPtHelper::kAllPart ;

  //
  // Create analysis object
  //

  AlidNdPtAnalysispPb *fdNdPtAnalysis = new AlidNdPtAnalysispPb("dNdPtAnalysis_TPCITS","dN/dPt Analysis with TPC-ITS tracking");//Now AnalysispPb before: Analzsiis
  fdNdPtAnalysis->SetEventCuts(evtCuts);
  fdNdPtAnalysis->SetAcceptanceCuts(accCuts);
  fdNdPtAnalysis->SetTrackCuts(esdTrackCuts);
  //fdNdPtAnalysis->SetBackgroundCuts(backCuts);
  fdNdPtAnalysis->SetAnalysisMode(analysisMode);
  fdNdPtAnalysis->SetParticleMode(particleMode);

  //j kCINT5 should work for 2012 data, kINT7 for 2013

  //fdNdPtAnalysis->SetTrigger(trigger);
 // fdNdPtAnalysis->SetTriggerMask(AliVEvent::kCINT5);
  fdNdPtAnalysis->SetTriggerMask(uTriggerMask);
  //fdNdPtAnalysis->SetTriggerMask(AliVEvent::kEMC1);
  if(hasMC)
  {
    //physTrigSel->SetAnalyzeMC();
    //fdNdPtAnalysis->SetPhysicsTriggerSelection(physTrigSel);

    fdNdPtAnalysis->SetUseMCInfo(kTRUE);
    fdNdPtAnalysis->SetHistogramsOn(kTRUE);
    //fdNdPtAnalysis->SetHistogramsOn(kFALSE);
  }
  else { // online trigger
//     physTrigSel->SetUseBXNumbers();
//     physTrigSel->SetComputeBG();
//     fdNdPtAnalysis->SetPhysicsTriggerSelection(physTrigSel);
  }

    // change binning
    Int_t multNbins = 152;
    Double_t binsMult[153];
    for (int i=0; i<=multNbins; i++) { binsMult[i] = -0.5 + i; }
    binsMult[152] = 1000.;
    // change binning
    const Int_t ptNbins = 81;
    Double_t bins[82] = {0.0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0, 3.2, 3.4, 3.6, 3.8, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 18.0, 20.0, 22.0, 24.0, 26.0, 28.0, 30.0, 32.0, 34.0, 36.0, 40.0, 45.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0, 110.0, 120.0, 130.0, 140.0, 150.0, 160.0, 180.0, 200.0};
    Double_t* binsPt = new Double_t[82];
    for (int i=0; i<82; i++) {binsPt[i] = bins[i];}
    fdNdPtAnalysis->SetBinsPt(ptNbins, binsPt);
    fdNdPtAnalysis->SetBinsPtCorr(ptNbins, binsPt);
    fdNdPtAnalysis->SetBinsMult(multNbins, binsMult);

       // y shift -0.465409
    const Int_t EtaNbins = 30;
    Double_t binse[31] = {-1.465409,-1.365409,-1.265409,-1.165409,-1.065409,-0.965409,-0.865409,-0.765409,-0.665409,-0.565409,-0.465409,-0.365409,-0.265409,-0.165409,-0.065409,0.034591,0.134591,0.234591,0.334591,0.434591,0.534591,0.634591,0.734591,0.834591,0.934591,1.034591,1.134591,1.234591,1.334591,1.434591,1.534591};
        Double_t* binsEta = new Double_t[31];
    for (int i=0; i<31; i++) {binsEta[i] = binse[i];}
    fdNdPtAnalysis->SetBinsEta(EtaNbins,binsEta);

    // set centrality estimator
   // fdNdPtAnalysis->SetCentralityEstimators("NPA");

  // Add analysis object
  task->AddAnalysisObject( fdNdPtAnalysis );

  // Add task
  mgr->AddTask(task);

  // Create containers for input
  AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();

  TString outputFileName = AliAnalysisManager::GetCommonFileName();

//  AliAnalysisDataContainer *coutput = mgr->CreateContainer("jgronef_dNdPtpPb_TPCITS", TList::Class(), AliAnalysisManager::kOutputContainer, "jgronef_dNdPtpPb_TPCITS.root");   //    <-- Old Way works on Batch

   AliAnalysisDataContainer *coutput = mgr->CreateContainer("dNdPtpPb", TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s:dNdPtHistos", mgr->GetCommonFileName())); //    <-- New Way changed to work on Grid

  mgr->ConnectInput(task, 0, cinput);
  mgr->ConnectOutput(task, 1, coutput);

  /*
   //                                                         Aus Phillips Macro kopiert:

   // Add task
   mgr->AddTask(task);

   // Create containers for input
   AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();

   TString outputFileName = AliAnalysisManager::GetCommonFileName();

   AliAnalysisDataContainer *coutput  = mgr->CreateContainer("dNdPtPbPb",
							     TList::Class(),
							     AliAnalysisManager::kOutputContainer,
							     Form("%s:dNdPtHistos", mgr->GetCommonFileName()));

							     mgr->ConnectInput(task, 0, cinput);
							     mgr->ConnectOutput(task, 1, coutput);

							    */

}

<commit_msg>added option in AddTask to change the container name, needed for LEGO Trains<commit_after>void AddTask_dNdPtpPb(UInt_t uTriggerMask = AliVEvent::kINT7, Int_t iCutMode = 2014, char *contName = "dNdPtpPb" )
{
/*
CheckLoadLibrary("libPWG0base");
CheckLoadLibrary("libPWG0dep");
CheckLoadLibrary("libPWG0selectors");
*/

  //Get current Analysis Manager
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();

  if (!mgr) {
    Error("AddTask_dNdPtAnalysis_TPCITS", "No analysis manager found.");
    return 0;
  }

  // Switch off all AliInfo (too much output!!!)
//  AliLog::SetGlobalLogLevel(AliLog::kError);
//  mgr->SetDebugLevel(0);

  //
  // Create event cuts
  //
  Float_t zvWindow = 30. ;

  AlidNdPtEventCuts *evtCuts = new AlidNdPtEventCuts("AlidNdPtEventCuts","Event cuts");
  evtCuts->SetZvRange(-zvWindow,zvWindow);
  evtCuts->SetMeanXYZv(0.0,0.0,0.0);
  evtCuts->SetSigmaMeanXYZv(1.0,1.0,10.0);
  evtCuts->SetTriggerRequired(kTRUE);
  //evtCuts->SetTriggerRequired(kFALSE);

  //
  // Create geom. acceptance cuts
  //
  //Float_t etaWindow = 1.0;
  eta1 = -0.765409; eta2 = -0.165409;
  Float_t ptMin = 0.1 ;

  AlidNdPtAcceptanceCuts *accCuts = new AlidNdPtAcceptanceCuts("AlidNdPtAcceptanceCuts","Geom. acceptance cuts");
  accCuts->SetEtaRange(eta1,eta2);
  accCuts->SetPtRange(ptMin,1.e10);

  //
  // Create standard esd track cuts
  //
  Int_t cutMode = iCutMode;

  gROOT->LoadMacro("$ALICE_ROOT/PWGLF/SPECTRA/ChargedHadrons/dNdPt/macros/CreatedNdPtTrackCuts.C");
  //gROOT->LoadMacro("./CreatedNdPtTrackCuts.C");
  AliESDtrackCuts* esdTrackCuts = CreatedNdPtTrackCuts(cutMode);
  if (!esdTrackCuts) {
    printf("ERROR: esdTrackCuts could not be created\n")
    return;
  } else {
    //esdTrackCuts->SetHistogramsOn(kTRUE);
    esdTrackCuts->SetHistogramsOn(kTRUE);
  }

  Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0);

  //
  // Create task
  //
  AlidNdPtTask *task = new AlidNdPtTask("AlidNdPtTask_TPCITS");
  task->SetUseMCInfo(hasMC);

  // trigger
  task->SelectCollisionCandidates(uTriggerMask);

  //
  // set analysis options from the Helper here !!!
  //

  //AliTriggerAnalysis::Trigger trigger = AliTriggerAnalysis::kMB1;
  AlidNdPtHelper::AnalysisMode analysisMode = AlidNdPtHelper::kTPCITS;
  AlidNdPtHelper::ParticleMode particleMode = AlidNdPtHelper::kAllPart ;

  //
  // Create analysis object
  //

  AlidNdPtAnalysispPb *fdNdPtAnalysis = new AlidNdPtAnalysispPb("dNdPtAnalysis_TPCITS","dN/dPt Analysis with TPC-ITS tracking");//Now AnalysispPb before: Analzsiis
  fdNdPtAnalysis->SetEventCuts(evtCuts);
  fdNdPtAnalysis->SetAcceptanceCuts(accCuts);
  fdNdPtAnalysis->SetTrackCuts(esdTrackCuts);
  //fdNdPtAnalysis->SetBackgroundCuts(backCuts);
  fdNdPtAnalysis->SetAnalysisMode(analysisMode);
  fdNdPtAnalysis->SetParticleMode(particleMode);

  //j kCINT5 should work for 2012 data, kINT7 for 2013

  //fdNdPtAnalysis->SetTrigger(trigger);
 // fdNdPtAnalysis->SetTriggerMask(AliVEvent::kCINT5);
  fdNdPtAnalysis->SetTriggerMask(uTriggerMask);
  //fdNdPtAnalysis->SetTriggerMask(AliVEvent::kEMC1);
  if(hasMC)
  {
    //physTrigSel->SetAnalyzeMC();
    //fdNdPtAnalysis->SetPhysicsTriggerSelection(physTrigSel);

    fdNdPtAnalysis->SetUseMCInfo(kTRUE);
    fdNdPtAnalysis->SetHistogramsOn(kTRUE);
    //fdNdPtAnalysis->SetHistogramsOn(kFALSE);
  }
  else { // online trigger
//     physTrigSel->SetUseBXNumbers();
//     physTrigSel->SetComputeBG();
//     fdNdPtAnalysis->SetPhysicsTriggerSelection(physTrigSel);
  }

    // change binning
    Int_t multNbins = 152;
    Double_t binsMult[153];
    for (int i=0; i<=multNbins; i++) { binsMult[i] = -0.5 + i; }
    binsMult[152] = 1000.;
    // change binning
    const Int_t ptNbins = 81;
    Double_t bins[82] = {0.0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0, 3.2, 3.4, 3.6, 3.8, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 18.0, 20.0, 22.0, 24.0, 26.0, 28.0, 30.0, 32.0, 34.0, 36.0, 40.0, 45.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0, 110.0, 120.0, 130.0, 140.0, 150.0, 160.0, 180.0, 200.0};
    Double_t* binsPt = new Double_t[82];
    for (int i=0; i<82; i++) {binsPt[i] = bins[i];}
    fdNdPtAnalysis->SetBinsPt(ptNbins, binsPt);
    fdNdPtAnalysis->SetBinsPtCorr(ptNbins, binsPt);
    fdNdPtAnalysis->SetBinsMult(multNbins, binsMult);

       // y shift -0.465409
    const Int_t EtaNbins = 30;
    Double_t binse[31] = {-1.465409,-1.365409,-1.265409,-1.165409,-1.065409,-0.965409,-0.865409,-0.765409,-0.665409,-0.565409,-0.465409,-0.365409,-0.265409,-0.165409,-0.065409,0.034591,0.134591,0.234591,0.334591,0.434591,0.534591,0.634591,0.734591,0.834591,0.934591,1.034591,1.134591,1.234591,1.334591,1.434591,1.534591};
        Double_t* binsEta = new Double_t[31];
    for (int i=0; i<31; i++) {binsEta[i] = binse[i];}
    fdNdPtAnalysis->SetBinsEta(EtaNbins,binsEta);

    // set centrality estimator
   // fdNdPtAnalysis->SetCentralityEstimators("NPA");

  // Add analysis object
  task->AddAnalysisObject( fdNdPtAnalysis );

  // Add task
  mgr->AddTask(task);

  // Create containers for input
  AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();

  TString outputFileName = AliAnalysisManager::GetCommonFileName();

//  AliAnalysisDataContainer *coutput = mgr->CreateContainer("jgronef_dNdPtpPb_TPCITS", TList::Class(), AliAnalysisManager::kOutputContainer, "jgronef_dNdPtpPb_TPCITS.root");   //    <-- Old Way works on Batch

   AliAnalysisDataContainer *coutput = mgr->CreateContainer(Form("%s", contName), TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s:dNdPtHistos", mgr->GetCommonFileName())); //    <-- New Way changed to work on Grid

  mgr->ConnectInput(task, 0, cinput);
  mgr->ConnectOutput(task, 1, coutput);

  /*
   //                                                         Aus Phillips Macro kopiert:

   // Add task
   mgr->AddTask(task);

   // Create containers for input
   AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();

   TString outputFileName = AliAnalysisManager::GetCommonFileName();

   AliAnalysisDataContainer *coutput  = mgr->CreateContainer("dNdPtPbPb",
							     TList::Class(),
							     AliAnalysisManager::kOutputContainer,
							     Form("%s:dNdPtHistos", mgr->GetCommonFileName()));

							     mgr->ConnectInput(task, 0, cinput);
							     mgr->ConnectOutput(task, 1, coutput);

							    */

}

<|endoftext|>


<commit_before>#include <cstring>

#include "conf.hh"
#include "io.hh"
#include "Unigrams.hh"
#include "Bigrams.hh"

using namespace std;

int main(int argc, char* argv[]) {

    string vocab_fname;
    string trans_fname;
    int maxlen;
    map<string, flt_type> vocab;
    StringSet *ss_vocab = NULL;
    transitions_t transitions;
    flt_type one_char_min_lp = -500.0;
    bool unigram = true;

    conf::Config config;
    config("usage: segtext [OPTION...] INPUT OUTPUT\n")
      ('h', "help", "", "", "display help")
      ('v', "vocabulary=FILE", "arg", "", "Unigram model file")
      ('t', "transitions=FILE", "arg", "", "Bigram model file")
      ('8', "utf-8", "", "", "Utf-8 character encoding in use");
    config.default_parse(argc, argv);
    if (config.arguments.size() != 2) config.print_help(stderr, 1);

    bool word_boundaries = config["word-boundaries"].specified;
    bool utf8_encoding = config["utf-8"].specified;
    string in_fname = config.arguments[0];
    string out_fname = config.arguments[1];

    if (!config["vocabulary"].specified && !config["transitions"].specified) {
        cerr << "Please define vocabulary or transitions" << endl;
        exit(EXIT_FAILURE);
    }

    if (config["vocabulary"].specified && config["transitions"].specified) {
        cerr << "Please don't define both vocabulary and transitions" << endl;
        exit(EXIT_FAILURE);
    }

    if (config["vocabulary"].specified) {
        vocab_fname = config["vocabulary"].get_str();
        cerr << "Reading vocabulary " << vocab_fname << endl;
        int retval = Unigrams::read_vocab(vocab_fname, vocab, maxlen, utf8_encoding);
        if (retval < 0) {
            cerr << "something went wrong reading vocabulary" << endl;
            exit(EXIT_FAILURE);
        }
        cerr << "\t" << "size: " << vocab.size() << endl;
        cerr << "\t" << "maximum string length: " << maxlen << endl;
        ss_vocab = new StringSet(vocab);
    }

    if (config["transitions"].specified) {
        unigram = false;
        trans_fname = config["transitions"].get_str();
        cerr << "Reading transitions " << trans_fname << endl;
        int retval = Bigrams::read_transitions(transitions, trans_fname);
        Bigrams::trans_to_vocab(transitions, vocab);
        ss_vocab = new StringSet(vocab);
        if (retval < 0) {
            cerr << "something went wrong reading transitions" << endl;
            exit(EXIT_FAILURE);
        }
        cerr << "\t" << "vocabulary size: " << transitions.size() << endl;
        cerr << "\t" << "transitions: " << retval << endl;
    }

    cerr << "Segmenting corpus" << endl;
    SimpleFileInput infile(in_fname);
    SimpleFileOutput outfile(out_fname);

    string line;
    while (infile.getline(line)) {

        for (unsigned int i=0; i<line.size(); i++) {
            string currchr {line[i]};
            if (!ss_vocab->includes(currchr))
                ss_vocab->add(currchr, one_char_min_lp);
        }

        vector<string> best_path;
        if (unigram)
            viterbi(*ss_vocab, line, best_path, true, utf8_encoding);
        else {
            FactorGraph fg(line, start_end_symbol, *ss_vocab);
            viterbi(transitions, fg, best_path);
            best_path.erase(best_path.begin());
            best_path.erase(best_path.end());
        }

        if (best_path.size() == 0) {
            cerr << "warning, no segmentation for line: " << line << endl;
            continue;
        }

        for (unsigned int i=0; i<best_path.size(); i++) {
            if (best_path[i] == " ")
                outfile << "\t";
            else {
                if (i>0) outfile << " ";
                outfile << best_path[i];
            }
        }
        outfile << "\n";
    }

    outfile.close();
    if (ss_vocab != NULL) delete ss_vocab;
    exit(EXIT_SUCCESS);
}
<commit_msg>Utf-8 fix for including all one char subwords to vocab.<commit_after>#include <cstring>

#include "conf.hh"
#include "io.hh"
#include "Unigrams.hh"
#include "Bigrams.hh"

using namespace std;

int main(int argc, char* argv[]) {

    string vocab_fname;
    string trans_fname;
    int maxlen;
    map<string, flt_type> vocab;
    StringSet *ss_vocab = NULL;
    transitions_t transitions;
    flt_type one_char_min_lp = -50.0;
    bool unigram = true;

    conf::Config config;
    config("usage: segtext [OPTION...] INPUT OUTPUT\n")
      ('h', "help", "", "", "display help")
      ('v', "vocabulary=FILE", "arg", "", "Unigram model file")
      ('t', "transitions=FILE", "arg", "", "Bigram model file")
      ('8', "utf-8", "", "", "Utf-8 character encoding in use");
    config.default_parse(argc, argv);
    if (config.arguments.size() != 2) config.print_help(stderr, 1);

    bool utf8_encoding = config["utf-8"].specified;
    string in_fname = config.arguments[0];
    string out_fname = config.arguments[1];

    if (!config["vocabulary"].specified && !config["transitions"].specified) {
        cerr << "Please define vocabulary or transitions" << endl;
        exit(EXIT_FAILURE);
    }

    if (config["vocabulary"].specified && config["transitions"].specified) {
        cerr << "Please don't define both vocabulary and transitions" << endl;
        exit(EXIT_FAILURE);
    }

    if (config["vocabulary"].specified) {
        vocab_fname = config["vocabulary"].get_str();
        cerr << "Reading vocabulary " << vocab_fname << endl;
        int retval = Unigrams::read_vocab(vocab_fname, vocab, maxlen, utf8_encoding);
        if (retval < 0) {
            cerr << "something went wrong reading vocabulary" << endl;
            exit(EXIT_FAILURE);
        }
        cerr << "\t" << "size: " << vocab.size() << endl;
        cerr << "\t" << "maximum string length: " << maxlen << endl;
        ss_vocab = new StringSet(vocab);
    }

    if (config["transitions"].specified) {
        unigram = false;
        trans_fname = config["transitions"].get_str();
        cerr << "Reading transitions " << trans_fname << endl;
        int retval = Bigrams::read_transitions(transitions, trans_fname);
        Bigrams::trans_to_vocab(transitions, vocab);
        ss_vocab = new StringSet(vocab);
        if (retval < 0) {
            cerr << "something went wrong reading transitions" << endl;
            exit(EXIT_FAILURE);
        }
        cerr << "\t" << "vocabulary size: " << transitions.size() << endl;
        cerr << "\t" << "transitions: " << retval << endl;
    }

    cerr << "Segmenting corpus" << endl;
    SimpleFileInput infile(in_fname);
    SimpleFileOutput outfile(out_fname);

    string line;
    while (infile.getline(line)) {

        vector<unsigned int> char_positions;
        get_character_positions(line, char_positions, utf8_encoding);
        for (unsigned int i=0; i<char_positions.size()-1; i++) {
            unsigned int start_pos = char_positions[i];
            unsigned int end_pos = char_positions[i+1];
            string currchr = line.substr(start_pos, end_pos-start_pos);
            if (!ss_vocab->includes(currchr))
                ss_vocab->add(currchr, one_char_min_lp);
        }

        vector<string> best_path;
        if (unigram)
            viterbi(*ss_vocab, line, best_path, true, utf8_encoding);
        else {
            FactorGraph fg(line, start_end_symbol, *ss_vocab);
            viterbi(transitions, fg, best_path);
            best_path.erase(best_path.begin());
            best_path.erase(best_path.end());
        }

        if (best_path.size() == 0) {
            cerr << "warning, no segmentation for line: " << line << endl;
            continue;
        }

        for (unsigned int i=0; i<best_path.size(); i++) {
            if (best_path[i] == " ")
                outfile << "\t";
            else {
                if (i>0) outfile << " ";
                outfile << best_path[i];
            }
        }
        outfile << "\n";
    }

    outfile.close();
    if (ss_vocab != NULL) delete ss_vocab;
    exit(EXIT_SUCCESS);
}
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

/**
 * @file
 **/

#include "modules/planning/tasks/speed_decider/speed_decider.h"

#include <algorithm>
#include <string>
#include <utility>
#include <vector>

#include "modules/planning/proto/decision.pb.h"

#include "modules/common/configs/vehicle_config_helper.h"
#include "modules/common/log.h"
#include "modules/common/util/util.h"
#include "modules/planning/common/planning_gflags.h"

namespace apollo {
namespace planning {

using apollo::common::ErrorCode;
using apollo::common::Status;
using common::math::Vec2d;

SpeedDecider::SpeedDecider() : Task("SpeedDecider") {}

bool SpeedDecider::Init(const PlanningConfig& config) {
  dp_st_speed_config_ = config.em_planner_config().dp_st_speed_config();
  st_boundary_config_ = dp_st_speed_config_.st_boundary_config();
  return true;
}

apollo::common::Status SpeedDecider::Execute(
    Frame* frame, ReferenceLineInfo* reference_line_info) {
  Task::Execute(frame, reference_line_info);
  init_point_ = frame_->PlanningStartPoint();
  adc_sl_boundary_ = reference_line_info_->AdcSlBoundary();
  reference_line_ = &reference_line_info_->reference_line();
  if (!MakeObjectDecision(reference_line_info->speed_data(),
                          reference_line_info->path_decision())
           .ok()) {
    const std::string msg = "Get object decision by speed profile failed.";
    AERROR << msg;
    return Status(ErrorCode::PLANNING_ERROR, msg);
  }
  return Status::OK();
}

SpeedDecider::StPosition SpeedDecider::GetStPosition(
    const SpeedData& speed_profile, const StBoundary& st_boundary) const {
  StPosition st_position = BELOW;
  const double start_t = st_boundary.min_t();
  const double end_t = st_boundary.max_t();
  for (const auto& speed_point : speed_profile.speed_vector()) {
    if (speed_point.t() < start_t) {
      continue;
    }
    if (speed_point.t() > end_t) {
      break;
    }

    STPoint st_point(speed_point.s(), speed_point.t());
    if (st_boundary.IsPointInBoundary(st_point)) {
      const std::string msg =
          "dp_st_graph failed: speed profile cross st_boundaries.";
      AERROR << msg;
      st_position = CROSS;
      return st_position;
    }

    double s_upper = reference_line_info_->reference_line().Length() -
                     reference_line_info_->AdcSlBoundary().end_s();
    double s_lower = 0.0;
    if (st_boundary.GetBoundarySRange(speed_point.t(), &s_upper, &s_lower)) {
      if (s_lower > speed_point.s()) {
        st_position = BELOW;
      } else if (s_upper < speed_point.s()) {
        st_position = ABOVE;
      }
    }
  }
  return st_position;
}

bool SpeedDecider::IsFollowTooClose(const PathObstacle& path_obstacle) const {
  if (!path_obstacle.IsBlockingObstacle()) {
    return false;
  }

  if (path_obstacle.st_boundary().min_t() > 0.0) {
    return false;
  }
  const double obs_speed = path_obstacle.obstacle()->Speed();
  const double ego_speed = init_point_.v();
  if (obs_speed > ego_speed) {
    return false;
  }
  const double distance = path_obstacle.st_boundary().min_s();
  constexpr double decel = 1.0;
  return distance < std::pow((ego_speed - obs_speed), 2) * 0.5 / decel;
}

Status SpeedDecider::MakeObjectDecision(
    const SpeedData& speed_profile, PathDecision* const path_decision) const {
  if (speed_profile.speed_vector().size() < 2) {
    const std::string msg = "dp_st_graph failed to get speed profile.";
    AERROR << msg;
    return Status(ErrorCode::PLANNING_ERROR, msg);
  }
  for (const auto* obstacle : path_decision->path_obstacles().Items()) {
    auto* path_obstacle = path_decision->Find(obstacle->Id());
    const auto& boundary = path_obstacle->st_boundary();
    if (boundary.IsEmpty() || boundary.max_s() < 0.0 ||
        boundary.max_t() < 0.0) {
      AppendIgnoreDecision(path_obstacle);
      continue;
    }
    if (path_obstacle->HasLongitudinalDecision()) {
      AppendIgnoreDecision(path_obstacle);
      continue;
    }

    auto position = GetStPosition(speed_profile, boundary);
    switch (position) {
      case BELOW:
        if (boundary.boundary_type() == StBoundary::BoundaryType::KEEP_CLEAR) {
          ObjectDecisionType stop_decision;
          if (CreateStopDecision(*path_obstacle, &stop_decision,
                                 -FLAGS_stop_distance_traffic_light)) {
            path_obstacle->AddLongitudinalDecision("dp_st_graph/keep_clear",
                                                   stop_decision);
          }
        } else if (CheckIsFollowByT(boundary) &&
                   (boundary.max_t() - boundary.min_t() >
                    FLAGS_follow_min_time_sec)) {
          // stop for low_speed decelerating
          if (IsFollowTooClose(*path_obstacle)) {
            ObjectDecisionType stop_decision;
            if (CreateStopDecision(*path_obstacle, &stop_decision,
                                   -FLAGS_min_stop_distance_obstacle)) {
              path_obstacle->AddLongitudinalDecision("dp_st_graph/too_close",
                                                     stop_decision);
            }
          } else {  // high speed or low speed accelerating
            // FOLLOW decision
            ObjectDecisionType follow_decision;
            if (CreateFollowDecision(*path_obstacle, &follow_decision)) {
              path_obstacle->AddLongitudinalDecision("dp_st_graph",
                                                     follow_decision);
            }
          }
        } else {
          // YIELD decision
          ObjectDecisionType yield_decision;
          if (CreateYieldDecision(boundary, &yield_decision)) {
            path_obstacle->AddLongitudinalDecision("dp_st_graph",
                                                   yield_decision);
          }
        }
        break;
      case ABOVE:
        if (boundary.boundary_type() == StBoundary::BoundaryType::KEEP_CLEAR) {
          ObjectDecisionType ignore;
          ignore.mutable_ignore();
          path_obstacle->AddLongitudinalDecision("dp_st_graph", ignore);

        } else {
          // OVERTAKE decision
          ObjectDecisionType overtake_decision;
          if (CreateOvertakeDecision(*path_obstacle, &overtake_decision)) {
            path_obstacle->AddLongitudinalDecision("dp_st_graph",
                                                   overtake_decision);
          }
        }
        break;
      case CROSS: {
        ObjectDecisionType stop_decision;
        if (CreateStopDecision(*path_obstacle, &stop_decision,
                               -FLAGS_min_stop_distance_obstacle)) {
          path_obstacle->AddLongitudinalDecision("dp_st_graph", stop_decision);
        }
      } break;
      default:
        AERROR << "Unknown position:" << position;
    }
    AppendIgnoreDecision(path_obstacle);
  }
  return Status::OK();
}

void SpeedDecider::AppendIgnoreDecision(PathObstacle* path_obstacle) const {
  ObjectDecisionType ignore_decision;
  ignore_decision.mutable_ignore();
  if (!path_obstacle->HasLongitudinalDecision()) {
    path_obstacle->AddLongitudinalDecision("dp_st_graph", ignore_decision);
  }
  if (!path_obstacle->HasLateralDecision()) {
    path_obstacle->AddLateralDecision("dp_st_graph", ignore_decision);
  }
}

bool SpeedDecider::CreateStopDecision(const PathObstacle& path_obstacle,
                                      ObjectDecisionType* const stop_decision,
                                      double stop_distance) const {
  const auto& boundary = path_obstacle.st_boundary();
  auto* stop = stop_decision->mutable_stop();
  stop->set_distance_s(stop_distance);
  const double fence_s =
      adc_sl_boundary_.end_s() + boundary.min_s() + stop_distance;

  const double main_stop_s =
      reference_line_info_->path_decision()->stop_reference_line_s();
  if (main_stop_s < fence_s) {
    ADEBUG << "Stop fence is further away, ignore.";
    return false;
  }

  const auto fence_point = reference_line_->GetReferencePoint(fence_s);
  auto* stop_point = stop->mutable_stop_point();
  stop_point->set_x(fence_point.x());
  stop_point->set_y(fence_point.y());
  stop_point->set_z(0.0);
  stop->set_stop_heading(fence_point.heading());
  return true;
}

bool SpeedDecider::CreateFollowDecision(
    const PathObstacle& path_obstacle,
    ObjectDecisionType* const follow_decision) const {
  DCHECK_NOTNULL(follow_decision);
  const auto& boundary = path_obstacle.st_boundary();

  auto* follow = follow_decision->mutable_follow();

  const double follow_speed = init_point_.v();
  const double follow_distance_s = -std::fmax(
      follow_speed * FLAGS_follow_time_buffer, FLAGS_follow_min_distance);

  follow->set_distance_s(follow_distance_s);

  const double reference_s =
      adc_sl_boundary_.end_s() + boundary.min_s() + follow_distance_s;

  const double main_stop_s =
      reference_line_info_->path_decision()->stop_reference_line_s();
  if (main_stop_s < reference_s) {
    ADEBUG << "Follow reference_s is further away, ignore.";
    return false;
  }

  auto ref_point = reference_line_->GetReferencePoint(reference_s);
  auto* fence_point = follow->mutable_fence_point();
  fence_point->set_x(ref_point.x());
  fence_point->set_y(ref_point.y());
  fence_point->set_z(0.0);
  follow->set_fence_heading(ref_point.heading());
  return true;
}

bool SpeedDecider::CreateYieldDecision(
    const StBoundary& boundary,
    ObjectDecisionType* const yield_decision) const {
  auto* yield = yield_decision->mutable_yield();

  // in meters
  const double kMinYieldDistance = FLAGS_yield_min_distance;
  const double yield_distance_s =
      std::max(-boundary.min_s(), -1.0 * kMinYieldDistance);
  yield->set_distance_s(yield_distance_s);

  const double reference_line_fence_s =
      adc_sl_boundary_.end_s() + boundary.min_s() + yield_distance_s;

  const double main_stop_s =
      reference_line_info_->path_decision()->stop_reference_line_s();
  if (main_stop_s < reference_line_fence_s) {
    ADEBUG << "Yield reference_s is further away, ignore.";
    return false;
  }

  auto ref_point = reference_line_->GetReferencePoint(reference_line_fence_s);

  yield->mutable_fence_point()->set_x(ref_point.x());
  yield->mutable_fence_point()->set_y(ref_point.y());
  yield->mutable_fence_point()->set_z(0.0);
  yield->set_fence_heading(ref_point.heading());
  return true;
}

bool SpeedDecider::CreateOvertakeDecision(
    const PathObstacle& path_obstacle,
    ObjectDecisionType* const overtake_decision) const {
  DCHECK_NOTNULL(overtake_decision);
  const auto& boundary = path_obstacle.st_boundary();
  auto* overtake = overtake_decision->mutable_overtake();

  // in seconds
  constexpr double kOvertakeTimeBuffer = 3.0;
  // in meters
  constexpr double kMinOvertakeDistance = 10.0;

  const auto& velocity = path_obstacle.obstacle()->Perception().velocity();
  const double obstacle_speed =
      common::math::Vec2d::CreateUnitVec2d(init_point_.path_point().theta())
          .InnerProd(Vec2d(velocity.x(), velocity.y()));

  const double overtake_distance_s = std::fmax(
      std::fmax(init_point_.v(), obstacle_speed) * kOvertakeTimeBuffer,
      kMinOvertakeDistance);
  overtake->set_distance_s(overtake_distance_s);

  const double reference_line_fence_s =
      adc_sl_boundary_.end_s() + boundary.min_s() + overtake_distance_s;

  const double main_stop_s =
      reference_line_info_->path_decision()->stop_reference_line_s();
  if (main_stop_s < reference_line_fence_s) {
    ADEBUG << "Overtake reference_s is further away, ignore.";
    return false;
  }

  auto ref_point = reference_line_->GetReferencePoint(reference_line_fence_s);
  overtake->mutable_fence_point()->set_x(ref_point.x());
  overtake->mutable_fence_point()->set_y(ref_point.y());
  overtake->mutable_fence_point()->set_z(0.0);
  overtake->set_fence_heading(ref_point.heading());
  return true;
}

bool SpeedDecider::CheckIsFollowByT(const StBoundary& boundary) const {
  if (boundary.BottomLeftPoint().s() > boundary.BottomRightPoint().s()) {
    return false;
  }
  constexpr double kFollowTimeEpsilon = 1e-3;
  constexpr double kFollowCutOffTime = 0.5;
  if (boundary.min_t() > kFollowCutOffTime ||
      boundary.max_t() < kFollowTimeEpsilon) {
    return false;
  }
  return true;
}

}  // namespace planning
}  // namespace apollo
<commit_msg>Planning: consider min follow distance to calculate IsFollowTooClose.<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

/**
 * @file
 **/

#include "modules/planning/tasks/speed_decider/speed_decider.h"

#include <algorithm>
#include <string>
#include <utility>
#include <vector>

#include "modules/planning/proto/decision.pb.h"

#include "modules/common/configs/vehicle_config_helper.h"
#include "modules/common/log.h"
#include "modules/common/util/util.h"
#include "modules/planning/common/planning_gflags.h"

namespace apollo {
namespace planning {

using apollo::common::ErrorCode;
using apollo::common::Status;
using common::math::Vec2d;

SpeedDecider::SpeedDecider() : Task("SpeedDecider") {}

bool SpeedDecider::Init(const PlanningConfig& config) {
  dp_st_speed_config_ = config.em_planner_config().dp_st_speed_config();
  st_boundary_config_ = dp_st_speed_config_.st_boundary_config();
  return true;
}

apollo::common::Status SpeedDecider::Execute(
    Frame* frame, ReferenceLineInfo* reference_line_info) {
  Task::Execute(frame, reference_line_info);
  init_point_ = frame_->PlanningStartPoint();
  adc_sl_boundary_ = reference_line_info_->AdcSlBoundary();
  reference_line_ = &reference_line_info_->reference_line();
  if (!MakeObjectDecision(reference_line_info->speed_data(),
                          reference_line_info->path_decision())
           .ok()) {
    const std::string msg = "Get object decision by speed profile failed.";
    AERROR << msg;
    return Status(ErrorCode::PLANNING_ERROR, msg);
  }
  return Status::OK();
}

SpeedDecider::StPosition SpeedDecider::GetStPosition(
    const SpeedData& speed_profile, const StBoundary& st_boundary) const {
  StPosition st_position = BELOW;
  const double start_t = st_boundary.min_t();
  const double end_t = st_boundary.max_t();
  for (const auto& speed_point : speed_profile.speed_vector()) {
    if (speed_point.t() < start_t) {
      continue;
    }
    if (speed_point.t() > end_t) {
      break;
    }

    STPoint st_point(speed_point.s(), speed_point.t());
    if (st_boundary.IsPointInBoundary(st_point)) {
      const std::string msg =
          "dp_st_graph failed: speed profile cross st_boundaries.";
      AERROR << msg;
      st_position = CROSS;
      return st_position;
    }

    double s_upper = reference_line_info_->reference_line().Length() -
                     reference_line_info_->AdcSlBoundary().end_s();
    double s_lower = 0.0;
    if (st_boundary.GetBoundarySRange(speed_point.t(), &s_upper, &s_lower)) {
      if (s_lower > speed_point.s()) {
        st_position = BELOW;
      } else if (s_upper < speed_point.s()) {
        st_position = ABOVE;
      }
    }
  }
  return st_position;
}

bool SpeedDecider::IsFollowTooClose(const PathObstacle& path_obstacle) const {
  if (!path_obstacle.IsBlockingObstacle()) {
    return false;
  }

  if (path_obstacle.st_boundary().min_t() > 0.0) {
    return false;
  }
  const double obs_speed = path_obstacle.obstacle()->Speed();
  const double ego_speed = init_point_.v();
  if (obs_speed > ego_speed) {
    return false;
  }
  const double distance =
      path_obstacle.st_boundary().min_s() - FLAGS_min_stop_distance_obstacle;
  constexpr double decel = 1.0;
  return distance < std::pow((ego_speed - obs_speed), 2) * 0.5 / decel;
}

Status SpeedDecider::MakeObjectDecision(
    const SpeedData& speed_profile, PathDecision* const path_decision) const {
  if (speed_profile.speed_vector().size() < 2) {
    const std::string msg = "dp_st_graph failed to get speed profile.";
    AERROR << msg;
    return Status(ErrorCode::PLANNING_ERROR, msg);
  }
  for (const auto* obstacle : path_decision->path_obstacles().Items()) {
    auto* path_obstacle = path_decision->Find(obstacle->Id());
    const auto& boundary = path_obstacle->st_boundary();
    if (boundary.IsEmpty() || boundary.max_s() < 0.0 ||
        boundary.max_t() < 0.0) {
      AppendIgnoreDecision(path_obstacle);
      continue;
    }
    if (path_obstacle->HasLongitudinalDecision()) {
      AppendIgnoreDecision(path_obstacle);
      continue;
    }

    auto position = GetStPosition(speed_profile, boundary);
    switch (position) {
      case BELOW:
        if (boundary.boundary_type() == StBoundary::BoundaryType::KEEP_CLEAR) {
          ObjectDecisionType stop_decision;
          if (CreateStopDecision(*path_obstacle, &stop_decision,
                                 -FLAGS_stop_distance_traffic_light)) {
            path_obstacle->AddLongitudinalDecision("dp_st_graph/keep_clear",
                                                   stop_decision);
          }
        } else if (CheckIsFollowByT(boundary) &&
                   (boundary.max_t() - boundary.min_t() >
                    FLAGS_follow_min_time_sec)) {
          // stop for low_speed decelerating
          if (IsFollowTooClose(*path_obstacle)) {
            ObjectDecisionType stop_decision;
            if (CreateStopDecision(*path_obstacle, &stop_decision,
                                   -FLAGS_min_stop_distance_obstacle)) {
              path_obstacle->AddLongitudinalDecision("dp_st_graph/too_close",
                                                     stop_decision);
            }
          } else {  // high speed or low speed accelerating
            // FOLLOW decision
            ObjectDecisionType follow_decision;
            if (CreateFollowDecision(*path_obstacle, &follow_decision)) {
              path_obstacle->AddLongitudinalDecision("dp_st_graph",
                                                     follow_decision);
            }
          }
        } else {
          // YIELD decision
          ObjectDecisionType yield_decision;
          if (CreateYieldDecision(boundary, &yield_decision)) {
            path_obstacle->AddLongitudinalDecision("dp_st_graph",
                                                   yield_decision);
          }
        }
        break;
      case ABOVE:
        if (boundary.boundary_type() == StBoundary::BoundaryType::KEEP_CLEAR) {
          ObjectDecisionType ignore;
          ignore.mutable_ignore();
          path_obstacle->AddLongitudinalDecision("dp_st_graph", ignore);

        } else {
          // OVERTAKE decision
          ObjectDecisionType overtake_decision;
          if (CreateOvertakeDecision(*path_obstacle, &overtake_decision)) {
            path_obstacle->AddLongitudinalDecision("dp_st_graph",
                                                   overtake_decision);
          }
        }
        break;
      case CROSS: {
        ObjectDecisionType stop_decision;
        if (CreateStopDecision(*path_obstacle, &stop_decision,
                               -FLAGS_min_stop_distance_obstacle)) {
          path_obstacle->AddLongitudinalDecision("dp_st_graph", stop_decision);
        }
      } break;
      default:
        AERROR << "Unknown position:" << position;
    }
    AppendIgnoreDecision(path_obstacle);
  }
  return Status::OK();
}

void SpeedDecider::AppendIgnoreDecision(PathObstacle* path_obstacle) const {
  ObjectDecisionType ignore_decision;
  ignore_decision.mutable_ignore();
  if (!path_obstacle->HasLongitudinalDecision()) {
    path_obstacle->AddLongitudinalDecision("dp_st_graph", ignore_decision);
  }
  if (!path_obstacle->HasLateralDecision()) {
    path_obstacle->AddLateralDecision("dp_st_graph", ignore_decision);
  }
}

bool SpeedDecider::CreateStopDecision(const PathObstacle& path_obstacle,
                                      ObjectDecisionType* const stop_decision,
                                      double stop_distance) const {
  const auto& boundary = path_obstacle.st_boundary();
  auto* stop = stop_decision->mutable_stop();
  stop->set_distance_s(stop_distance);
  const double fence_s =
      adc_sl_boundary_.end_s() + boundary.min_s() + stop_distance;

  const double main_stop_s =
      reference_line_info_->path_decision()->stop_reference_line_s();
  if (main_stop_s < fence_s) {
    ADEBUG << "Stop fence is further away, ignore.";
    return false;
  }

  const auto fence_point = reference_line_->GetReferencePoint(fence_s);
  auto* stop_point = stop->mutable_stop_point();
  stop_point->set_x(fence_point.x());
  stop_point->set_y(fence_point.y());
  stop_point->set_z(0.0);
  stop->set_stop_heading(fence_point.heading());
  return true;
}

bool SpeedDecider::CreateFollowDecision(
    const PathObstacle& path_obstacle,
    ObjectDecisionType* const follow_decision) const {
  DCHECK_NOTNULL(follow_decision);
  const auto& boundary = path_obstacle.st_boundary();

  auto* follow = follow_decision->mutable_follow();

  const double follow_speed = init_point_.v();
  const double follow_distance_s = -std::fmax(
      follow_speed * FLAGS_follow_time_buffer, FLAGS_follow_min_distance);

  follow->set_distance_s(follow_distance_s);

  const double reference_s =
      adc_sl_boundary_.end_s() + boundary.min_s() + follow_distance_s;

  const double main_stop_s =
      reference_line_info_->path_decision()->stop_reference_line_s();
  if (main_stop_s < reference_s) {
    ADEBUG << "Follow reference_s is further away, ignore.";
    return false;
  }

  auto ref_point = reference_line_->GetReferencePoint(reference_s);
  auto* fence_point = follow->mutable_fence_point();
  fence_point->set_x(ref_point.x());
  fence_point->set_y(ref_point.y());
  fence_point->set_z(0.0);
  follow->set_fence_heading(ref_point.heading());
  return true;
}

bool SpeedDecider::CreateYieldDecision(
    const StBoundary& boundary,
    ObjectDecisionType* const yield_decision) const {
  auto* yield = yield_decision->mutable_yield();

  // in meters
  const double kMinYieldDistance = FLAGS_yield_min_distance;
  const double yield_distance_s =
      std::max(-boundary.min_s(), -1.0 * kMinYieldDistance);
  yield->set_distance_s(yield_distance_s);

  const double reference_line_fence_s =
      adc_sl_boundary_.end_s() + boundary.min_s() + yield_distance_s;

  const double main_stop_s =
      reference_line_info_->path_decision()->stop_reference_line_s();
  if (main_stop_s < reference_line_fence_s) {
    ADEBUG << "Yield reference_s is further away, ignore.";
    return false;
  }

  auto ref_point = reference_line_->GetReferencePoint(reference_line_fence_s);

  yield->mutable_fence_point()->set_x(ref_point.x());
  yield->mutable_fence_point()->set_y(ref_point.y());
  yield->mutable_fence_point()->set_z(0.0);
  yield->set_fence_heading(ref_point.heading());
  return true;
}

bool SpeedDecider::CreateOvertakeDecision(
    const PathObstacle& path_obstacle,
    ObjectDecisionType* const overtake_decision) const {
  DCHECK_NOTNULL(overtake_decision);
  const auto& boundary = path_obstacle.st_boundary();
  auto* overtake = overtake_decision->mutable_overtake();

  // in seconds
  constexpr double kOvertakeTimeBuffer = 3.0;
  // in meters
  constexpr double kMinOvertakeDistance = 10.0;

  const auto& velocity = path_obstacle.obstacle()->Perception().velocity();
  const double obstacle_speed =
      common::math::Vec2d::CreateUnitVec2d(init_point_.path_point().theta())
          .InnerProd(Vec2d(velocity.x(), velocity.y()));

  const double overtake_distance_s = std::fmax(
      std::fmax(init_point_.v(), obstacle_speed) * kOvertakeTimeBuffer,
      kMinOvertakeDistance);
  overtake->set_distance_s(overtake_distance_s);

  const double reference_line_fence_s =
      adc_sl_boundary_.end_s() + boundary.min_s() + overtake_distance_s;

  const double main_stop_s =
      reference_line_info_->path_decision()->stop_reference_line_s();
  if (main_stop_s < reference_line_fence_s) {
    ADEBUG << "Overtake reference_s is further away, ignore.";
    return false;
  }

  auto ref_point = reference_line_->GetReferencePoint(reference_line_fence_s);
  overtake->mutable_fence_point()->set_x(ref_point.x());
  overtake->mutable_fence_point()->set_y(ref_point.y());
  overtake->mutable_fence_point()->set_z(0.0);
  overtake->set_fence_heading(ref_point.heading());
  return true;
}

bool SpeedDecider::CheckIsFollowByT(const StBoundary& boundary) const {
  if (boundary.BottomLeftPoint().s() > boundary.BottomRightPoint().s()) {
    return false;
  }
  constexpr double kFollowTimeEpsilon = 1e-3;
  constexpr double kFollowCutOffTime = 0.5;
  if (boundary.min_t() > kFollowCutOffTime ||
      boundary.max_t() < kFollowTimeEpsilon) {
    return false;
  }
  return true;
}

}  // namespace planning
}  // namespace apollo
<|endoftext|>


<commit_before>#include "S_Temporal_Boss_Room.h"
#include "j1Input.h"
#include "SDL\include\SDL.h"
#include "j1Scene.h"
#include "p2Log.h"
#include "j1App.h"
#include "j1Map.h"
#include "j1Render.h"
#include "j1Textures.h"
#include "j1Pathfinding.h"
#include "j1App.h"
#include "j1Player.h"
#include "j1Camera.h"
#include "j1HUD.h"
#include "j1Enemy.h"
#include"j1Audio.h"
#include"j1GameStartMenuBack.h"
#include "S_InGameMenu.h"
#include "O_ElectricBall.h"
#include"Video.h"

bool S_TempBossRoom::Start()
{
	scene_str = "HYRULE CASTLE";

	App->camera->Enable();
	App->hud->Enable();
	App->collision->Enable();
	App->map->Enable();
	App->player->Enable();
	App->object->Enable();
	App->enemy->Enable();

	App->enemy->Final_Boss = new Boss();
	App->enemy->Final_Boss->im_active = true;
	App->enemy->Final_Boss->is_testing = true;
	//PAUSE FALSE
	App->player->paused = true;
	App->enemy->paused = false;
	App->collision->paused = false;
	App->pathfinding->paused = false;
	SDL_Rect r = { 0,0,1280,720 };
	App->videoplayer->PlayVideo("Boss video.ogv", r);
	App->videoplayer->video_finished = false;

	if (App->map->Load("final_boss_map_advanced.tmx") == true)

	{
		int w, h = 0;
		uchar* data = nullptr;
		if (App->map->CreateWalkabilityMap(w, h, &data))
			App->pathfinding->SetMap(w, h);

		for (uint i = 0; i < App->object->V_Objects.size(); i++) {
			if (App->object->V_Objects[i]->collider_tiles.size() > 0) {
				App->object->CreateColliders(*App->object->V_Objects[i]);
			}
		}

		int w_two, h_two = 0;
		uchar* data_two = nullptr;
		if (App->map->CreateEnemyMap(w_two, h_two, &data_two)) {
			int w_three = 0;
			int h_three = 0;
			uchar* data_three = nullptr;
			if (App->map->CreateEnemyPathMap(w_three, h_three, &data_three)) {
				App->enemy->Enable();
			}
		}
		RELEASE_ARRAY(data);
		//App->map->CreateLogicMap();
	}

	App->render->camera.x = 0;
	App->render->camera.y = 0;

	//App->player->Link->pos = { 660,1400 };
	//App->player->Zelda->pos = { 620,1400 };
	App->player->Link->logic_height = 0;
	App->player->Zelda->logic_height = 0;

	LOG("World Open");
	App->cutscenemanager->StartCutscene(3);
	return false;
}

bool S_TempBossRoom::Update()
{
	for (int i = 0; i < App->object->V_Objects.size(); i++) {
		if (App->object->V_Objects[i]->type == objectType::electric_ball) {
			App->object->V_Objects[i]->texture_rect = App->object->V_Objects[i]->actual_animation.GetCurrentFrame().rect;
		}
	}
	if (App->videoplayer->video_finished && done_video_boss == false)
	{
		App->audio->CleanUp();
		App->audio->Awake(App->config);
		App->audio->Start();
		App->player->paused = false;
		done_video_boss = true;
		App->audio->PlayMusic("audio/music/Final-boss-theme.ogg", 0);
		App->audio->VolumeMusic(100);
	}

	if (!App->player->paused)
		App->enemy->Final_Boss->UpdateLegs();

	return false;
}

bool S_TempBossRoom::PostUpdate()
{
	if (App->videoplayer->video_finished)
	{
		if (App->player->loop_game_menu == true || App->player->half_hearts_test_purpose <= 0) {

			App->scene->ChangeScene(Scene_ID::Send);
			App->startmenuback->Freeze(false);
			App->player->loop_game_menu = false;
			App->player->half_hearts_test_purpose = App->player->hearts_containers_test_purpose * 2;
		}

		for (int i = 0; i < App->object->V_Objects.size(); i++) {
			if (App->object->V_Objects[i]->type == objectType::electric_ball) {
				ElectricBall* temp = (ElectricBall*)App->object->V_Objects[i];
				if (temp->active_phase == 1 && (App->enemy->Final_Boss->actual_phase == boss_phase_2 || App->enemy->Final_Boss->actual_phase == boss_phase_3))
					temp->active = true;
				if (temp->active_phase == 2 && (App->enemy->Final_Boss->actual_phase == boss_phase_3))
					temp->active = true;
			}
		}
		if (App->enemy->Final_Boss != nullptr) {
			if (App->enemy->Final_Boss->boss_defeated) {
				//Play final video
				//if finished App->scene->ChangeScene(Scene_ID::credits);
				App->scene->ChangeScene(Scene_ID::credits);
				App->scene->win_game_variableforshowcredits = true;
			}
		}
	}
	return true;

}

bool S_TempBossRoom::Clean()
{
	if (App->enemy->Final_Boss != NULL) {
		App->enemy->Final_Boss->im_active = false;
		delete App->enemy->Final_Boss;
		App->enemy->Final_Boss = NULL;
	}
	LOG("World Test Deleted");

	App->player->Disable();
	App->enemy->Disable();
	App->map->Disable();
	App->collision->Disable();
	App->hud->Disable();
	App->object->Disable();

	//std::list <TileSet*>::iterator temp = App->map->data.tilesets.begin();

	/*p2List_item<TileSet*>* temp = App->map->data.tilesets.start;
	while (temp != NULL) {
	App->tex->UnLoad(temp->data->texture);
	temp = temp->next;
	}*/

	//This must be revised
	((S_InGameMenu*)App->scene->InGameMenuScene())->active = false;

	return false;
}

bool S_TempBossRoom::Save(pugi::xml_node& node) const
{
	return true;
}

bool S_TempBossRoom::Load(pugi::xml_node& node)
{
	return true;
}<commit_msg>Bug fixed<commit_after>#include "S_Temporal_Boss_Room.h"
#include "j1Input.h"
#include "SDL\include\SDL.h"
#include "j1Scene.h"
#include "p2Log.h"
#include "j1App.h"
#include "j1Map.h"
#include "j1Render.h"
#include "j1Textures.h"
#include "j1Pathfinding.h"
#include "j1App.h"
#include "j1Player.h"
#include "j1Camera.h"
#include "j1HUD.h"
#include "j1Enemy.h"
#include"j1Audio.h"
#include"j1GameStartMenuBack.h"
#include "S_InGameMenu.h"
#include "O_ElectricBall.h"
#include"Video.h"

bool S_TempBossRoom::Start()
{
	scene_str = "HYRULE CASTLE";

	App->camera->Enable();
	App->hud->Enable();
	App->collision->Enable();
	App->map->Enable();
	App->player->Enable();
	App->object->Enable();
	App->enemy->Enable();

	App->enemy->Final_Boss = new Boss();
	App->enemy->Final_Boss->im_active = true;
	App->enemy->Final_Boss->is_testing = true;
	//PAUSE FALSE
	App->player->paused = true;
	App->enemy->paused = false;
	App->collision->paused = false;
	App->pathfinding->paused = false;
	SDL_Rect r = { 0,0,1280,720 };
	App->videoplayer->PlayVideo("Boss video.ogv", r);
	App->videoplayer->video_finished = false;

	if (App->map->Load("final_boss_map_advanced.tmx") == true)

	{
		int w, h = 0;
		uchar* data = nullptr;
		if (App->map->CreateWalkabilityMap(w, h, &data))
			App->pathfinding->SetMap(w, h);

		for (uint i = 0; i < App->object->V_Objects.size(); i++) {
			if (App->object->V_Objects[i]->collider_tiles.size() > 0) {
				App->object->CreateColliders(*App->object->V_Objects[i]);
			}
		}

		int w_two, h_two = 0;
		uchar* data_two = nullptr;
		if (App->map->CreateEnemyMap(w_two, h_two, &data_two)) {
			int w_three = 0;
			int h_three = 0;
			uchar* data_three = nullptr;
			if (App->map->CreateEnemyPathMap(w_three, h_three, &data_three)) {
				App->enemy->Enable();
			}
		}
		RELEASE_ARRAY(data);
		//App->map->CreateLogicMap();
	}

	App->render->camera.x = 0;
	App->render->camera.y = 0;

	//App->player->Link->pos = { 660,1400 };
	//App->player->Zelda->pos = { 620,1400 };
	App->player->Link->logic_height = 0;
	App->player->Zelda->logic_height = 0;

	LOG("World Open");
	App->cutscenemanager->StartCutscene(3);
	return false;
}

bool S_TempBossRoom::Update()
{
	for (int i = 0; i < App->object->V_Objects.size(); i++) {
		if (App->object->V_Objects[i]->type == objectType::electric_ball) {
			App->object->V_Objects[i]->texture_rect = App->object->V_Objects[i]->actual_animation.GetCurrentFrame().rect;
		}
	}
	if (App->videoplayer->video_finished && done_video_boss == false)
	{
		App->audio->CleanUp();
		App->audio->Awake(App->config);
		App->audio->Start();
		App->player->paused = false;
		done_video_boss = true;
		App->audio->PlayMusic("audio/music/Final-boss-theme.ogg", 0);
		App->audio->VolumeMusic(100);
	}

	if (!App->player->paused)
		App->enemy->Final_Boss->UpdateLegs();

	return false;
}

bool S_TempBossRoom::PostUpdate()
{
	if (App->videoplayer->video_finished && done_video_boss == false)
	{
		/*if (App->player->loop_game_menu == true || App->player->half_hearts_test_purpose <= 0) {

			App->scene->ChangeScene(Scene_ID::Send);
			App->startmenuback->Freeze(false);
			App->player->loop_game_menu = false;
			App->player->half_hearts_test_purpose = App->player->hearts_containers_test_purpose * 2;
		}*/

		for (int i = 0; i < App->object->V_Objects.size(); i++) {
			if (App->object->V_Objects[i]->type == objectType::electric_ball) {
				ElectricBall* temp = (ElectricBall*)App->object->V_Objects[i];
				if (temp->active_phase == 1 && (App->enemy->Final_Boss->actual_phase == boss_phase_2 || App->enemy->Final_Boss->actual_phase == boss_phase_3))
					temp->active = true;
				if (temp->active_phase == 2 && (App->enemy->Final_Boss->actual_phase == boss_phase_3))
					temp->active = true;
			}
		}
		if (App->enemy->Final_Boss != nullptr) {
			if (App->enemy->Final_Boss->boss_defeated) {
				//Play final video
				//if finished App->scene->ChangeScene(Scene_ID::credits);
				App->scene->ChangeScene(Scene_ID::credits);
				App->scene->win_game_variableforshowcredits = true;
			}
		}
	}
	return true;

}

bool S_TempBossRoom::Clean()
{
	if (App->enemy->Final_Boss != NULL) {
		App->enemy->Final_Boss->im_active = false;
		delete App->enemy->Final_Boss;
		App->enemy->Final_Boss = NULL;
	}
	LOG("World Test Deleted");

	App->player->Disable();
	App->enemy->Disable();
	App->map->Disable();
	App->collision->Disable();
	App->hud->Disable();
	App->object->Disable();

	//std::list <TileSet*>::iterator temp = App->map->data.tilesets.begin();

	/*p2List_item<TileSet*>* temp = App->map->data.tilesets.start;
	while (temp != NULL) {
	App->tex->UnLoad(temp->data->texture);
	temp = temp->next;
	}*/

	//This must be revised
	((S_InGameMenu*)App->scene->InGameMenuScene())->active = false;

	return false;
}

bool S_TempBossRoom::Save(pugi::xml_node& node) const
{
	return true;
}

bool S_TempBossRoom::Load(pugi::xml_node& node)
{
	return true;
}<|endoftext|>


<commit_before>

#include "GA.h"
#include "GAPowerUp.h"
#include "GACharacter.h"
#include "Net/UnrealNetwork.h"

AGAPowerUp::AGAPowerUp(const class FPostConstructInitializeProperties& PCIP)
	: Super(PCIP)
{
	IsInit = false;
	IsPowerUpActive = false;

	// Replicate to Server / Clients
	bReplicates = true;
	bAlwaysRelevant = true;
	PrimaryActorTick.bCanEverTick = true;
}

void AGAPowerUp::Tick(float DeltaTime){
	Super::Tick(DeltaTime);
	if(!IsInit) InitPowerUp();
	ReduceCoolDown(DeltaTime);
}

void AGAPowerUp::InitPowerUp(){
	if (Role == ROLE_Authority){
		if (IsRandomPowerUp){
			PowerUpType = (TEnumAsByte<EGAPowerUp::Type>) FMath::RandRange(1, 2);
		}
		IsInit = true;
	}
}

void AGAPowerUp::ReduceCoolDown(float DeltaTime){
	if (Role == ROLE_Authority){
		CurrentCoolDown -= DeltaTime;
		if (CurrentCoolDown <= 0){
			PowerUpFinishedCoolDown();
			IsPowerUpActive = true;
		}
	}
}

void AGAPowerUp::OnRep_IsPowerUpActive(){
	if (IsPowerUpActive){
		PowerUpFinishedCoolDown();
	}
	else{
		PowerUpTaken();
	}
}

void AGAPowerUp::ReceiveActorBeginOverlap(class AActor* OtherActor){
	Super::ReceiveActorBeginOverlap(OtherActor);
	if (OtherActor->ActorHasTag("Player") && IsPowerUpActive){
		ActivatePowerUpEffect(OtherActor);
	}
}

void AGAPowerUp::ActivatePowerUpEffect(class AActor* OtherActor){
	if (Role < ROLE_Authority){
		ServerActivatePowerUpEffect(OtherActor);
	}
	else{
		if (IsAffectingAll){
			for (TActorIterator<AGACharacter> ActorItr(GetWorld()); ActorItr; ++ActorItr){
				if (PowerUpType == EGAPowerUp::Type::GAHealthBoost){
					ActorItr->HealPlayer(HealAmount);
				}
				else {
					ActorItr->ActivatePowerUp(PowerUpType, EffectDuration);
				}
			}
		}
		else{
			if (PowerUpType == EGAPowerUp::Type::GAHealthBoost){
				((AGACharacter*)OtherActor)->HealPlayer(HealAmount);
			}
			else {
				((AGACharacter*)OtherActor)->ActivatePowerUp(PowerUpType, EffectDuration);
			}
		}

		CurrentCoolDown = CoolDown;
		IsPowerUpActive = false;
		PowerUpTaken();

		if (IsRandomPowerUp){
			PowerUpType = (TEnumAsByte<EGAPowerUp::Type>) FMath::RandRange(1, 2);
		}
	}
}

bool AGAPowerUp::ServerActivatePowerUpEffect_Validate(class AActor* OtherActor){return true;}
void AGAPowerUp::ServerActivatePowerUpEffect_Implementation(class AActor* OtherActor){ActivatePowerUpEffect(OtherActor);}

// Replicates Replicated Attributes
void AGAPowerUp::GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const{
	Super::GetLifetimeReplicatedProps(OutLifetimeProps);

	DOREPLIFETIME(AGAPowerUp, IsPowerUpActive);
	DOREPLIFETIME(AGAPowerUp, PowerUpType);
	DOREPLIFETIME(AGAPowerUp, IsRandomPowerUp);
	DOREPLIFETIME(AGAPowerUp, IsAffectingAll);
	DOREPLIFETIME(AGAPowerUp, CoolDown);
	DOREPLIFETIME(AGAPowerUp, CurrentCoolDown);
}
<commit_msg>~fix PowerUpFinishedCoolDown<commit_after>

#include "GA.h"
#include "GAPowerUp.h"
#include "GACharacter.h"
#include "Net/UnrealNetwork.h"

AGAPowerUp::AGAPowerUp(const class FPostConstructInitializeProperties& PCIP)
	: Super(PCIP)
{
	IsInit = false;
	IsPowerUpActive = false;

	// Replicate to Server / Clients
	bReplicates = true;
	bAlwaysRelevant = true;
	PrimaryActorTick.bCanEverTick = true;
}

void AGAPowerUp::Tick(float DeltaTime){
	Super::Tick(DeltaTime);
	if(!IsInit) InitPowerUp();
	ReduceCoolDown(DeltaTime);
}

void AGAPowerUp::InitPowerUp(){
	if (Role == ROLE_Authority){
		if (IsRandomPowerUp){
			PowerUpType = (TEnumAsByte<EGAPowerUp::Type>) FMath::RandRange(1, 2);
		}
		IsInit = true;
	}
}

void AGAPowerUp::ReduceCoolDown(float DeltaTime){
	if (Role == ROLE_Authority){
		if (!IsPowerUpActive){
			CurrentCoolDown -= DeltaTime;
			if (CurrentCoolDown <= 0){
				PowerUpFinishedCoolDown();
				IsPowerUpActive = true;
			}
		}
	}
}

void AGAPowerUp::OnRep_IsPowerUpActive(){
	if (IsPowerUpActive){
		PowerUpFinishedCoolDown();
	}
	else{
		PowerUpTaken();
	}
}

void AGAPowerUp::ReceiveActorBeginOverlap(class AActor* OtherActor){
	Super::ReceiveActorBeginOverlap(OtherActor);
	if (OtherActor->ActorHasTag("Player") && IsPowerUpActive){
		ActivatePowerUpEffect(OtherActor);
	}
}

void AGAPowerUp::ActivatePowerUpEffect(class AActor* OtherActor){
	if (Role < ROLE_Authority){
		ServerActivatePowerUpEffect(OtherActor);
	}
	else{
		if (IsAffectingAll){
			for (TActorIterator<AGACharacter> ActorItr(GetWorld()); ActorItr; ++ActorItr){
				if (PowerUpType == EGAPowerUp::Type::GAHealthBoost){
					ActorItr->HealPlayer(HealAmount);
				}
				else {
					ActorItr->ActivatePowerUp(PowerUpType, EffectDuration);
				}
			}
		}
		else{
			if (PowerUpType == EGAPowerUp::Type::GAHealthBoost){
				((AGACharacter*)OtherActor)->HealPlayer(HealAmount);
			}
			else {
				((AGACharacter*)OtherActor)->ActivatePowerUp(PowerUpType, EffectDuration);
			}
		}

		CurrentCoolDown = CoolDown;
		IsPowerUpActive = false;
		PowerUpTaken();

		if (IsRandomPowerUp){
			PowerUpType = (TEnumAsByte<EGAPowerUp::Type>) FMath::RandRange(1, 2);
		}
	}
}

bool AGAPowerUp::ServerActivatePowerUpEffect_Validate(class AActor* OtherActor){return true;}
void AGAPowerUp::ServerActivatePowerUpEffect_Implementation(class AActor* OtherActor){ActivatePowerUpEffect(OtherActor);}

// Replicates Replicated Attributes
void AGAPowerUp::GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const{
	Super::GetLifetimeReplicatedProps(OutLifetimeProps);

	DOREPLIFETIME(AGAPowerUp, IsPowerUpActive);
	DOREPLIFETIME(AGAPowerUp, PowerUpType);
	DOREPLIFETIME(AGAPowerUp, IsRandomPowerUp);
	DOREPLIFETIME(AGAPowerUp, IsAffectingAll);
	DOREPLIFETIME(AGAPowerUp, CoolDown);
	DOREPLIFETIME(AGAPowerUp, CurrentCoolDown);
}
<|endoftext|>