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

#ifndef INCLUDED_FILTER_SOURCE_GRAPHICFILTER_ICGM_CHART_HXX
#define INCLUDED_FILTER_SOURCE_GRAPHICFILTER_ICGM_CHART_HXX

/* FILE TYPE CONSTANTS: */
#define NOCHART         0       /* Undefined chart.         */
#define XYCHART         1       /* Standard XY chart.       */
#define PIECHART        21      /* Standard pie chart file. */
#define ORGCHART        26      /* Standard org chart file. */
#define TTLCHART        31      /* Title chart file.        */
#define BULCHART        32      /* Bullet chart file.       */
#define TABCHART        33      /* Table chart file.        */
#define DRWCHART        41      /* Chart with drawings only.*/
#define MLTCHART        42      /* Multiple chart file.     */
#define LASTCHART       45      /* The largest chart type.  */
#define SHWFILE         46      /* Slide show file.         */
#define SYMFILE         47      /* Symbol file.             */
/* the following were added although SPC doesn't have a #define */
/* for them...                                                  */
#define AUTOTTLCHT      95      /* Autobuild TTL CHT        */
#define AUTOBULCHT      96      /* Autobuild BUL CHT        */
#define AUTOTABCHT      97      /* Autobuild TAB CHT        */

/* FNC 10/11/93: for the chart stream, ALLCHART was added.  */
/* It is used specifically by PPT in its Template to let    */
/* us know that the template applies to all charts, not to  */
/* one specific chart type.                                 */
#define ALLCHART       127      /* Applies to all chart types */
#define ALLCHART_TPL   255      /* Applies to all chart types */

#define IOC_CHTTITLE        1       /* Title for any chart.                  */
#define IOC_CHTFOOTNOTE     2       /* ::com::sun::star::text::Footnote for any chart.               */
#define IOC_XYAXIS          3       /* Axis title for XY charts.             */
#define IOC_XYSERIESLEGEND  4       /* Series legend titles for XY charts.   */
#define IOC_PIETITLE        5       /* Title for pie charts.                 */
#define IOC_TABLEBODY       6       /* Table chart text element.             */
#define IOC_TITLEBODY       7       /* Title chart text element.             */
#define IOC_BULLETBODY      8       /* Bullet chart text element.            */
#define IOC_XYLEGENDTITLE   9       /* Legend title for XY charts.           */
#define IOC_PIELEGENDTITLE  10      /* Legend title for pie charts.          */
#define IOC_TABLEGENDTITLE  11      /* Legend title for table charts.        */

typedef struct TextAttribute
{
    sal_uInt16          nTextAttribCount;
    sal_Int8            nTextColorIndex;
    sal_Int8            nTextColorRed;
    sal_Int8            nTextColorGreen;
    sal_Int8            nTextColorBlue;
    sal_Int8            nShadowColorIndex;
    sal_Int8            nShadowColorRed;
    sal_Int8            nShadowColorGreen;
    sal_Int8            nShadowColorBlue;
    float           nTextAttribSize;
    sal_uInt16          nTextAttribBits;
    sal_Int8            nTextFontType;      // font identifiers
    sal_Int8            nTextCharPage;
    sal_uInt16          nTextFontFamily;
    sal_Int8            nTextFontMemberID;
    sal_Int8            nTextFontVendorID;
    TextAttribute*  pNextAttribute;     // zero or pointer to next TextAttribute
} TextAttribute;

typedef struct TextEntry
{
    sal_uInt16          nTypeOfText;
    sal_uInt16          nRowOrLineNum;
    sal_uInt16          nColumnNum;
    sal_uInt16          nZoneSize;          // textzone attributes
    sal_uInt16          nLineType;
    sal_uInt16          nAttributes;
    char*           pText;              // null terminated text
    TextAttribute*  pAttribute;
} TextEntry;

typedef struct ZoneOption
{
    char            nOverTitle;
    char            nOverBody;
    char            nOverFoot;
    char            nFStyle_Title;
    char            nFStyle_Body;
    char            nFStyle_Foot;
    char            nFOutc_Title;
    char            nFOutc_Body;
    char            nFOutc_Foot;
    char            nFFillc_Title;
    char            nFFillc_Body;
    char            nFFillc_Foot;
} ZoneOption;

typedef struct BulletOption
{
    char            nBType;
    char            nBSize;
    char            nBColor;
    sal_Int16           nBStart;
    double          nTMargin;
    double          nBSpace;
    char            nCPlace;
} BulletOption;

typedef struct BulDef
{
    char            btype;
    char            bsize;
    char            bcolor;
    char            bnumber;
} BulDef;

typedef struct BulletLines
{
    BulDef          nBulDef[ 48 ];
} BulletLines;

typedef struct IntSettings
{
    sal_uInt16          nCountry;
    sal_uInt16          nDateFormat;
    sal_uInt16          nDateSep;
    sal_uInt16          nTimeFormat;
    sal_uInt16          nTimeSep;
    sal_uInt16          nNumSeps;
    sal_uInt16          nCurrencyFormat;
    char            nCurrencySymbol[ 5 ];
} IntSettings;

typedef struct PageOrientDim
{
    char            nOrientation;
    char            nDimension;
    float           nPageX;
    float           nPageY;
} PageOrientDim;

typedef struct DataNode
{
    sal_Int16           nBoxX1;
    sal_Int16           nBoxY1;
    sal_Int16           nBoxX2;
    sal_Int16           nBoxY2;
    sal_Int8            nZoneEnum;
} DataNode;

typedef struct ChartZone
{
    sal_Int16           nMinX;
    sal_Int16           nMinY;
    sal_Int16           nMaxX;
    sal_Int16           nMaxY;
    char            nUserDef;
    char            nPad1;
} ChartZone;

class CGM;
class CGMImpressOutAct;
class CGMChart
{
    friend class CGM;
    friend class CGMImpressOutAct;

    protected:
        CGM*                    mpCGM;
        sal_Int8                mnCurrentFileType;
        ::std::vector< TextEntry* > maTextEntryList;
        DataNode                mDataNode[ 7 ];
        ChartZone               mChartZone;
        PageOrientDim           mPageOrientDim;
        BulletOption            mBulletOption;
        BulletLines             mBulletLines;
        ZoneOption              mZoneOption;
        IntSettings             mIntSettings;

    public:
                                CGMChart( CGM& rCGM );
                                ~CGMChart();

        void                    DeleteTextEntry( TextEntry* );
        void                    InsertTextEntry( TextEntry* );

        void                    ResetAnnotation();
        sal_Bool                    IsAnnotation();
};

#endif

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

#ifndef INCLUDED_FILTER_SOURCE_GRAPHICFILTER_ICGM_CHART_HXX
#define INCLUDED_FILTER_SOURCE_GRAPHICFILTER_ICGM_CHART_HXX

/* FILE TYPE CONSTANTS: */
#define NOCHART         0       /* Undefined chart.         */
#define XYCHART         1       /* Standard XY chart.       */
#define PIECHART        21      /* Standard pie chart file. */
#define ORGCHART        26      /* Standard org chart file. */
#define TTLCHART        31      /* Title chart file.        */
#define BULCHART        32      /* Bullet chart file.       */
#define TABCHART        33      /* Table chart file.        */
#define DRWCHART        41      /* Chart with drawings only.*/
#define MLTCHART        42      /* Multiple chart file.     */
#define LASTCHART       45      /* The largest chart type.  */
#define SHWFILE         46      /* Slide show file.         */
#define SYMFILE         47      /* Symbol file.             */
/* the following were added although SPC doesn't have a #define */
/* for them...                                                  */
#define AUTOTTLCHT      95      /* Autobuild TTL CHT        */
#define AUTOBULCHT      96      /* Autobuild BUL CHT        */
#define AUTOTABCHT      97      /* Autobuild TAB CHT        */

/* FNC 10/11/93: for the chart stream, ALLCHART was added.  */
/* It is used specifically by PPT in its Template to let    */
/* us know that the template applies to all charts, not to  */
/* one specific chart type.                                 */
#define ALLCHART       127      /* Applies to all chart types */
#define ALLCHART_TPL   255      /* Applies to all chart types */

#define IOC_CHTTITLE        1       /* Title for any chart.                  */
#define IOC_CHTFOOTNOTE     2       /* ::com::sun::star::text::Footnote for any chart.               */
#define IOC_XYAXIS          3       /* Axis title for XY charts.             */
#define IOC_XYSERIESLEGEND  4       /* Series legend titles for XY charts.   */
#define IOC_PIETITLE        5       /* Title for pie charts.                 */
#define IOC_TABLEBODY       6       /* Table chart text element.             */
#define IOC_TITLEBODY       7       /* Title chart text element.             */
#define IOC_BULLETBODY      8       /* Bullet chart text element.            */
#define IOC_XYLEGENDTITLE   9       /* Legend title for XY charts.           */
#define IOC_PIELEGENDTITLE  10      /* Legend title for pie charts.          */
#define IOC_TABLEGENDTITLE  11      /* Legend title for table charts.        */

typedef struct TextAttribute
{
    sal_uInt16          nTextAttribCount;
    sal_Int8            nTextColorIndex;
    sal_Int8            nTextColorRed;
    sal_Int8            nTextColorGreen;
    sal_Int8            nTextColorBlue;
    sal_Int8            nShadowColorIndex;
    sal_Int8            nShadowColorRed;
    sal_Int8            nShadowColorGreen;
    sal_Int8            nShadowColorBlue;
    float           nTextAttribSize;
    sal_uInt16          nTextAttribBits;
    sal_Int8            nTextFontType;      // font identifiers
    sal_Int8            nTextCharPage;
    sal_uInt16          nTextFontFamily;
    sal_Int8            nTextFontMemberID;
    sal_Int8            nTextFontVendorID;
    TextAttribute*  pNextAttribute;     // zero or pointer to next TextAttribute
} TextAttribute;

typedef struct TextEntry
{
    sal_uInt16          nTypeOfText;
    sal_uInt16          nRowOrLineNum;
    sal_uInt16          nColumnNum;
    sal_uInt16          nZoneSize;          // textzone attributes
    sal_uInt16          nLineType;
    sal_uInt16          nAttributes;
    char*           pText;              // null terminated text
    TextAttribute*  pAttribute;
} TextEntry;

struct ZoneOption
{
    char            nOverTitle;
    char            nOverBody;
    char            nOverFoot;
    char            nFStyle_Title;
    char            nFStyle_Body;
    char            nFStyle_Foot;
    char            nFOutc_Title;
    char            nFOutc_Body;
    char            nFOutc_Foot;
    char            nFFillc_Title;
    char            nFFillc_Body;
    char            nFFillc_Foot;
    ZoneOption()
        : nOverTitle(0)
        , nOverBody(0)
        , nOverFoot(0)
        , nFStyle_Title(0)
        , nFStyle_Body(0)
        , nFStyle_Foot(0)
        , nFOutc_Title(0)
        , nFOutc_Body(0)
        , nFOutc_Foot(0)
        , nFFillc_Title(0)
        , nFFillc_Body(0)
        , nFFillc_Foot(0)
    {
    }
};

struct BulletOption
{
    char            nBType;
    char            nBSize;
    char            nBColor;
    sal_Int16       nBStart;
    double          nTMargin;
    double          nBSpace;
    char            nCPlace;
    BulletOption()
        : nBType(0)
        , nBSize(0)
        , nBColor(0)
        , nBStart(0)
        , nTMargin(0)
        , nBSpace(0)
        , nCPlace(0)
    {
    }
};

typedef struct BulDef
{
    char            btype;
    char            bsize;
    char            bcolor;
    char            bnumber;
} BulDef;

typedef struct BulletLines
{
    BulDef          nBulDef[ 48 ];
} BulletLines;

struct IntSettings
{
    sal_uInt16          nCountry;
    sal_uInt16          nDateFormat;
    sal_uInt16          nDateSep;
    sal_uInt16          nTimeFormat;
    sal_uInt16          nTimeSep;
    sal_uInt16          nNumSeps;
    sal_uInt16          nCurrencyFormat;
    char            nCurrencySymbol[ 5 ];
    IntSettings()
        : nCountry(0)
        , nDateFormat(0)
        , nDateSep(0)
        , nTimeFormat(0)
        , nTimeSep(0)
        , nNumSeps(0)
        , nCurrencyFormat(0)
    {
        memset (nCurrencySymbol, 0, sizeof(nCurrencySymbol));
    }
};

typedef struct PageOrientDim
{
    char            nOrientation;
    char            nDimension;
    float           nPageX;
    float           nPageY;
} PageOrientDim;

typedef struct DataNode
{
    sal_Int16           nBoxX1;
    sal_Int16           nBoxY1;
    sal_Int16           nBoxX2;
    sal_Int16           nBoxY2;
    sal_Int8            nZoneEnum;
} DataNode;

typedef struct ChartZone
{
    sal_Int16           nMinX;
    sal_Int16           nMinY;
    sal_Int16           nMaxX;
    sal_Int16           nMaxY;
    char            nUserDef;
    char            nPad1;
} ChartZone;

class CGM;
class CGMImpressOutAct;
class CGMChart
{
    friend class CGM;
    friend class CGMImpressOutAct;

    protected:
        CGM*                    mpCGM;
        sal_Int8                mnCurrentFileType;
        ::std::vector< TextEntry* > maTextEntryList;
        DataNode                mDataNode[ 7 ];
        ChartZone               mChartZone;
        PageOrientDim           mPageOrientDim;
        BulletOption            mBulletOption;
        BulletLines             mBulletLines;
        ZoneOption              mZoneOption;
        IntSettings             mIntSettings;

    public:
                                CGMChart( CGM& rCGM );
                                ~CGMChart();

        void                    DeleteTextEntry( TextEntry* );
        void                    InsertTextEntry( TextEntry* );

        void                    ResetAnnotation();
        sal_Bool                    IsAnnotation();
};

#endif

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


<commit_before>// This macro draws 4 Latex-style formula in a canvas and prints the canvas
// as a Postscript file.
// Note that this macro relies on a first implementation of the TLatex class.
// There are still some discrepancies between the result on the screen
// and the result on Postscript.
// Also some differences will be seen between Unix servers depending
// the version of X in use. Results on WindowsNT are also slightly different.
//Author: Rene Brun
void latex5() {
   TCanvas *c1 = new TCanvas("c1","test",600,700);
   // write formulas
   TLatex l;
   l.SetTextAlign(12);
   l.SetTextSize(0.04);
   l.DrawLatex(0.1,0.9,"1)   C(x) = d #sqrt{#frac{2}{#lambdaD}}  #int^{x}_{0}cos(#frac{#pi}{2}t^{2})dt");
   l.DrawLatex(0.1,0.7,"2)   C(x) = d #sqrt{#frac{2}{#lambdaD}}  #int^{x}cos(#frac{#pi}{2}t^{2})dt");
   l.DrawLatex(0.1,0.5,"3)   R = |A|^{2} = #frac{1}{2}#left(#[]{#frac{1}{2}+C(V)}^{2}+#[]{#frac{1}{2}+S(V)}^{2}#right)");
   l.DrawLatex(0.1,0.3,"4)   F(t) = #sum_{i=-#infty}^{#infty}A(i)cos#[]{#frac{i}{t+i}}");
   l.DrawLatex(0.1,0.1,"5)   {}_{3}^{7}Li");
   c1->Print("latex.ps");
}
<commit_msg>Rename function latex instead of latex5<commit_after>// This macro draws 4 Latex-style formula in a canvas and prints the canvas
// as a Postscript file.
// Note that this macro relies on a first implementation of the TLatex class.
// There are still some discrepancies between the result on the screen
// and the result on Postscript.
// Also some differences will be seen between Unix servers depending
// the version of X in use. Results on WindowsNT are also slightly different.
//Author: Rene Brun
void latex() {
   TCanvas *c1 = new TCanvas("c1","test",600,700);
   // write formulas
   TLatex l;
   l.SetTextAlign(12);
   l.SetTextSize(0.04);
   l.DrawLatex(0.1,0.9,"1)   C(x) = d #sqrt{#frac{2}{#lambdaD}}  #int^{x}_{0}cos(#frac{#pi}{2}t^{2})dt");
   l.DrawLatex(0.1,0.7,"2)   C(x) = d #sqrt{#frac{2}{#lambdaD}}  #int^{x}cos(#frac{#pi}{2}t^{2})dt");
   l.DrawLatex(0.1,0.5,"3)   R = |A|^{2} = #frac{1}{2}#left(#[]{#frac{1}{2}+C(V)}^{2}+#[]{#frac{1}{2}+S(V)}^{2}#right)");
   l.DrawLatex(0.1,0.3,"4)   F(t) = #sum_{i=-#infty}^{#infty}A(i)cos#[]{#frac{i}{t+i}}");
   l.DrawLatex(0.1,0.1,"5)   {}_{3}^{7}Li");
   c1->Print("latex.ps");
}
<|endoftext|>


<commit_before>#include "gtest/gtest.h"
#include "cpp/ylikuutio/geometry/line_segment_line_segment_intersection.hpp"
#include "cpp/ylikuutio/geometry/line_segment2D.hpp"

// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif

// Include standard headers
#include <cmath>    // NAN, std::isnan, std::pow

TEST(line_segment2D_line_segment2D_intersection, parallel_line_segments)
{
    // ^............ a1 = point 1 of line segment a at (2, 2).
    // |.....b1..... a2 = point 2 of line segment a at (11, 5).
    // |..b2.....a2.
    // |*......*.... b1 = point 1 of line segment b at (7, 6).
    // |....*....... b2 = point 2 of line segment b at (4, 5).
    // |a1..........
    // |............
    // +----------->
    geometry::LineSegment2D line_segment_a = geometry::LineSegment2D(glm::vec2(2.0f, 2.0f), glm::vec2(11.0f, 5.0f));
    geometry::LineSegment2D line_segment_b = geometry::LineSegment2D(glm::vec2(7.0f, 6.0f), glm::vec2(4.0f, 5.0f));

    glm::vec2 intersection_point_a_a = geometry::get_intersection_point(&line_segment_a, &line_segment_a);
    ASSERT_TRUE(isnan(intersection_point_a_a.x));
    ASSERT_TRUE(isnan(intersection_point_a_a.y));

    glm::vec2 intersection_point_a_b = geometry::get_intersection_point(&line_segment_a, &line_segment_b);
    ASSERT_TRUE(isnan(intersection_point_a_b.x));
    ASSERT_TRUE(isnan(intersection_point_a_b.y));

    glm::vec2 intersection_point_b_a = geometry::get_intersection_point(&line_segment_b, &line_segment_a);
    ASSERT_TRUE(isnan(intersection_point_b_a.x));
    ASSERT_TRUE(isnan(intersection_point_b_a.y));

    glm::vec2 intersection_point_b_b = geometry::get_intersection_point(&line_segment_b, &line_segment_b);
    ASSERT_TRUE(isnan(intersection_point_b_b.x));
    ASSERT_TRUE(isnan(intersection_point_b_b.y));

    // LineSegment c is same as but point order is changed.
    geometry::LineSegment2D line_segment_c = geometry::LineSegment2D(glm::vec2(11.0f, 5.0f), glm::vec2(2.0f, 2.0f));

    glm::vec2 intersection_point_a_c = geometry::get_intersection_point(&line_segment_a, &line_segment_c);
    ASSERT_TRUE(isnan(intersection_point_a_c.x));
    ASSERT_TRUE(isnan(intersection_point_a_c.y));

    glm::vec2 intersection_point_b_c = geometry::get_intersection_point(&line_segment_b, &line_segment_c);
    ASSERT_TRUE(isnan(intersection_point_b_c.x));
    ASSERT_TRUE(isnan(intersection_point_b_c.y));

    glm::vec2 intersection_point_c_c = geometry::get_intersection_point(&line_segment_c, &line_segment_c);
    ASSERT_TRUE(isnan(intersection_point_c_c.x));
    ASSERT_TRUE(isnan(intersection_point_c_c.y));

    glm::vec2 intersection_point_c_a = geometry::get_intersection_point(&line_segment_c, &line_segment_a);
    ASSERT_TRUE(isnan(intersection_point_c_a.x));
    ASSERT_TRUE(isnan(intersection_point_c_a.y));

    glm::vec2 intersection_point_c_b = geometry::get_intersection_point(&line_segment_c, &line_segment_b);
    ASSERT_TRUE(isnan(intersection_point_c_b.x));
    ASSERT_TRUE(isnan(intersection_point_c_b.y));
}

TEST(line_segment2D_line_segment2D_intersection, intersecting_line_segments)
{
    // ^..........*. a1 = point 1 of line segment a at (5, 1).
    // |*.......a2.. a2 = point 2 of line segment a at (10, 6).
    // |.b1.....*...
    // |....*..*.... b1 = point 1 of line segment b at (3, 5).
    // |......x..... b2 = point 2 of line segment b at (9, 2).
    // |.....*.b2...
    // |...a1.....*. x = intersection point at (7, 3).
    // +----------->
    geometry::LineSegment2D line_segment_a = geometry::LineSegment2D(glm::vec2(5.0f, 1.0f), glm::vec2(10.0f, 6.0f));
    ASSERT_EQ(line_segment_a.determinant, 20.0f);
    ASSERT_EQ(line_segment_a.x1_minus_x2, -5.0f);
    ASSERT_EQ(line_segment_a.y1_minus_y2, -5.0f);

    geometry::LineSegment2D line_segment_b = geometry::LineSegment2D(glm::vec2(3.0f, 5.0f), glm::vec2(9.0f, 2.0f));
    ASSERT_EQ(line_segment_b.determinant, -39.0f);
    ASSERT_EQ(line_segment_b.x1_minus_x2, -6.0f);
    ASSERT_EQ(line_segment_b.y1_minus_y2, 3.0f);

    glm::vec2 intersection_point = geometry::get_intersection_point(&line_segment_a, &line_segment_b);
    ASSERT_EQ(intersection_point.x, 7.0f);
    ASSERT_EQ(intersection_point.y, 3.0f);
}

TEST(line_segment2D_line_segment2D_intersection, potentially_but_not_intersecting_line_segments)
{
    // ^..........*. a1 = point 1 of line segment a at (5, 1).
    // |*.......a2.. a2 = point 2 of line segment a at (10, 6).
    // |.b1.....*...
    // |...b2..*.... b1 = point 1 of line segment b at (3, 5).
    // |......x..... b2 = point 2 of line segment b at (5, 4).
    // |.....*......
    // |...a1....... x = potential intersection point at (7, 3).
    // +----------->
    geometry::LineSegment2D line_segment_a = geometry::LineSegment2D(glm::vec2(5.0f, 1.0f), glm::vec2(10.0f, 6.0f));
    ASSERT_EQ(line_segment_a.determinant, 20.0f);
    ASSERT_EQ(line_segment_a.x1_minus_x2, -5.0f);
    ASSERT_EQ(line_segment_a.y1_minus_y2, -5.0f);

    geometry::LineSegment2D line_segment_b = geometry::LineSegment2D(glm::vec2(3.0f, 5.0f), glm::vec2(5.0f, 4.0f));
    ASSERT_EQ(line_segment_b.determinant, -13.0f);
    ASSERT_EQ(line_segment_b.x1_minus_x2, -2.0f);
    ASSERT_EQ(line_segment_b.y1_minus_y2, 1.0f);

    glm::vec2 intersection_point = geometry::get_intersection_point(&line_segment_a, &line_segment_b);
    ASSERT_TRUE(isnan(intersection_point.x));
    ASSERT_TRUE(isnan(intersection_point.y));
}
<commit_msg>More tests for line segment - line segment intersection.<commit_after>#include "gtest/gtest.h"
#include "cpp/ylikuutio/geometry/line_segment_line_segment_intersection.hpp"
#include "cpp/ylikuutio/geometry/line_segment2D.hpp"

// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif

// Include standard headers
#include <cmath>    // NAN, std::isnan, std::pow

TEST(line_segment2D_line_segment2D_intersection, parallel_line_segments)
{
    // ^............ a1 = point 1 of line segment a at (2, 2).
    // |.....b1..... a2 = point 2 of line segment a at (11, 5).
    // |..b2.....a2.
    // |*......*.... b1 = point 1 of line segment b at (7, 6).
    // |....*....... b2 = point 2 of line segment b at (4, 5).
    // |a1..........
    // |............
    // +----------->
    geometry::LineSegment2D line_segment_a = geometry::LineSegment2D(glm::vec2(2.0f, 2.0f), glm::vec2(11.0f, 5.0f));
    geometry::LineSegment2D line_segment_b = geometry::LineSegment2D(glm::vec2(7.0f, 6.0f), glm::vec2(4.0f, 5.0f));

    glm::vec2 intersection_point_a_a = geometry::get_intersection_point(&line_segment_a, &line_segment_a);
    ASSERT_TRUE(isnan(intersection_point_a_a.x));
    ASSERT_TRUE(isnan(intersection_point_a_a.y));

    glm::vec2 intersection_point_a_b = geometry::get_intersection_point(&line_segment_a, &line_segment_b);
    ASSERT_TRUE(isnan(intersection_point_a_b.x));
    ASSERT_TRUE(isnan(intersection_point_a_b.y));

    glm::vec2 intersection_point_b_a = geometry::get_intersection_point(&line_segment_b, &line_segment_a);
    ASSERT_TRUE(isnan(intersection_point_b_a.x));
    ASSERT_TRUE(isnan(intersection_point_b_a.y));

    glm::vec2 intersection_point_b_b = geometry::get_intersection_point(&line_segment_b, &line_segment_b);
    ASSERT_TRUE(isnan(intersection_point_b_b.x));
    ASSERT_TRUE(isnan(intersection_point_b_b.y));

    // LineSegment c is same as but point order is changed.
    geometry::LineSegment2D line_segment_c = geometry::LineSegment2D(glm::vec2(11.0f, 5.0f), glm::vec2(2.0f, 2.0f));

    glm::vec2 intersection_point_a_c = geometry::get_intersection_point(&line_segment_a, &line_segment_c);
    ASSERT_TRUE(isnan(intersection_point_a_c.x));
    ASSERT_TRUE(isnan(intersection_point_a_c.y));

    glm::vec2 intersection_point_b_c = geometry::get_intersection_point(&line_segment_b, &line_segment_c);
    ASSERT_TRUE(isnan(intersection_point_b_c.x));
    ASSERT_TRUE(isnan(intersection_point_b_c.y));

    glm::vec2 intersection_point_c_c = geometry::get_intersection_point(&line_segment_c, &line_segment_c);
    ASSERT_TRUE(isnan(intersection_point_c_c.x));
    ASSERT_TRUE(isnan(intersection_point_c_c.y));

    glm::vec2 intersection_point_c_a = geometry::get_intersection_point(&line_segment_c, &line_segment_a);
    ASSERT_TRUE(isnan(intersection_point_c_a.x));
    ASSERT_TRUE(isnan(intersection_point_c_a.y));

    glm::vec2 intersection_point_c_b = geometry::get_intersection_point(&line_segment_c, &line_segment_b);
    ASSERT_TRUE(isnan(intersection_point_c_b.x));
    ASSERT_TRUE(isnan(intersection_point_c_b.y));
}

TEST(line_segment2D_line_segment2D_intersection, intersecting_line_segments)
{
    // ^..........*. a1 = point 1 of line segment a at (5, 1).
    // |*.......a2.. a2 = point 2 of line segment a at (10, 6).
    // |.b1.....*...
    // |....*..*.... b1 = point 1 of line segment b at (3, 5).
    // |......x..... b2 = point 2 of line segment b at (9, 2).
    // |.....*.b2...
    // |...a1.....*. x = intersection point at (7, 3).
    // +----------->
    geometry::LineSegment2D line_segment_a = geometry::LineSegment2D(glm::vec2(5.0f, 1.0f), glm::vec2(10.0f, 6.0f));
    ASSERT_EQ(line_segment_a.determinant, 20.0f);
    ASSERT_EQ(line_segment_a.x1_minus_x2, -5.0f);
    ASSERT_EQ(line_segment_a.y1_minus_y2, -5.0f);

    geometry::LineSegment2D line_segment_b = geometry::LineSegment2D(glm::vec2(3.0f, 5.0f), glm::vec2(9.0f, 2.0f));
    ASSERT_EQ(line_segment_b.determinant, -39.0f);
    ASSERT_EQ(line_segment_b.x1_minus_x2, -6.0f);
    ASSERT_EQ(line_segment_b.y1_minus_y2, 3.0f);

    glm::vec2 intersection_point = geometry::get_intersection_point(&line_segment_a, &line_segment_b);
    ASSERT_EQ(intersection_point.x, 7.0f);
    ASSERT_EQ(intersection_point.y, 3.0f);
}

TEST(line_segment2D_line_segment2D_intersection, potentially_but_not_intersecting_line_segments)
{
    // ^..........*. a1 = point 1 of line segment a at (5, 1).
    // |*.......a2.. a2 = point 2 of line segment a at (10, 6).
    // |.b1.....*...
    // |...b2..*.... b1 = point 1 of line segment b at (3, 5).
    // |......x..... b2 = point 2 of line segment b at (5, 4).
    // |.....*......
    // |...a1....... x = potential intersection point at (7, 3).
    // +----------->
    geometry::LineSegment2D line_segment_a = geometry::LineSegment2D(glm::vec2(5.0f, 1.0f), glm::vec2(10.0f, 6.0f));
    ASSERT_EQ(line_segment_a.determinant, 20.0f);
    ASSERT_EQ(line_segment_a.x1_minus_x2, -5.0f);
    ASSERT_EQ(line_segment_a.y1_minus_y2, -5.0f);

    geometry::LineSegment2D line_segment_b = geometry::LineSegment2D(glm::vec2(3.0f, 5.0f), glm::vec2(5.0f, 4.0f));
    ASSERT_EQ(line_segment_b.determinant, -13.0f);
    ASSERT_EQ(line_segment_b.x1_minus_x2, -2.0f);
    ASSERT_EQ(line_segment_b.y1_minus_y2, 1.0f);

    glm::vec2 intersection_point = geometry::get_intersection_point(&line_segment_a, &line_segment_b);
    ASSERT_TRUE(isnan(intersection_point.x));
    ASSERT_TRUE(isnan(intersection_point.y));
}

TEST(line_segment2D_line_segment2D_intersection, intersection_at_other_lines_point2)
{
    // ^..........*. a1 = point 1 of line segment a at (5, 1).
    // |*.......a2.. a2 = point 2 of line segment a at (10, 6).
    // |.b1.....*...
    // |....*..*.... b1 = point 1 of line segment b at (3, 5).
    // |......x..... x = point 2 of line segment b at (7, 3).
    // |.....*......
    // |...a1....... x = potential intersection point at (7, 3).
    // +----------->
    geometry::LineSegment2D line_segment_a = geometry::LineSegment2D(glm::vec2(5.0f, 1.0f), glm::vec2(10.0f, 6.0f));
    ASSERT_EQ(line_segment_a.determinant, 20.0f);
    ASSERT_EQ(line_segment_a.x1_minus_x2, -5.0f);
    ASSERT_EQ(line_segment_a.y1_minus_y2, -5.0f);

    geometry::LineSegment2D line_segment_b = geometry::LineSegment2D(glm::vec2(3.0f, 5.0f), glm::vec2(7.0f, 3.0f));
    ASSERT_EQ(line_segment_b.determinant, -26.0f);
    ASSERT_EQ(line_segment_b.x1_minus_x2, -4.0f);
    ASSERT_EQ(line_segment_b.y1_minus_y2, 2.0f);

    glm::vec2 intersection_point = geometry::get_intersection_point(&line_segment_a, &line_segment_b);
    ASSERT_EQ(intersection_point.x, 7.0f);
    ASSERT_EQ(intersection_point.y, 3.0f);
}

TEST(line_segment2D_line_segment2D_intersection, intersection_at_both_lines_point2)
{
    // ^............ a1 = point 1 of line segment a at (5, 1).
    // |*........... x = point 2 of line segment a at (7, 3).
    // |.b1.........
    // |....*....... b1 = point 1 of line segment b at (3, 5).
    // |......x..... x = point 2 of line segment b at (7, 3).
    // |.....*......
    // |...a1....... x = potential intersection point at (7, 3).
    // +----------->
    geometry::LineSegment2D line_segment_a = geometry::LineSegment2D(glm::vec2(5.0f, 1.0f), glm::vec2(7.0f, 3.0f));
    ASSERT_EQ(line_segment_a.determinant, 8.0f);
    ASSERT_EQ(line_segment_a.x1_minus_x2, -2.0f);
    ASSERT_EQ(line_segment_a.y1_minus_y2, -2.0f);

    geometry::LineSegment2D line_segment_b = geometry::LineSegment2D(glm::vec2(3.0f, 5.0f), glm::vec2(7.0f, 3.0f));
    ASSERT_EQ(line_segment_b.determinant, -26.0f);
    ASSERT_EQ(line_segment_b.x1_minus_x2, -4.0f);
    ASSERT_EQ(line_segment_b.y1_minus_y2, 2.0f);

    glm::vec2 intersection_point = geometry::get_intersection_point(&line_segment_a, &line_segment_b);
    ASSERT_EQ(intersection_point.x, 7.0f);
    ASSERT_EQ(intersection_point.y, 3.0f);
}
<|endoftext|>


<commit_before>/* UART interface for PIC32.
 *
 * On the PIC32, the CAN translator uses Serial from the chipKIT library's
 * HardwareSerial interface for vehicle data. This is equivalent to UART1A or
 * U1A. Hardware flow control (RTS/CTS) is enabled, so CTS must be pulled low
 * by the receiving device before data will be sent.
 *
 * UART1 is also used by the USB-Serial connection, so in order to flash the
 * PIC32, these Tx/Rx lines must be disconnected. Ideally we could leave that
 * UART interface for debugging, but there are conflicts with all other exposed
 * UART interfaces when using flow control.
 *
 * U1A, U2A and U3A all have CTS/RTS lines exposed on the chipKIT. U2A doesn't
 * have Rx/Tx exposed through the HardwareSerial library, so we avoid that to
 * minimize additional programming. U3A's CTS/RTS lines conflict with CAN1, so
 * that's out; that leaves U1A.
 *
 * Pin 0 - U1ARX, connect this to the TX line of the receiver.
 * Pin 1 - U1ATX, connect this to the RX line of the receiver.
 * Pin 18 - U1ARTS, connect this to the CTS line of the receiver.
 * Pin 19 - U1ACTS, connect this to the RTS line of the receiver.
 */
#include "serialutil.h"
#include "buffers.h"
#include "log.h"
#include "HardwareSerial.h"
#include "WProgram.h"

#define UART_BAUDRATE 460800
// See http://www.chipkit.org/forum/viewtopic.php?f=19&t=711
#define _UARTMODE_BRGH 3

// bit 8 in the uxMode register controls hardware flow control
#define _UARTMODE_FLOWCONTROL 8

extern HardwareSerial Serial;

// TODO see if we can do this with interrupts on the chipKIT
// http://www.chipkit.org/forum/viewtopic.php?f=7&t=1088
void readFromSerial(SerialDevice* device, bool (*callback)(uint8_t*)) {
    if(device != NULL) {
        int bytesAvailable = ((HardwareSerial*)device->controller)->available();
        if(bytesAvailable > 0) {
            for(int i = 0; i < bytesAvailable &&
                    !QUEUE_FULL(uint8_t, &device->receiveQueue); i++) {
                char byte = ((HardwareSerial*)device->controller)->read();
                QUEUE_PUSH(uint8_t, &device->receiveQueue, (uint8_t) byte);
            }
            processQueue(&device->receiveQueue, callback);
        }
    }
}

void initializeSerial(SerialDevice* device) {
    if(device != NULL) {
        initializeSerialCommon(device);
        device->controller = &Serial;
        ((HardwareSerial*)device->controller)->begin(UART_BAUDRATE);
        // Manually enable RTS/CTS hardware flow control using the UART2
        // register. The chipKIT serial library doesn't have an interface to do
        // this, and the alternative UART libraries provided by Microchip are a
        // bit of a mess.
        ((p32_uart*)_UART1_BASE_ADDRESS)->uxMode.reg |= 2 << _UARTMODE_FLOWCONTROL;
        // Override baud rate setup to allow baud rates 200000 (see
        // http://www.chipkit.org/forum/viewtopic.php?f=19&t=711, this should
        // eventually make it into the MPIDE toolchain)
        ((p32_uart*)_UART1_BASE_ADDRESS)->uxBrg.reg = ((__PIC32_pbClk / 4 / UART_BAUDRATE) - 1);
        ((p32_uart*)_UART1_BASE_ADDRESS)->uxMode.reg = (1 << _UARTMODE_ON) | (1 << _UARTMODE_BRGH);
        debug("Done.");
    }
}

// The chipKIT version of this function is blocking. It will entirely flush the
// send queue before returning.
void processSerialSendQueue(SerialDevice* device) {
    int byteCount = 0;
    char sendBuffer[MAX_MESSAGE_SIZE];
    while(!QUEUE_EMPTY(uint8_t, &device->sendQueue) &&
                    byteCount < MAX_MESSAGE_SIZE) {
        sendBuffer[byteCount++] = QUEUE_POP(uint8_t, &device->sendQueue);
    }

    if(byteCount > 0) {
        ((HardwareSerial*)device->controller)->write((const uint8_t*)sendBuffer,
                byteCount);
    }
}
<commit_msg>Don't clobber flow control setting when setting baud rate on PIC32.<commit_after>/* UART interface for PIC32.
 *
 * On the PIC32, the CAN translator uses Serial from the chipKIT library's
 * HardwareSerial interface for vehicle data. This is equivalent to UART1A or
 * U1A. Hardware flow control (RTS/CTS) is enabled, so CTS must be pulled low
 * by the receiving device before data will be sent.
 *
 * UART1 is also used by the USB-Serial connection, so in order to flash the
 * PIC32, these Tx/Rx lines must be disconnected. Ideally we could leave that
 * UART interface for debugging, but there are conflicts with all other exposed
 * UART interfaces when using flow control.
 *
 * U1A, U2A and U3A all have CTS/RTS lines exposed on the chipKIT. U2A doesn't
 * have Rx/Tx exposed through the HardwareSerial library, so we avoid that to
 * minimize additional programming. U3A's CTS/RTS lines conflict with CAN1, so
 * that's out; that leaves U1A.
 *
 * Pin 0 - U1ARX, connect this to the TX line of the receiver.
 * Pin 1 - U1ATX, connect this to the RX line of the receiver.
 * Pin 18 - U1ARTS, connect this to the CTS line of the receiver.
 * Pin 19 - U1ACTS, connect this to the RTS line of the receiver.
 */
#include "serialutil.h"
#include "buffers.h"
#include "log.h"
#include "HardwareSerial.h"
#include "WProgram.h"

#define UART_BAUDRATE 460800
// See http://www.chipkit.org/forum/viewtopic.php?f=19&t=711
#define _UARTMODE_BRGH 3

// bit 8 in the uxMode register controls hardware flow control
#define _UARTMODE_FLOWCONTROL 8

extern HardwareSerial Serial;

// TODO see if we can do this with interrupts on the chipKIT
// http://www.chipkit.org/forum/viewtopic.php?f=7&t=1088
void readFromSerial(SerialDevice* device, bool (*callback)(uint8_t*)) {
    if(device != NULL) {
        int bytesAvailable = ((HardwareSerial*)device->controller)->available();
        if(bytesAvailable > 0) {
            for(int i = 0; i < bytesAvailable &&
                    !QUEUE_FULL(uint8_t, &device->receiveQueue); i++) {
                char byte = ((HardwareSerial*)device->controller)->read();
                QUEUE_PUSH(uint8_t, &device->receiveQueue, (uint8_t) byte);
            }
            processQueue(&device->receiveQueue, callback);
        }
    }
}

void initializeSerial(SerialDevice* device) {
    if(device != NULL) {
        initializeSerialCommon(device);
        device->controller = &Serial;
        ((HardwareSerial*)device->controller)->begin(UART_BAUDRATE);
        // Override baud rate setup to allow baud rates 200000 (see
        // http://www.chipkit.org/forum/viewtopic.php?f=19&t=711, this should
        // eventually make it into the MPIDE toolchain)
        ((p32_uart*)_UART1_BASE_ADDRESS)->uxBrg.reg = ((__PIC32_pbClk / 4 / UART_BAUDRATE) - 1);
        ((p32_uart*)_UART1_BASE_ADDRESS)->uxMode.reg = (1 << _UARTMODE_ON) | (1 << _UARTMODE_BRGH);
        // Manually enable RTS/CTS hardware flow control using the UART2
        // register. The chipKIT serial library doesn't have an interface to do
        // this, and the alternative UART libraries provided by Microchip are a
        // bit of a mess.
        ((p32_uart*)_UART1_BASE_ADDRESS)->uxMode.reg |= 2 << _UARTMODE_FLOWCONTROL;
        debug("Done.");
    }
}

// The chipKIT version of this function is blocking. It will entirely flush the
// send queue before returning.
void processSerialSendQueue(SerialDevice* device) {
    int byteCount = 0;
    char sendBuffer[MAX_MESSAGE_SIZE];
    while(!QUEUE_EMPTY(uint8_t, &device->sendQueue) &&
                    byteCount < MAX_MESSAGE_SIZE) {
        sendBuffer[byteCount++] = QUEUE_POP(uint8_t, &device->sendQueue);
    }

    if(byteCount > 0) {
        ((HardwareSerial*)device->controller)->write((const uint8_t*)sendBuffer,
                byteCount);
    }
}
<|endoftext|>


<commit_before>/* Copyright (c) 2013-2014 Jeffrey Pfau
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// This must be defined before anything else is included.
#define SDL_MAIN_HANDLED

#include "ConfigController.h"
#include "GBAApp.h"
#include "Window.h"

#include <mgba/core/version.h>
#include <mgba/gba/interface.h>

#include <QLibraryInfo>
#include <QTranslator>

#ifdef BUILD_GLES2
#include <QSurfaceFormat>
#endif

#ifdef QT_STATIC
#include <QtPlugin>
#ifdef Q_OS_WIN
Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin);
Q_IMPORT_PLUGIN(QWindowsVistaStylePlugin);
#ifdef BUILD_QT_MULTIMEDIA
Q_IMPORT_PLUGIN(QWindowsAudioPlugin);
Q_IMPORT_PLUGIN(DSServicePlugin);
#endif
#elif defined(Q_OS_MAC)
Q_IMPORT_PLUGIN(QCocoaIntegrationPlugin);
#ifdef BUILD_QT_MULTIMEDIA
Q_IMPORT_PLUGIN(CoreAudioPlugin);
Q_IMPORT_PLUGIN(AVFServicePlugin);
#endif
#endif
#endif

using namespace QGBA;

int main(int argc, char* argv[]) {
#ifdef BUILD_SDL
#if SDL_VERSION_ATLEAST(2, 0, 0) // CPP does not shortcut function lookup
	SDL_SetMainReady();
#endif
#endif

	ConfigController configController;

	QLocale locale;
	if (!configController.getQtOption("language").isNull()) {
		locale = QLocale(configController.getQtOption("language").toString());
		QLocale::setDefault(locale);
	}

	mArguments args;
	mGraphicsOpts graphicsOpts;
	mSubParser subparser;
	initParserForGraphics(&subparser, &graphicsOpts);
	bool loaded = configController.parseArguments(&args, argc, argv, &subparser);
	if (loaded && args.showHelp) {
		usage(argv[0], subparser.usage);
		return 0;
	}

	QApplication::setApplicationName(projectName);
	QApplication::setApplicationVersion(projectVersion);
	QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps, true);

#ifdef BUILD_GLES2
	QSurfaceFormat format;
	format.setVersion(3, 0);
	QSurfaceFormat::setDefaultFormat(format);
#endif

	GBAApp application(argc, argv, &configController);

#ifndef Q_OS_MAC
	QApplication::setWindowIcon(QIcon(":/res/mgba-256.png"));
#endif

	QTranslator qtTranslator;
	qtTranslator.load(locale, "qt", "_", QLibraryInfo::location(QLibraryInfo::TranslationsPath));
	application.installTranslator(&qtTranslator);

#ifdef QT_STATIC
	QTranslator qtStaticTranslator;
	qtStaticTranslator.load(locale, "qtbase", "_", ":/translations/");
	application.installTranslator(&qtStaticTranslator);
#endif

	QTranslator langTranslator;
	langTranslator.load(locale, binaryName, "-", ":/translations/");
	application.installTranslator(&langTranslator);

	Window* w = application.newWindow();
	if (loaded) {
		w->argumentsPassed(&args);
	} else {
		w->loadConfig();
	}
	freeArguments(&args);

	if (graphicsOpts.multiplier) {
		w->resizeFrame(QSize(GBA_VIDEO_HORIZONTAL_PIXELS * graphicsOpts.multiplier, GBA_VIDEO_VERTICAL_PIXELS * graphicsOpts.multiplier));
	}
	if (graphicsOpts.fullscreen) {
		w->enterFullScreen();
	}

	w->show();

	return application.exec();
}

#ifdef _WIN32
#include <mgba-util/string.h>
#include <vector>

extern "C"
int wmain(int argc, wchar_t* argv[]) {
	std::vector<char*> argv8;
	for (int i = 0; i < argc; ++i) {
		argv8.push_back(utf16to8(reinterpret_cast<uint16_t*>(argv[i]), wcslen(argv[i]) * 2));
	}
	int ret = main(argc, argv8.data());
	for (char* ptr : argv8) {
		free(ptr);
	}
	return ret;
}
#endif
<commit_msg>Qt: Parse --version flag<commit_after>/* Copyright (c) 2013-2014 Jeffrey Pfau
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// This must be defined before anything else is included.
#define SDL_MAIN_HANDLED

#include "ConfigController.h"
#include "GBAApp.h"
#include "Window.h"

#include <mgba/core/version.h>
#include <mgba/gba/interface.h>

#include <QLibraryInfo>
#include <QTranslator>

#ifdef BUILD_GLES2
#include <QSurfaceFormat>
#endif

#ifdef QT_STATIC
#include <QtPlugin>
#ifdef Q_OS_WIN
Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin);
Q_IMPORT_PLUGIN(QWindowsVistaStylePlugin);
#ifdef BUILD_QT_MULTIMEDIA
Q_IMPORT_PLUGIN(QWindowsAudioPlugin);
Q_IMPORT_PLUGIN(DSServicePlugin);
#endif
#elif defined(Q_OS_MAC)
Q_IMPORT_PLUGIN(QCocoaIntegrationPlugin);
#ifdef BUILD_QT_MULTIMEDIA
Q_IMPORT_PLUGIN(CoreAudioPlugin);
Q_IMPORT_PLUGIN(AVFServicePlugin);
#endif
#endif
#endif

using namespace QGBA;

int main(int argc, char* argv[]) {
#ifdef BUILD_SDL
#if SDL_VERSION_ATLEAST(2, 0, 0) // CPP does not shortcut function lookup
	SDL_SetMainReady();
#endif
#endif

	ConfigController configController;

	QLocale locale;
	if (!configController.getQtOption("language").isNull()) {
		locale = QLocale(configController.getQtOption("language").toString());
		QLocale::setDefault(locale);
	}

	mArguments args;
	mGraphicsOpts graphicsOpts;
	mSubParser subparser;
	initParserForGraphics(&subparser, &graphicsOpts);
	bool loaded = configController.parseArguments(&args, argc, argv, &subparser);
	if (loaded) {
		if (args.showHelp) {
			usage(argv[0], subparser.usage);
			freeArguments(&args);
			return 0;
		}
		if (args.showVersion) {
			version(argv[0]);
			freeArguments(&args);
			return 0;
		}
	}

	QApplication::setApplicationName(projectName);
	QApplication::setApplicationVersion(projectVersion);
	QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps, true);

#ifdef BUILD_GLES2
	QSurfaceFormat format;
	format.setVersion(3, 0);
	QSurfaceFormat::setDefaultFormat(format);
#endif

	GBAApp application(argc, argv, &configController);

#ifndef Q_OS_MAC
	QApplication::setWindowIcon(QIcon(":/res/mgba-256.png"));
#endif

	QTranslator qtTranslator;
	qtTranslator.load(locale, "qt", "_", QLibraryInfo::location(QLibraryInfo::TranslationsPath));
	application.installTranslator(&qtTranslator);

#ifdef QT_STATIC
	QTranslator qtStaticTranslator;
	qtStaticTranslator.load(locale, "qtbase", "_", ":/translations/");
	application.installTranslator(&qtStaticTranslator);
#endif

	QTranslator langTranslator;
	langTranslator.load(locale, binaryName, "-", ":/translations/");
	application.installTranslator(&langTranslator);

	Window* w = application.newWindow();
	if (loaded) {
		w->argumentsPassed(&args);
	} else {
		w->loadConfig();
	}
	freeArguments(&args);

	if (graphicsOpts.multiplier) {
		w->resizeFrame(QSize(GBA_VIDEO_HORIZONTAL_PIXELS * graphicsOpts.multiplier, GBA_VIDEO_VERTICAL_PIXELS * graphicsOpts.multiplier));
	}
	if (graphicsOpts.fullscreen) {
		w->enterFullScreen();
	}

	w->show();

	return application.exec();
}

#ifdef _WIN32
#include <mgba-util/string.h>
#include <vector>

extern "C"
int wmain(int argc, wchar_t* argv[]) {
	std::vector<char*> argv8;
	for (int i = 0; i < argc; ++i) {
		argv8.push_back(utf16to8(reinterpret_cast<uint16_t*>(argv[i]), wcslen(argv[i]) * 2));
	}
	int ret = main(argc, argv8.data());
	for (char* ptr : argv8) {
		free(ptr);
	}
	return ret;
}
#endif
<|endoftext|>


<commit_before>
//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2011 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "SDLWindow.h"

#include "Player.h"
#include "MouseEvent.h"
#include "SDLTouchInputDevice.h"

#include "../base/Exception.h"
#include "../base/Logger.h"
#include "../base/ScopeTimer.h"
#include "../base/OSHelper.h"
#include "../base/StringHelper.h"

#include "../graphics/GLContext.h"
#include "../graphics/GLContextManager.h"

#ifdef WIN32
#undef WIN32_LEAN_AND_MEAN
#endif
#include <SDL2/SDL_syswm.h>
#include <SDL2/SDL_events.h>

#include <iostream>

using namespace std;

namespace avg {

SDLWindow::SDLWindow(const DisplayParams& dp, const WindowParams& wp, GLConfig glConfig)
    : Window(wp, dp.isFullscreen()),
      m_pSDLWindow(0),
      m_SDLGLContext(0),
      m_LastMousePos(IntPoint(-1, -1))
{
    IntPoint pos = getPos();
    if (pos.x == -1) {
        pos.x = SDL_WINDOWPOS_UNDEFINED;
        pos.y = SDL_WINDOWPOS_UNDEFINED;
    }
    unsigned int flags = SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL;
    if (dp.isFullscreen()) {
        flags |= SDL_WINDOW_FULLSCREEN;
    }
    if (!wp.m_bHasWindowFrame) {
        flags |= SDL_WINDOW_BORDERLESS;
    }

    switch (dp.getBPP()) {
        case 24:
            SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
            SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
            SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
            SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 24);
            break;
        case 16:
            SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
            SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6);
            SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
            SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 16);
            break;
        default:
            AVG_LOG_ERROR("Unsupported bpp " << dp.getBPP() << "in SDLWindow::init()");
            exit(-1);
    }
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
    SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    if (glConfig.m_bGLES) {
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
    }
    if (glConfig.m_bUseDebugContext) {
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
    }

    while (glConfig.m_MultiSampleSamples && !m_SDLGLContext) {
        if (glConfig.m_MultiSampleSamples > 1) {
            SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
            SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES,
                    glConfig.m_MultiSampleSamples);
        } else {
            SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);
            SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);
        }
        m_pSDLWindow = SDL_CreateWindow(wp.m_sTitle.c_str(), pos.x, pos.y,
                getSize().x, getSize().y, flags);
        if (m_pSDLWindow) {
            m_SDLGLContext = SDL_GL_CreateContext(m_pSDLWindow);
        } else {
            m_SDLGLContext = 0;
        }
        if (!m_SDLGLContext) {
            glConfig.m_MultiSampleSamples = GLContext::nextMultiSampleValue(
                    glConfig.m_MultiSampleSamples);
        }
    }

#ifndef __linux__
    glConfig.m_bUseDebugContext = false;
#endif

    if (!m_SDLGLContext) {
        throw Exception(AVG_ERR_UNSUPPORTED, string("Creating window failed: ")
                + SDL_GetError() + ". (size=" + toString(wp.m_Size) + ", bpp=" +
                toString(dp.getBPP()) + ").");
    }
    SDL_GL_MakeCurrent(m_pSDLWindow, m_SDLGLContext);
    SDL_SysWMinfo info;
    SDL_VERSION(&info.version);
    int rc = SDL_GetWindowWMInfo(m_pSDLWindow, &info);
    AVG_ASSERT(rc != -1);
    GLContext* pGLContext =
            GLContextManager::get()->createContext(glConfig, wp.m_Size, &info);
    setGLContext(pGLContext);
    pGLContext->logConfig();
}

SDLWindow::~SDLWindow()
{
    if (m_pSDLWindow) {
        SDL_DestroyWindow(m_pSDLWindow);
    }
}

void SDLWindow::setTouchHandler(SDLTouchInputDevicePtr pInputDevice)
{
    m_pTouchInputDevice = pInputDevice;
}

bool SDLWindow::hasTouchHandler() const
{
    return (m_pTouchInputDevice != SDLTouchInputDevicePtr());
}

void SDLWindow::setTitle(const string& sTitle)
{
    SDL_SetWindowTitle(m_pSDLWindow, sTitle.c_str());
}

static ProfilingZoneID SwapBufferProfilingZone("Render - swap buffers");

void SDLWindow::swapBuffers() const
{
    ScopeTimer timer(SwapBufferProfilingZone);
    getGLContext()->activate();
#ifdef AVG_ENABLE_RPI
    SDL_GL_SwapWindow(m_pSDLWindow);
#else
    getGLContext()->swapBuffers();
#endif
    GLContext::checkError("swapBuffers()");
}

vector<EventPtr> SDLWindow::pollEvents()
{
    SDL_Event sdlEvent;
    vector<EventPtr> events;
    KeyEventPtr pPendingKeyEvent;

    int numEvents = 0;
    cerr << "----pollEvents----" << endl;
    while (SDL_PollEvent(&sdlEvent)) {
        numEvents++;
        EventPtr pNewEvent;
        switch (sdlEvent.type) {
            case SDL_MOUSEMOTION:
                {
                    pNewEvent = createMouseEvent(Event::CURSOR_MOTION, sdlEvent,
                            MouseEvent::NO_BUTTON);
                    CursorEventPtr pNewCursorEvent =
                            boost::dynamic_pointer_cast<CursorEvent>(pNewEvent);
                    if (!events.empty()) {
                        CursorEventPtr pLastEvent =
                                boost::dynamic_pointer_cast<CursorEvent>(events.back());
                        if (pLastEvent && *pNewCursorEvent == *pLastEvent) {
                            pNewEvent = EventPtr();
                        }
                    }
                }
                break;
            case SDL_MOUSEBUTTONDOWN:
                pNewEvent = createMouseButtonEvent(Event::CURSOR_DOWN, sdlEvent);
                break;
            case SDL_MOUSEBUTTONUP:
                pNewEvent = createMouseButtonEvent(Event::CURSOR_UP, sdlEvent);
                break;
            case SDL_JOYAXISMOTION:
//                pNewEvent = createAxisEvent(sdlEvent));
                break;
            case SDL_JOYBUTTONDOWN:
//                pNewEvent = createButtonEvent(Event::BUTTON_DOWN, sdlEvent));
                break;
            case SDL_JOYBUTTONUP:
//                pNewEvent = createButtonEvent(Event::BUTTON_UP, sdlEvent));
                break;
            case SDL_KEYDOWN:
                cerr << "down" << endl;
                if (pPendingKeyEvent) {
                    events.push_back(pPendingKeyEvent);
                }
                pPendingKeyEvent = createKeyEvent(Event::KEY_DOWN, sdlEvent);
                break;
            case SDL_KEYUP:
                cerr << "up" << endl;
                pNewEvent = createKeyEvent(Event::KEY_UP, sdlEvent);
                break;
            case SDL_TEXTINPUT:
                cerr << "Text: " << sdlEvent.text.text << endl;
                // We ignore repeating keys.
                if (pPendingKeyEvent) {
                    pPendingKeyEvent->setText(sdlEvent.text.text);
                    pNewEvent = pPendingKeyEvent;
                    pPendingKeyEvent = KeyEventPtr();
                }
                break;
            case SDL_QUIT:
                pNewEvent = EventPtr(new Event(Event::QUIT, Event::NONE));
                break;
            case SDL_FINGERMOTION:
            case SDL_FINGERDOWN:
            case SDL_FINGERUP:
                if (m_pTouchInputDevice) {
                    m_pTouchInputDevice->onTouchEvent(this, sdlEvent);
                }
                break;
            default:
                // Ignore unknown events.
                break;
        }
        if (pNewEvent) {
            events.push_back(pNewEvent);
        }
    }
    if (pPendingKeyEvent) {
        events.push_back(pPendingKeyEvent);
        pPendingKeyEvent = KeyEventPtr();
    }
    if (numEvents > 124) {
        AVG_TRACE(Logger::category::EVENTS, Logger::severity::WARNING,
                "SDL Event queue full, dropping events.");
    }
    return events;
}

void SDLWindow::setMousePos(const IntPoint& pos)
{
    SDL_WarpMouseInWindow(m_pSDLWindow, pos.x, pos.y);
}

void SDLWindow::setGamma(float red, float green, float blue)
{
    Uint16 redRamp[256];
    Uint16 greenRamp[256];
    Uint16 blueRamp[256];
    SDL_CalculateGammaRamp(red, redRamp);
    SDL_CalculateGammaRamp(green, greenRamp);
    SDL_CalculateGammaRamp(blue, blueRamp);
    int rc = SDL_SetWindowGammaRamp(m_pSDLWindow, redRamp, greenRamp, blueRamp);
    if (rc != 0) {
        AVG_LOG_INFO("Unable to set display gamma.");
    }
}

#ifdef _WIN32
HWND SDLWindow::getWinHWnd()
{
    SDL_SysWMinfo info;
    SDL_VERSION(&info.version);
    bool bOK = SDL_GetWindowWMInfo(m_pSDLWindow, &info);
    AVG_ASSERT(bOK);
    return info.info.win.window;

}
#endif

#if defined(__linux__) && !defined(AVG_ENABLE_RPI)
::Display* SDLWindow::getX11Display()
{
    SDL_SysWMinfo info;
    SDL_VERSION(&info.version);
    bool bOk = SDL_GetWindowWMInfo(m_pSDLWindow, &info);
    AVG_ASSERT(bOk);
    return info.info.x11.display;
}

::Window SDLWindow::getX11Window()
{
    SDL_SysWMinfo info;
    SDL_VERSION(&info.version);
    bool bOk = SDL_GetWindowWMInfo(m_pSDLWindow, &info);
    AVG_ASSERT(bOk);
    return info.info.x11.window;
}
#endif

EventPtr SDLWindow::createMouseEvent(Event::Type type, const SDL_Event& sdlEvent,
        long button)
{
    int x, y;
    Uint8 buttonState = SDL_GetMouseState(&x, &y);
    IntRect viewport = getViewport();
    IntPoint size = getSize();
    x = int((x*viewport.width())/size.x);
    y = int((y*viewport.height())/size.y);
    glm::vec2 speed;
    if (m_LastMousePos.x == -1) {
        speed = glm::vec2(0,0);
    } else {
        float lastFrameTime = 1000/Player::get()->getEffectiveFramerate();
        speed = glm::vec2(x-m_LastMousePos.x, y-m_LastMousePos.y)/lastFrameTime;
    }
    MouseEventPtr pEvent(new MouseEvent(type, (buttonState & SDL_BUTTON(1)) != 0,
            (buttonState & SDL_BUTTON(2)) != 0, (buttonState & SDL_BUTTON(3)) != 0,
            IntPoint(x, y), button, speed));

    m_LastMousePos = pEvent->getPos();
    return pEvent;
}

EventPtr SDLWindow::createMouseButtonEvent(Event::Type type, const SDL_Event& sdlEvent)
{
    long button = 0;
    switch (sdlEvent.button.button) {
        case SDL_BUTTON_LEFT:
            button = MouseEvent::LEFT_BUTTON;
            break;
        case SDL_BUTTON_MIDDLE:
            button = MouseEvent::MIDDLE_BUTTON;
            break;
        case SDL_BUTTON_RIGHT:
            button = MouseEvent::RIGHT_BUTTON;
            break;
        default:
            AVG_ASSERT(false);
    }
    return createMouseEvent(type, sdlEvent, button);

}

KeyEventPtr SDLWindow::createKeyEvent(Event::Type type, const SDL_Event& sdlEvent)
{
/*
    cerr << "scancode: " << sdlEvent.key.keysym.scancode <<
            ", sym: " << sdlEvent.key.keysym.sym <<
            ", name: " << SDL_GetKeyName(sdlEvent.key.keysym.sym) <<
            ", mod: " << sdlEvent.key.keysym.mod << endl;
            */
    KeyEventPtr pEvent(new KeyEvent(type,
            sdlEvent.key.keysym.scancode, SDL_GetKeyName(sdlEvent.key.keysym.sym),
            (unsigned)sdlEvent.key.keysym.mod));
    return pEvent;
}

}
<commit_msg>Removed console spam<commit_after>
//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2011 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "SDLWindow.h"

#include "Player.h"
#include "MouseEvent.h"
#include "SDLTouchInputDevice.h"

#include "../base/Exception.h"
#include "../base/Logger.h"
#include "../base/ScopeTimer.h"
#include "../base/OSHelper.h"
#include "../base/StringHelper.h"

#include "../graphics/GLContext.h"
#include "../graphics/GLContextManager.h"

#ifdef WIN32
#undef WIN32_LEAN_AND_MEAN
#endif
#include <SDL2/SDL_syswm.h>
#include <SDL2/SDL_events.h>

#include <iostream>

using namespace std;

namespace avg {

SDLWindow::SDLWindow(const DisplayParams& dp, const WindowParams& wp, GLConfig glConfig)
    : Window(wp, dp.isFullscreen()),
      m_pSDLWindow(0),
      m_SDLGLContext(0),
      m_LastMousePos(IntPoint(-1, -1))
{
    IntPoint pos = getPos();
    if (pos.x == -1) {
        pos.x = SDL_WINDOWPOS_UNDEFINED;
        pos.y = SDL_WINDOWPOS_UNDEFINED;
    }
    unsigned int flags = SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL;
    if (dp.isFullscreen()) {
        flags |= SDL_WINDOW_FULLSCREEN;
    }
    if (!wp.m_bHasWindowFrame) {
        flags |= SDL_WINDOW_BORDERLESS;
    }

    switch (dp.getBPP()) {
        case 24:
            SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
            SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
            SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
            SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 24);
            break;
        case 16:
            SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
            SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6);
            SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
            SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 16);
            break;
        default:
            AVG_LOG_ERROR("Unsupported bpp " << dp.getBPP() << "in SDLWindow::init()");
            exit(-1);
    }
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
    SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    if (glConfig.m_bGLES) {
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
    }
    if (glConfig.m_bUseDebugContext) {
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
    }

    while (glConfig.m_MultiSampleSamples && !m_SDLGLContext) {
        if (glConfig.m_MultiSampleSamples > 1) {
            SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
            SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES,
                    glConfig.m_MultiSampleSamples);
        } else {
            SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);
            SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);
        }
        m_pSDLWindow = SDL_CreateWindow(wp.m_sTitle.c_str(), pos.x, pos.y,
                getSize().x, getSize().y, flags);
        if (m_pSDLWindow) {
            m_SDLGLContext = SDL_GL_CreateContext(m_pSDLWindow);
        } else {
            m_SDLGLContext = 0;
        }
        if (!m_SDLGLContext) {
            glConfig.m_MultiSampleSamples = GLContext::nextMultiSampleValue(
                    glConfig.m_MultiSampleSamples);
        }
    }

#ifndef __linux__
    glConfig.m_bUseDebugContext = false;
#endif

    if (!m_SDLGLContext) {
        throw Exception(AVG_ERR_UNSUPPORTED, string("Creating window failed: ")
                + SDL_GetError() + ". (size=" + toString(wp.m_Size) + ", bpp=" +
                toString(dp.getBPP()) + ").");
    }
    SDL_GL_MakeCurrent(m_pSDLWindow, m_SDLGLContext);
    SDL_SysWMinfo info;
    SDL_VERSION(&info.version);
    int rc = SDL_GetWindowWMInfo(m_pSDLWindow, &info);
    AVG_ASSERT(rc != -1);
    GLContext* pGLContext =
            GLContextManager::get()->createContext(glConfig, wp.m_Size, &info);
    setGLContext(pGLContext);
    pGLContext->logConfig();
}

SDLWindow::~SDLWindow()
{
    if (m_pSDLWindow) {
        SDL_DestroyWindow(m_pSDLWindow);
    }
}

void SDLWindow::setTouchHandler(SDLTouchInputDevicePtr pInputDevice)
{
    m_pTouchInputDevice = pInputDevice;
}

bool SDLWindow::hasTouchHandler() const
{
    return (m_pTouchInputDevice != SDLTouchInputDevicePtr());
}

void SDLWindow::setTitle(const string& sTitle)
{
    SDL_SetWindowTitle(m_pSDLWindow, sTitle.c_str());
}

static ProfilingZoneID SwapBufferProfilingZone("Render - swap buffers");

void SDLWindow::swapBuffers() const
{
    ScopeTimer timer(SwapBufferProfilingZone);
    getGLContext()->activate();
#ifdef AVG_ENABLE_RPI
    SDL_GL_SwapWindow(m_pSDLWindow);
#else
    getGLContext()->swapBuffers();
#endif
    GLContext::checkError("swapBuffers()");
}

vector<EventPtr> SDLWindow::pollEvents()
{
    SDL_Event sdlEvent;
    vector<EventPtr> events;
    KeyEventPtr pPendingKeyEvent;

    int numEvents = 0;
    while (SDL_PollEvent(&sdlEvent)) {
        numEvents++;
        EventPtr pNewEvent;
        switch (sdlEvent.type) {
            case SDL_MOUSEMOTION:
                {
                    pNewEvent = createMouseEvent(Event::CURSOR_MOTION, sdlEvent,
                            MouseEvent::NO_BUTTON);
                    CursorEventPtr pNewCursorEvent =
                            boost::dynamic_pointer_cast<CursorEvent>(pNewEvent);
                    if (!events.empty()) {
                        CursorEventPtr pLastEvent =
                                boost::dynamic_pointer_cast<CursorEvent>(events.back());
                        if (pLastEvent && *pNewCursorEvent == *pLastEvent) {
                            pNewEvent = EventPtr();
                        }
                    }
                }
                break;
            case SDL_MOUSEBUTTONDOWN:
                pNewEvent = createMouseButtonEvent(Event::CURSOR_DOWN, sdlEvent);
                break;
            case SDL_MOUSEBUTTONUP:
                pNewEvent = createMouseButtonEvent(Event::CURSOR_UP, sdlEvent);
                break;
            case SDL_JOYAXISMOTION:
//                pNewEvent = createAxisEvent(sdlEvent));
                break;
            case SDL_JOYBUTTONDOWN:
//                pNewEvent = createButtonEvent(Event::BUTTON_DOWN, sdlEvent));
                break;
            case SDL_JOYBUTTONUP:
//                pNewEvent = createButtonEvent(Event::BUTTON_UP, sdlEvent));
                break;
            case SDL_KEYDOWN:
//                cerr << "down" << endl;
                if (pPendingKeyEvent) {
                    events.push_back(pPendingKeyEvent);
                }
                pPendingKeyEvent = createKeyEvent(Event::KEY_DOWN, sdlEvent);
                break;
            case SDL_KEYUP:
//                cerr << "up" << endl;
                pNewEvent = createKeyEvent(Event::KEY_UP, sdlEvent);
                break;
            case SDL_TEXTINPUT:
//                cerr << "Text: " << sdlEvent.text.text << endl;
                // We ignore repeating keys.
                if (pPendingKeyEvent) {
                    pPendingKeyEvent->setText(sdlEvent.text.text);
                    pNewEvent = pPendingKeyEvent;
                    pPendingKeyEvent = KeyEventPtr();
                }
                break;
            case SDL_QUIT:
                pNewEvent = EventPtr(new Event(Event::QUIT, Event::NONE));
                break;
            case SDL_FINGERMOTION:
            case SDL_FINGERDOWN:
            case SDL_FINGERUP:
                if (m_pTouchInputDevice) {
                    m_pTouchInputDevice->onTouchEvent(this, sdlEvent);
                }
                break;
            default:
                // Ignore unknown events.
                break;
        }
        if (pNewEvent) {
            events.push_back(pNewEvent);
        }
    }
    if (pPendingKeyEvent) {
        events.push_back(pPendingKeyEvent);
        pPendingKeyEvent = KeyEventPtr();
    }
    if (numEvents > 124) {
        AVG_TRACE(Logger::category::EVENTS, Logger::severity::WARNING,
                "SDL Event queue full, dropping events.");
    }
    return events;
}

void SDLWindow::setMousePos(const IntPoint& pos)
{
    SDL_WarpMouseInWindow(m_pSDLWindow, pos.x, pos.y);
}

void SDLWindow::setGamma(float red, float green, float blue)
{
    Uint16 redRamp[256];
    Uint16 greenRamp[256];
    Uint16 blueRamp[256];
    SDL_CalculateGammaRamp(red, redRamp);
    SDL_CalculateGammaRamp(green, greenRamp);
    SDL_CalculateGammaRamp(blue, blueRamp);
    int rc = SDL_SetWindowGammaRamp(m_pSDLWindow, redRamp, greenRamp, blueRamp);
    if (rc != 0) {
        AVG_LOG_INFO("Unable to set display gamma.");
    }
}

#ifdef _WIN32
HWND SDLWindow::getWinHWnd()
{
    SDL_SysWMinfo info;
    SDL_VERSION(&info.version);
    bool bOK = SDL_GetWindowWMInfo(m_pSDLWindow, &info);
    AVG_ASSERT(bOK);
    return info.info.win.window;

}
#endif

#if defined(__linux__) && !defined(AVG_ENABLE_RPI)
::Display* SDLWindow::getX11Display()
{
    SDL_SysWMinfo info;
    SDL_VERSION(&info.version);
    bool bOk = SDL_GetWindowWMInfo(m_pSDLWindow, &info);
    AVG_ASSERT(bOk);
    return info.info.x11.display;
}

::Window SDLWindow::getX11Window()
{
    SDL_SysWMinfo info;
    SDL_VERSION(&info.version);
    bool bOk = SDL_GetWindowWMInfo(m_pSDLWindow, &info);
    AVG_ASSERT(bOk);
    return info.info.x11.window;
}
#endif

EventPtr SDLWindow::createMouseEvent(Event::Type type, const SDL_Event& sdlEvent,
        long button)
{
    int x, y;
    Uint8 buttonState = SDL_GetMouseState(&x, &y);
    IntRect viewport = getViewport();
    IntPoint size = getSize();
    x = int((x*viewport.width())/size.x);
    y = int((y*viewport.height())/size.y);
    glm::vec2 speed;
    if (m_LastMousePos.x == -1) {
        speed = glm::vec2(0,0);
    } else {
        float lastFrameTime = 1000/Player::get()->getEffectiveFramerate();
        speed = glm::vec2(x-m_LastMousePos.x, y-m_LastMousePos.y)/lastFrameTime;
    }
    MouseEventPtr pEvent(new MouseEvent(type, (buttonState & SDL_BUTTON(1)) != 0,
            (buttonState & SDL_BUTTON(2)) != 0, (buttonState & SDL_BUTTON(3)) != 0,
            IntPoint(x, y), button, speed));

    m_LastMousePos = pEvent->getPos();
    return pEvent;
}

EventPtr SDLWindow::createMouseButtonEvent(Event::Type type, const SDL_Event& sdlEvent)
{
    long button = 0;
    switch (sdlEvent.button.button) {
        case SDL_BUTTON_LEFT:
            button = MouseEvent::LEFT_BUTTON;
            break;
        case SDL_BUTTON_MIDDLE:
            button = MouseEvent::MIDDLE_BUTTON;
            break;
        case SDL_BUTTON_RIGHT:
            button = MouseEvent::RIGHT_BUTTON;
            break;
        default:
            AVG_ASSERT(false);
    }
    return createMouseEvent(type, sdlEvent, button);

}

KeyEventPtr SDLWindow::createKeyEvent(Event::Type type, const SDL_Event& sdlEvent)
{
/*
    cerr << "scancode: " << sdlEvent.key.keysym.scancode <<
            ", sym: " << sdlEvent.key.keysym.sym <<
            ", name: " << SDL_GetKeyName(sdlEvent.key.keysym.sym) <<
            ", mod: " << sdlEvent.key.keysym.mod << endl;
            */
    KeyEventPtr pEvent(new KeyEvent(type,
            sdlEvent.key.keysym.scancode, SDL_GetKeyName(sdlEvent.key.keysym.sym),
            (unsigned)sdlEvent.key.keysym.mod));
    return pEvent;
}

}
<|endoftext|>


<commit_before>#include "ex13_49_Message.h"
#include <iostream>

void swap(Message &lhs, Message &rhs)
{
    using std::swap;
    for (auto f : lhs.folders)
        f->remMsg(&lhs);
    std::cout << "Remove message from folders" << std::endl; // debug

    for (auto f : rhs.folders)
        f->remMsg(&rhs);
    std::cout << "Remove message from folders" << std::endl; // debug

    swap(lhs.folders, rhs.folders);
    swap(lhs.contents, rhs.contents);

    std::cout << "Message members swaped" << std::endl; // debug

    for (auto f : lhs.folders)
        f->addMsg(&lhs);
    std::cout << "Added message to folders" << std::endl; // debug

    for (auto f : rhs.folders)
        f->addMsg(&rhs);
    std::cout << "Added message to folders" << std::endl; // debug
}

Message::Message(const Message &m) : contents(m.contents), folders(m.folders)
{
    add_to_Folders(m);
}

Message::~Message()
{
    remove_from_Folders();
}

void Message::save(Folder &f)
{
    folders.insert(&f);
    f.addMsg(this);
}

void Message::remove(Folder &f)
{
    folders.erase(&f);
    f.remMsg(this);
}

void Message::add_to_Folders(const Message &m)
{
    for (auto f : m.folders)
        f->addMsg(this);
    std::cout << "Added message to folders" << std::endl; // debug
}

void Message::remove_from_Folders()
{
    for (auto f : folders)
        f->remMsg(this);
    std::cout << "Remove message from folders" << std::endl; // debug
}

Message& Message::operator=(const Message &rhs)
{
    remove_from_Folders();
    contents = rhs.contents;
    folders = rhs.folders;
    std::cout << "Message members assgined" << std::endl; // debug
    add_to_Folders(rhs);
    return *this;
}

void Message::print_debug()
{
    std::cout << contents << ": ";
    for (auto f : folders)
        std::cout << f->fldr() << " ";
    std::cout << std::endl;
}

Message& Message::operator = (Message &&rhs) NOEXCEPT
{
    remove_from_Folders();
    contents = std::move(rhs.contents);
    folders = std::move(rhs.folders);
    std::cout << "Message members moved" << std::endl; // debug
    return *this;
}

// Folder Implementation

void swap(Folder &lhs, Folder &rhs)
{
    using std::swap;
    for (auto m : lhs.msgs)
        m->remFldr(&lhs);
    std::cout << "clear folder" << std::endl; // debug

    for (auto m : rhs.msgs)
        m->remFldr(&rhs);
    std::cout << "clear folder" << std::endl; // debug

    swap(lhs.name, rhs.name);
    swap(lhs.msgs, rhs.msgs);
    std::cout << "Folder members swaped" << std::endl; // debug

    for (auto m : lhs.msgs)
        m->addFldr(&lhs);
    std::cout << "Added messages to folder" << std::endl; // debug

    for (auto m : rhs.msgs)
        m->addFldr(&rhs);
    std::cout << "Added messages to folder" << std::endl; // debug
}

void Folder::add_to_Message(const Folder &f)
{
    for (auto m : f.msgs)
        m->addFldr(this);
    std::cout << "Added messages to folder" << std::endl; // debug
}

Folder::Folder(const Folder &f) : name(f.name), msgs(f.msgs)
{
    add_to_Message(f);
}

void Folder::remove_from_Message()
{
    for (auto m : msgs)
        m->remFldr(this);
    std::cout << "clear folder" << std::endl; // debug
}

Folder::~Folder()
{
    remove_from_Message();
}

Folder& Folder::operator =(const Folder &rhs)
{
    remove_from_Message();
    name = rhs.name;
    msgs = rhs.msgs;
    std::cout << "Folder members assigned" << std::endl; // debug
    add_to_Message(rhs);
    return *this;
}

void Folder::print_debug()
{
    std::cout << name << ": ";
    for (auto m : msgs)
        std::cout << m->msg() << " ";
    std::cout << std::endl;
}

Folder& Folder::operator=(Folder &&rhs) NOEXCEPT
{
    remove_from_Message();
    name = std::move(rhs.name);
    msgs = std::move(rhs.msgs);
    std::cout << "Folder members moved" << std::endl; // debug
    return *this;
}
<commit_msg>Update ex13_49_Message.cpp<commit_after>#include "ex13_49_Message.h"
#include <iostream>

void swap(Message &lhs, Message &rhs)
{
    using std::swap;
    for (auto f : lhs.folders)
        f->remMsg(&lhs);
    std::cout << "Remove message from folders" << std::endl; // debug

    for (auto f : rhs.folders)
        f->remMsg(&rhs);
    std::cout << "Remove message from folders" << std::endl; // debug

    swap(lhs.folders, rhs.folders);
    swap(lhs.contents, rhs.contents);

    std::cout << "Message members swaped" << std::endl; // debug

    for (auto f : lhs.folders)
        f->addMsg(&lhs);
    std::cout << "Added message to folders" << std::endl; // debug

    for (auto f : rhs.folders)
        f->addMsg(&rhs);
    std::cout << "Added message to folders" << std::endl; // debug
}

Message::Message(const Message &m) : contents(m.contents), folders(m.folders)
{
    add_to_Folders(m);
}

Message::~Message()
{
    remove_from_Folders();
}

void Message::save(Folder &f)
{
    folders.insert(&f);
    f.addMsg(this);
}

void Message::remove(Folder &f)
{
    folders.erase(&f);
    f.remMsg(this);
}

void Message::add_to_Folders(const Message &m)
{
    for (auto f : m.folders)
        f->addMsg(this);
    std::cout << "Added message to folders" << std::endl; // debug
}

void Message::remove_from_Folders()
{
    for (auto f : folders)
        f->remMsg(this);
    std::cout << "Remove message from folders" << std::endl; // debug
}

Message& Message::operator=(const Message &rhs)
{
    remove_from_Folders();
    contents = rhs.contents;
    folders = rhs.folders;
    std::cout << "Message members assgined" << std::endl; // debug
    add_to_Folders(rhs);
    return *this;
}

void Message::print_debug()
{
    std::cout << contents << ": ";
    for (auto f : folders)
        std::cout << f->fldr() << " ";
    std::cout << std::endl;
}

void Message::move_Folders(Message *m)
{
	folders = std::move(m->folders);
	for (auto f : folders)
	{
		f->remMsg(m);
		f->addMsg(this);
	}
	m->folders.clear();
}

Message::Message(Message &&m) : contents(std::move(m.contents))
{
    move_Folders(&m);
}

Message& Message::operator= (Message &&rhs)
{
    if (this != &rhs)
	{
		remove_from_Folders();
		contents = std::move(rhs.contents);
		move_Folders(&rhs);
	}
	std::cout << "Message members moved" << std::endl; // debug
	return *this;
}

// Folder Implementation

void swap(Folder &lhs, Folder &rhs)
{
    using std::swap;
    for (auto m : lhs.msgs)
        m->remFldr(&lhs);
    std::cout << "clear folder" << std::endl; // debug

    for (auto m : rhs.msgs)
        m->remFldr(&rhs);
    std::cout << "clear folder" << std::endl; // debug

    swap(lhs.name, rhs.name);
    swap(lhs.msgs, rhs.msgs);
    std::cout << "Folder members swaped" << std::endl; // debug

    for (auto m : lhs.msgs)
        m->addFldr(&lhs);
    std::cout << "Added messages to folder" << std::endl; // debug

    for (auto m : rhs.msgs)
        m->addFldr(&rhs);
    std::cout << "Added messages to folder" << std::endl; // debug
}

void Folder::add_to_Message(const Folder &f)
{
    for (auto m : f.msgs)
        m->addFldr(this);
    std::cout << "Added messages to folder" << std::endl; // debug
}

Folder::Folder(const Folder &f) : name(f.name), msgs(f.msgs)
{
    add_to_Message(f);
}

void Folder::remove_from_Message()
{
    for (auto m : msgs)
        m->remFldr(this);
    std::cout << "clear folder" << std::endl; // debug
}

Folder::~Folder()
{
    remove_from_Message();
}

Folder& Folder::operator =(const Folder &rhs)
{
    remove_from_Message();
    name = rhs.name;
    msgs = rhs.msgs;
    std::cout << "Folder members assigned" << std::endl; // debug
    add_to_Message(rhs);
    return *this;
}

void Folder::print_debug()
{
    std::cout << name << ": ";
    for (auto m : msgs)
        std::cout << m->msg() << " ";
    std::cout << std::endl;
}

void Folder::move_Messages(Folder *f)
{
	msgs = std::move(f->msgs);
	for (auto m : msgs)
	{
		m->remFldr(f);
		m->addFldr(this);
	}
	f->msgs.clear();
}

Folder::Folder(Folder&& f) : name(std::move(f.name))
{
	move_Messages(&f);
}

Folder& Folder::operator=(Folder &&rhs)
{
    if (this != &rhs)
	{
		remove_from_Message();
		name = std::move(rhs.name);
		move_Messages(&rhs);
	}
	std::cout << "Message members moved" << std::endl; // debug
	return *this;
}
<|endoftext|>


<commit_before>// -*- mode: c++; c-basic-offset:4 -*-

// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.

// Copyright (c) 2005,2018 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.

#include <cppunit/TextTestRunner.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/extensions/HelperMacros.h>

#include <cstring>
#include <string>

#include <unistd.h>

#include "GNURegex.h"

#include "Array.h"
#include "Byte.h"
#include "Int16.h"
#include "Float32.h"
#include "Int64.h"
#include "D4Enum.h"
#include "D4Dimensions.h"

#include "run_tests_cppunit.h"
#include "test_config.h"

using namespace CppUnit;
using namespace std;

namespace libdap {

class BigArrayTest: public TestFixture {
private:
    Byte *d_uint8 = nullptr;
    uint64_t num_eles;
    vector<unsigned char>buf_int8;

public:
    BigArrayTest() = default;

    ~BigArrayTest() = default;

    void setUp()
    {
        num_eles=1024*1024*1024;
        //num_eles=num_eles*2;
        num_eles = num_eles*5;
        num_eles = 4;
        buf_int8.resize(num_eles);
        buf_int8[0] = 0;
        //cout<<"buf_int8 0 is "<<(int)(buf_int8[0]) <<endl;
        buf_int8[num_eles/2] = 128;
        buf_int8[num_eles-1] = 255;

#if 0
        auto d4_dim_byte = new D4Dimension("dimension",num_eles);
        d_cardinal_byte->append_dim(d4_dim_byte);
        vector<unsigned char> buffer_u8;
        buffer_u8.resize(num_eles);
        d_cardinal_byte->val2buf(buffer_u8.data());
        delete d4_dim_byte;
        delete d_uint8;
#endif

    }

    void tearDown()
    {
    }

    CPPUNIT_TEST_SUITE (BigArrayTest);

    CPPUNIT_TEST (dap4_val2buf_buf2val);
    CPPUNIT_TEST (dap4_val2buf_value);
    CPPUNIT_TEST (dap2_set_value);

    CPPUNIT_TEST_SUITE_END();

    void dap4_val2buf_buf2val()
    {

        unique_ptr<Byte> d_uint8(new Byte("Byte"));
        Array d4_ar_uint8 = Array("Byte_array",d_uint8.get());
        unique_ptr<D4Dimension> d4_dim_byte(new D4Dimension("dimension",num_eles));
        d4_ar_uint8.append_dim(d4_dim_byte.get());
        d4_ar_uint8.val2buf(buf_int8.data());
        cout<<"the first value is "<<(int)(buf_int8[0]) <<endl;
        cout<<"the middle value is "<<(int)(buf_int8[num_eles/2]) <<endl;
        vector<unsigned char>d4_ar_val;
        d4_ar_val.resize(num_eles);

        // The following doesn't work for 64-bit integer
        void* d4_ar_val_ptr = (void*)(d4_ar_val.data());
        d4_ar_uint8.buf2val(&d4_ar_val_ptr);
        cout<<"the first value buf2val is "<<(int)(d4_ar_val[0]) <<endl;
        cout<<"the middle value buf2val is "<<(int)(d4_ar_val[num_eles/2]) <<endl;
        CPPUNIT_ASSERT(buf_int8[0] == d4_ar_val[0]);
        CPPUNIT_ASSERT(buf_int8[num_eles/2] == d4_ar_val[num_eles/2]);
        CPPUNIT_ASSERT(buf_int8[num_eles-1] == d4_ar_val[num_eles-1]);
    }

    void dap4_val2buf_value()
    {

        unique_ptr<Byte> d_uint8(new Byte("Byte"));
        Array d4_ar_uint8 = Array("Byte_array",d_uint8.get());
        unique_ptr<D4Dimension> d4_dim_byte(new D4Dimension("dimension",num_eles));
        d4_ar_uint8.append_dim(d4_dim_byte.get());
        d4_ar_uint8.val2buf(buf_int8.data());
        cout<<"the first value is "<<(int)(buf_int8[0]) <<endl;
        cout<<"the middle value is "<<(int)(buf_int8[num_eles/2]) <<endl;
        vector<unsigned char>d4_ar_val;
        d4_ar_val.resize(num_eles);

        // The following doesn't work for 64-bit integer
        d4_ar_uint8.value(d4_ar_val.data());
        cout<<"the first value buf2val is "<<(int)(d4_ar_val[0]) <<endl;
        cout<<"the middle value buf2val is "<<(int)(d4_ar_val[num_eles/2]) <<endl;
        CPPUNIT_ASSERT(buf_int8[0] == d4_ar_val[0]);
        CPPUNIT_ASSERT(buf_int8[num_eles/2] == d4_ar_val[num_eles/2]);
        CPPUNIT_ASSERT(buf_int8[num_eles-1] == d4_ar_val[num_eles-1]);
    }

    void dap2_set_value()
    {
        unique_ptr<Byte> d_uint8(new Byte("Byte"));
        Array d_ar_uint8 = Array("Byte_array",d_uint8.get());
        d_ar_uint8.append_dim(2);
        d_ar_uint8.append_dim(num_eles/2);
        d_ar_uint8.set_value((dods_byte *)buf_int8.data(),num_eles);
        cout<<"the first value is "<<(int)(buf_int8[0]) <<endl;
        cout<<"the middle value is "<<(int)(buf_int8[num_eles/2]) <<endl;
        vector<unsigned char>d_ar_val;
        d_ar_val.resize(num_eles);
        d_ar_uint8.value(d_ar_val.data());
        cout<<"the first value buf2val is "<<(int)(d_ar_val[0]) <<endl;
        cout<<"the middle value buf2val is "<<(int)(d_ar_val[num_eles/2]) <<endl;
        CPPUNIT_ASSERT(buf_int8[0] == d_ar_val[0]);
        CPPUNIT_ASSERT(buf_int8[num_eles/2] == d_ar_val[num_eles/2]);
        CPPUNIT_ASSERT(buf_int8[num_eles-1] == d_ar_val[num_eles-1]);

    }
#if 0

    void error_handling_test()
    {
        Array a1 = Array("a", d_int16);
        Array::Dim_iter i = a1.dim_begin();
        string msg;
        CPPUNIT_ASSERT_THROW(a1.dimension_name(i), InternalErr);
        CPPUNIT_ASSERT(!a1.check_semantics(msg));
    }

    void error_handling_2_test()
    {
        Array a1 = Array("a", d_int16);
        a1.append_dim(2, "dim_a");
        Array::Dim_iter i = a1.dim_begin();
        CPPUNIT_ASSERT(a1.dimension_size(i) == 2);
        CPPUNIT_ASSERT_THROW(a1.add_constraint(i, 2, 1, 1), Error);
        CPPUNIT_ASSERT_THROW(a1.add_constraint(i, 0, 1, 2), Error);
        CPPUNIT_ASSERT_THROW(a1.add_constraint(i, 0, 3, 1), Error);
    }

#endif

};

CPPUNIT_TEST_SUITE_REGISTRATION (BigArrayTest);

} // namespace libdap

int main(int argc, char *argv[])
{
    return run_tests<libdap::BigArrayTest>(argc, argv) ? 0: 1;
}
<commit_msg>HYRAX-863, adding the Big Array Test.<commit_after>// -*- mode: c++; c-basic-offset:4 -*-

// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.

// Copyright (c) 2005,2018 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.

#include <cppunit/TextTestRunner.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/extensions/HelperMacros.h>

#include <cstring>
#include <string>

#include <unistd.h>

#include "GNURegex.h"

#include "Array.h"
#include "Byte.h"
#include "D4Dimensions.h"

#include "run_tests_cppunit.h"
#include "test_config.h"

using namespace CppUnit;
using namespace std;

namespace libdap {

class BigArrayTest: public TestFixture {
private:
    Byte *d_uint8 = nullptr;
    uint64_t num_eles;
    vector<unsigned char>buf_int8;

public:
    BigArrayTest() = default;

    ~BigArrayTest() = default;

    void setUp()
    {
        num_eles=1024*1024*1024;
        num_eles = num_eles*5;

        // Uncomment this #if 0 block to test a trivial small array case.
#if 0
        num_eles = 4;
#endif
        buf_int8.resize(num_eles);
        buf_int8[0] = 0;
        buf_int8[num_eles/2] = 128;
        buf_int8[num_eles-1] = 255;

        DBG(cerr<<"Input buffer: The first value is "<<(int)(buf_int8[0]) <<endl);
        DBG(cerr<<"Input buffer: The middle value is "<<(int)(buf_int8[num_eles/2]) <<endl);
        DBG(cerr<<"Input buffer: The last value is "<<(int)(buf_int8[num_eles-1]) <<endl);

    }

    void tearDown()
    {
    }

    CPPUNIT_TEST_SUITE (BigArrayTest);

    CPPUNIT_TEST (dap4_val2buf_buf2val);
    CPPUNIT_TEST (dap4_val2buf_value);
    CPPUNIT_TEST (dap2_set_value);

    CPPUNIT_TEST_SUITE_END();

    void dap4_val2buf_buf2val()
    {

        unique_ptr<Byte> d_uint8(new Byte("Byte"));
        Array d4_ar_uint8 = Array("Byte_array",d_uint8.get());
        unique_ptr<D4Dimension> d4_dim_byte(new D4Dimension("dimension",num_eles));
        d4_ar_uint8.append_dim(d4_dim_byte.get());

        // Set the array value via val2buf
        d4_ar_uint8.val2buf(buf_int8.data());

        vector<unsigned char>d4_ar_val;
        d4_ar_val.resize(num_eles);
        void* d4_ar_val_ptr = (void*)(d4_ar_val.data());

        // Retrieve the array value via buf2val
        d4_ar_uint8.buf2val(&d4_ar_val_ptr);
#if 0
        cout<<"the first value buf2val is "<<(int)(d4_ar_val[0]) <<endl;
        cout<<"the middle value buf2val is "<<(int)(d4_ar_val[num_eles/2]) <<endl;
#endif
        DBG(cerr<<"DAP4 buf2val: The first value is "<<(int)(d4_ar_val[0]) <<endl);
        DBG(cerr<<"DAP4 buf2val: The middle value is "<<(int)(d4_ar_val[num_eles/2]) <<endl);
        DBG(cerr<<"DAP4 buf2val: The last value is "<<(int)(d4_ar_val[num_eles-1]) <<endl);

        CPPUNIT_ASSERT(buf_int8[0] == d4_ar_val[0]);
        CPPUNIT_ASSERT(buf_int8[num_eles/2] == d4_ar_val[num_eles/2]);
        CPPUNIT_ASSERT(buf_int8[num_eles-1] == d4_ar_val[num_eles-1]);
    }

    void dap4_val2buf_value()
    {

        unique_ptr<Byte> d_uint8(new Byte("Byte"));
        Array d4_ar_uint8 = Array("Byte_array",d_uint8.get());
        unique_ptr<D4Dimension> d4_dim_byte(new D4Dimension("dimension",num_eles));
        d4_ar_uint8.append_dim(d4_dim_byte.get());

        // Set the array value via val2buf
        d4_ar_uint8.val2buf(buf_int8.data());

        vector<unsigned char>d4_ar_val;
        d4_ar_val.resize(num_eles);

        // Retrieve the array value via value()
        d4_ar_uint8.value(d4_ar_val.data());
#if 0
        cout<<"the first value via value() is "<<(int)(d4_ar_val[0]) <<endl;
        cout<<"the middle value via value() is "<<(int)(d4_ar_val[num_eles/2]) <<endl;
#endif
        DBG(cerr<<"DAP4 value(): The first value is "<<(int)(d4_ar_val[0]) <<endl);
        DBG(cerr<<"DAP4 value(): The middle value is "<<(int)(d4_ar_val[num_eles/2]) <<endl);
        DBG(cerr<<"DAP4 value(): The last value is "<<(int)(d4_ar_val[num_eles-1]) <<endl);

        CPPUNIT_ASSERT(buf_int8[0] == d4_ar_val[0]);
        CPPUNIT_ASSERT(buf_int8[num_eles/2] == d4_ar_val[num_eles/2]);
        CPPUNIT_ASSERT(buf_int8[num_eles-1] == d4_ar_val[num_eles-1]);
    }

    void dap2_set_value()
    {
        unique_ptr<Byte> d_uint8(new Byte("Byte"));
        Array d_ar_uint8 = Array("Byte_array",d_uint8.get());
        d_ar_uint8.append_dim(2);
        d_ar_uint8.append_dim(num_eles/2);

        // Set the array value via set_value()
        d_ar_uint8.set_value((dods_byte *)buf_int8.data(),num_eles);

        vector<unsigned char>d_ar_val;
        d_ar_val.resize(num_eles);

        // Retrieve the array value via value()
        d_ar_uint8.value(d_ar_val.data());
#if 0
        cout<<"the first value buf2val is "<<(int)(d_ar_val[0]) <<endl;
        cout<<"the middle value buf2val is "<<(int)(d_ar_val[num_eles/2]) <<endl;
#endif
        DBG(cerr<<"DAP2 value() via set_value(): The first value is "<<(int)(d_ar_val[0]) <<endl);
        DBG(cerr<<"DAP2 value() via set_value(): The middle value is "<<(int)(d_ar_val[num_eles/2]) <<endl);
        DBG(cerr<<"DAP2 value() via set_value(): The last value is "<<(int)(d_ar_val[num_eles-1]) <<endl);

        CPPUNIT_ASSERT(buf_int8[0] == d_ar_val[0]);
        CPPUNIT_ASSERT(buf_int8[num_eles/2] == d_ar_val[num_eles/2]);
        CPPUNIT_ASSERT(buf_int8[num_eles-1] == d_ar_val[num_eles-1]);

    }

};

CPPUNIT_TEST_SUITE_REGISTRATION (BigArrayTest);

} // namespace libdap

int main(int argc, char *argv[])
{
    return run_tests<libdap::BigArrayTest>(argc, argv) ? 0: 1;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: text.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2008-02-26 14:50:18 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "text.hxx"
namespace DOM
{
    CText::CText(const xmlNodePtr aNodePtr)
    {
        m_aNodeType = NodeType_TEXT_NODE;
        init_characterdata(aNodePtr);
    }

    void SAL_CALL CText::saxify(
            const Reference< XDocumentHandler >& i_xHandler) {
        if (!i_xHandler.is()) throw RuntimeException();
        i_xHandler->characters(getData());
    }

    void CText::init_text(const xmlNodePtr aNodePtr)
    {
        init_characterdata(aNodePtr);
    }

  Reference< XText > SAL_CALL CText::splitText(sal_Int32 /*offset*/)
             throw (RuntimeException)
    {
        return Reference< XText >(this);
    }

    OUString SAL_CALL CText::getNodeName()throw (RuntimeException)
    {
        return OUString::createFromAscii("#text");
    }

}
<commit_msg>INTEGRATION: CWS changefileheader (1.6.4); FILE MERGED 2008/03/31 13:38:58 rt 1.6.4.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: text.cxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "text.hxx"
namespace DOM
{
    CText::CText(const xmlNodePtr aNodePtr)
    {
        m_aNodeType = NodeType_TEXT_NODE;
        init_characterdata(aNodePtr);
    }

    void SAL_CALL CText::saxify(
            const Reference< XDocumentHandler >& i_xHandler) {
        if (!i_xHandler.is()) throw RuntimeException();
        i_xHandler->characters(getData());
    }

    void CText::init_text(const xmlNodePtr aNodePtr)
    {
        init_characterdata(aNodePtr);
    }

  Reference< XText > SAL_CALL CText::splitText(sal_Int32 /*offset*/)
             throw (RuntimeException)
    {
        return Reference< XText >(this);
    }

    OUString SAL_CALL CText::getNodeName()throw (RuntimeException)
    {
        return OUString::createFromAscii("#text");
    }

}
<|endoftext|>