<commit_before>//
//  histo_translation.cpp
//
//
//  Created by Jean-françois Villeforceix on 21/03/2016.
//
//
#include <iostream>
#include <fstream>
#include <cmath>
#include <algorithm>
#include <string>
#include <sstream>
#include <stdio.h>
#include <vector>

using namespace std;

vector<double> linspace(double a, double b, int n)
{
    vector<double> array;
    double step = (b-a) / (n-1);

    while(a <= b) {
        array.push_back(a);
        a += step;
    }
    return array;
}

vector<vector<double>> imregionalmax(vector<vector<double>> matrice_histo)
{
    vector<vector<double>> matrice_histo_max;
    matrice_histo_max = matrice_histo;
    for(int i=1 ; i<matrice_histo.size()-1 ; i++)
    {
        for(int j=1 ; j<matrice_histo.size()-1 ; j++)
        {
            if(matrice_histo[i][j]<matrice_histo[i-1][j-1]
               || matrice_histo[i][j]<matrice_histo[i][j-1]
               || matrice_histo[i][j]<matrice_histo[i+1][j-1]
               || matrice_histo[i][j]<matrice_histo[i][j-1]
               || matrice_histo[i][j]<matrice_histo[i-1][j]
               || matrice_histo[i][j]<matrice_histo[i+1][j]
               || matrice_histo[i][j]<matrice_histo[i-1][j+1]
               || matrice_histo[i][j]<matrice_histo[i][j+1]
               || matrice_histo[i][j]<matrice_histo[i+1][j+1])
            {
                matrice_histo_max[i][j]=0;
            }
            matrice_histo_max[i][0]=0;
            matrice_histo_max[j][0]=0;
            matrice_histo_max[i][matrice_histo.size()-1]=0;
            matrice_histo_max[j][matrice_histo.size()-1]=0;
        }
    }
    return matrice_histo_max;
}

vector<vector<double>> find_non_zeros(vector<vector<double>> matrice_histo_max, int taille_vignette)
{
    vector<vector<double>> ligne_colonne;
    for(int i=1 ; i<matrice_histo_max.size()-1 ; i++)
    {
        for(int j=1 ; j<matrice_histo_max.size()-1 ; j++)
        {
            if(matrice_histo_max[i][j] != 0){
                vector<double> vtemp;
                vtemp = {static_cast<double>(i-taille_vignette),static_cast<double>(j-taille_vignette)};
                ligne_colonne.push_back(vtemp);
            }
        }
    }
    return ligne_colonne;
}

int main(int argc, char** argv)
{
    string nomfichier{argv[1]};
    ifstream fichier(nomfichier, ios::in); // ouverture du fichier en lecture

    double x1, y1 ,x2 ,y2;

    vector<vector<double>> v1;
    vector<vector<double>> v2;

    if(fichier)     // si ouverture a reussi
    {
        string ligne;
        do{
            fichier >> x1 >> y1 >> x2 >> y2;
            //cout << xa << " " << ya << " " << xb << " " << yb << endl;
            vector<double> v;
            v.push_back(x1);
            v.push_back(y1);
            v1.push_back(v);
            v.clear();
            v.push_back(x2);
            v.push_back(y2);
            v2.push_back(v);
        }while(getline(fichier, ligne));
        //M.pop_back();
        fichier.close();
    }
    else{ //sinon
        cerr << "Impossible d'ouvrir le fichier !" << endl;
    }

    vector<double> dx;
    vector<double> dy;

    if(v1.size()==v2.size()){
        for(int i=0 ; i<v1.size() ; i++)
        {
            double temp;
            temp = v1[i][0]-v2[i][0];
            dx.push_back(temp);
            temp = v1[i][1]-v2[i][1];
            dy.push_back(temp);
        }
    }
    else{ //sinon
        cerr << "Les tableaux de points Harris n'ont pas la même taille !" << endl;
    }

    int taille_matrice = 40;
    double min_dx{*min_element(dx.begin(),dx.end())};
    double max_dx{*max_element(dx.begin(),dx.end())};
    double min_dy{*min_element(dy.begin(),dy.end())};
    double max_dy{*max_element(dy.begin(),dy.end())};
    vector<double> x = linspace(min_dx,max_dx,taille_matrice);
    vector<double> y = linspace(min_dy,max_dy,taille_matrice);

    vector<vector<double>> xy;

    for(int i=0 ; i<taille_matrice ; i++)
    {
        vector<double> vtemp;
        for(int j=0 ; j<taille_matrice ; j++)
        {
            vtemp.push_back(0);
        }
        xy.push_back(vtemp);
    }

    for(int i=0 ; i<v1.size() ; i++)
    {
        for(int j=0 ; j<x.size() ; j++)
        {
            for(int k=0 ; k<y.size() ; k++)
            {
                if(dx[i]>x[j] && dx[i]<=x[j+1])
                {
                    if(dy[i]>y[k] && dy[i]<=y[k+1])
                    {
                        xy[j][k] += 1;
                    }
                }
            }
        }
    }

    for(int i=0 ; i<xy.size() ; i++)
    {
        for(int j=0 ; j<xy.size() ; j++)
        {
            if(xy[i][j]<100)
            {
                xy[i][j]=0;
            }
        }
    }

    vector<vector<double>> xy_max = imregionalmax(xy);

    int taille_vignette = 20;
    vector<vector<double>> lc_nz = find_non_zeros(xy_max, taille_vignette);

    for(auto translation : lc_nz)
    {
        cout << "La translation (" << translation[0] << "," << translation[1] << ") a été détectée.";
        cout << endl;
    }
}
<commit_msg>Delete histo_translation.cpp<commit_after><|endoftext|>


<commit_before>#include "depthai/pipeline/datatype/ImgFrame.hpp"

#include <cmath>

#include "spdlog/spdlog.h"

namespace dai {

void ImgFrame::setFrame(cv::Mat frame) {
    img.data.clear();
    img.data.insert(img.data.begin(), frame.datastart, frame.dataend);
}

cv::Mat ImgFrame::getFrame(bool deepCopy) {
    // Convert to cv::Mat. If deepCopy enabled, then copy pixel data, otherwise reference only
    cv::Mat mat;
    cv::Size size = {0, 0};
    int type = 0;

    switch(getType()) {
        case Type::RGB888i:
        case Type::BGR888i:
        case Type::BGR888p:
        case Type::RGB888p:
            size = cv::Size(getWidth(), getHeight());
            type = CV_8UC3;
            break;

        case Type::YUV420p:
        case Type::NV12:
        case Type::NV21:
            size = cv::Size(getWidth(), getHeight() * 3 / 2);
            type = CV_8UC1;
            break;

        case Type::RAW8:
        case Type::GRAY8:
            size = cv::Size(getWidth(), getHeight());
            type = CV_8UC1;
            break;

        case Type::GRAYF16:
            size = cv::Size(getWidth(), getHeight());
            type = CV_16FC1;
            break;

        case Type::RAW16:
            size = cv::Size(getWidth(), getHeight());
            type = CV_16UC1;
            break;

        case Type::RGBF16F16F16i:
        case Type::BGRF16F16F16i:
        case Type::RGBF16F16F16p:
        case Type::BGRF16F16F16p:
            size = cv::Size(getWidth(), getHeight());
            type = CV_16FC3;
            break;

        case dai::RawImgFrame::Type::BITSTREAM:
        default:
            size = cv::Size(static_cast<int>(getData().size()), 1);
            type = CV_8UC1;
            break;
    }

    // Check if enough data
    long requiredSize = CV_ELEM_SIZE(type) * size.area();
    long actualSize = static_cast<long>(img.data.size());
    if(actualSize < requiredSize) {
        throw std::runtime_error("ImgFrame doesn't have enough data to encode specified frame, required " + std::to_string(requiredSize) + ", actual "
                                 + std::to_string(actualSize) + ". Maybe metadataOnly transfer was made?");
    } else if(actualSize > requiredSize) {
        spdlog::warn("ImgFrame has excess data: actual {}, expected {}", actualSize, requiredSize);
    }
    if(getWidth() <= 0 || getHeight() <= 0) {
        throw std::runtime_error("ImgFrame metadata not valid (width or height = 0)");
    }

    // Copy or reference to existing data
    if(deepCopy) {
        // Create new image data
        mat.create(size, type);
        // Copy number of bytes that are available by Mat space or by img data size
        std::memcpy(mat.data, img.data.data(), std::min((long)(img.data.size()), (long)(mat.dataend - mat.datastart)));
    } else {
        mat = cv::Mat(size, type, img.data.data());
    }

    return mat;
}

cv::Mat ImgFrame::getCvFrame() {
    cv::Mat frame = getFrame();
    cv::Mat output;

    switch(getType()) {
        case Type::RGB888i:
            cv::cvtColor(frame, output, cv::ColorConversionCodes::COLOR_RGB2BGR);
            break;

        case Type::BGR888i:
            output = frame.clone();
            break;

        case Type::RGB888p: {
            cv::Size s(getWidth(), getHeight());
            std::vector<cv::Mat> channels;
            // RGB
            channels.push_back(cv::Mat(s, CV_8UC1, getData().data() + s.area() * 2));
            channels.push_back(cv::Mat(s, CV_8UC1, getData().data() + s.area() * 1));
            channels.push_back(cv::Mat(s, CV_8UC1, getData().data() + s.area() * 0));
            cv::merge(channels, output);
        } break;

        case Type::BGR888p: {
            cv::Size s(getWidth(), getHeight());
            std::vector<cv::Mat> channels;
            // BGR
            channels.push_back(cv::Mat(s, CV_8UC1, getData().data() + s.area() * 0));
            channels.push_back(cv::Mat(s, CV_8UC1, getData().data() + s.area() * 1));
            channels.push_back(cv::Mat(s, CV_8UC1, getData().data() + s.area() * 2));
            cv::merge(channels, output);
        } break;

        case Type::YUV420p:
            cv::cvtColor(frame, output, cv::ColorConversionCodes::COLOR_YUV2BGR_IYUV);
            break;

        case Type::NV12:
            cv::cvtColor(frame, output, cv::ColorConversionCodes::COLOR_YUV2BGR_NV12);
            break;

        case Type::NV21:
            cv::cvtColor(frame, output, cv::ColorConversionCodes::COLOR_YUV2BGR_NV21);
            break;

        case Type::RAW8:
        case Type::RAW16:
        case Type::GRAY8:
        case Type::GRAYF16:
            output = frame.clone();
            break;

        default:
            output = frame.clone();
            break;
    }

    return output;
}

}  // namespace dai
<commit_msg>Comment out for now ImgFrame excess data warning, doesn't build on Windows<commit_after>#include "depthai/pipeline/datatype/ImgFrame.hpp"

#include <cmath>

// #include "spdlog/spdlog.h"

namespace dai {

void ImgFrame::setFrame(cv::Mat frame) {
    img.data.clear();
    img.data.insert(img.data.begin(), frame.datastart, frame.dataend);
}

cv::Mat ImgFrame::getFrame(bool deepCopy) {
    // Convert to cv::Mat. If deepCopy enabled, then copy pixel data, otherwise reference only
    cv::Mat mat;
    cv::Size size = {0, 0};
    int type = 0;

    switch(getType()) {
        case Type::RGB888i:
        case Type::BGR888i:
        case Type::BGR888p:
        case Type::RGB888p:
            size = cv::Size(getWidth(), getHeight());
            type = CV_8UC3;
            break;

        case Type::YUV420p:
        case Type::NV12:
        case Type::NV21:
            size = cv::Size(getWidth(), getHeight() * 3 / 2);
            type = CV_8UC1;
            break;

        case Type::RAW8:
        case Type::GRAY8:
            size = cv::Size(getWidth(), getHeight());
            type = CV_8UC1;
            break;

        case Type::GRAYF16:
            size = cv::Size(getWidth(), getHeight());
            type = CV_16FC1;
            break;

        case Type::RAW16:
            size = cv::Size(getWidth(), getHeight());
            type = CV_16UC1;
            break;

        case Type::RGBF16F16F16i:
        case Type::BGRF16F16F16i:
        case Type::RGBF16F16F16p:
        case Type::BGRF16F16F16p:
            size = cv::Size(getWidth(), getHeight());
            type = CV_16FC3;
            break;

        case dai::RawImgFrame::Type::BITSTREAM:
        default:
            size = cv::Size(static_cast<int>(getData().size()), 1);
            type = CV_8UC1;
            break;
    }

    // Check if enough data
    long requiredSize = CV_ELEM_SIZE(type) * size.area();
    long actualSize = static_cast<long>(img.data.size());
    if(actualSize < requiredSize) {
        throw std::runtime_error("ImgFrame doesn't have enough data to encode specified frame, required " + std::to_string(requiredSize) + ", actual "
                                 + std::to_string(actualSize) + ". Maybe metadataOnly transfer was made?");
    } else if(actualSize > requiredSize) {
        // FIXME doesn't build on Windows (multiple definitions during link)
        // spdlog::warn("ImgFrame has excess data: actual {}, expected {}", actualSize, requiredSize);
    }
    if(getWidth() <= 0 || getHeight() <= 0) {
        throw std::runtime_error("ImgFrame metadata not valid (width or height = 0)");
    }

    // Copy or reference to existing data
    if(deepCopy) {
        // Create new image data
        mat.create(size, type);
        // Copy number of bytes that are available by Mat space or by img data size
        std::memcpy(mat.data, img.data.data(), std::min((long)(img.data.size()), (long)(mat.dataend - mat.datastart)));
    } else {
        mat = cv::Mat(size, type, img.data.data());
    }

    return mat;
}

cv::Mat ImgFrame::getCvFrame() {
    cv::Mat frame = getFrame();
    cv::Mat output;

    switch(getType()) {
        case Type::RGB888i:
            cv::cvtColor(frame, output, cv::ColorConversionCodes::COLOR_RGB2BGR);
            break;

        case Type::BGR888i:
            output = frame.clone();
            break;

        case Type::RGB888p: {
            cv::Size s(getWidth(), getHeight());
            std::vector<cv::Mat> channels;
            // RGB
            channels.push_back(cv::Mat(s, CV_8UC1, getData().data() + s.area() * 2));
            channels.push_back(cv::Mat(s, CV_8UC1, getData().data() + s.area() * 1));
            channels.push_back(cv::Mat(s, CV_8UC1, getData().data() + s.area() * 0));
            cv::merge(channels, output);
        } break;

        case Type::BGR888p: {
            cv::Size s(getWidth(), getHeight());
            std::vector<cv::Mat> channels;
            // BGR
            channels.push_back(cv::Mat(s, CV_8UC1, getData().data() + s.area() * 0));
            channels.push_back(cv::Mat(s, CV_8UC1, getData().data() + s.area() * 1));
            channels.push_back(cv::Mat(s, CV_8UC1, getData().data() + s.area() * 2));
            cv::merge(channels, output);
        } break;

        case Type::YUV420p:
            cv::cvtColor(frame, output, cv::ColorConversionCodes::COLOR_YUV2BGR_IYUV);
            break;

        case Type::NV12:
            cv::cvtColor(frame, output, cv::ColorConversionCodes::COLOR_YUV2BGR_NV12);
            break;

        case Type::NV21:
            cv::cvtColor(frame, output, cv::ColorConversionCodes::COLOR_YUV2BGR_NV21);
            break;

        case Type::RAW8:
        case Type::RAW16:
        case Type::GRAY8:
        case Type::GRAYF16:
            output = frame.clone();
            break;

        default:
            output = frame.clone();
            break;
    }

    return output;
}

}  // namespace dai
<|endoftext|>


<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
 *
 * This library is open source and may be redistributed and/or modified under
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 *
 * 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
 * OpenSceneGraph Public License for more details.
*/
#include <osg/LineSegment>

using namespace osg;

LineSegment::~LineSegment()
{
}

bool LineSegment::intersectAndClip(vec_type& s,vec_type& e,const BoundingBox& bb)
{
    // compate s and e against the xMin to xMax range of bb.
    if (s.x()<=e.x())
    {

        // trivial reject of segment wholely outside.
        if (e.x()<bb.xMin()) return false;
        if (s.x()>bb.xMax()) return false;

        if (s.x()<bb.xMin())
        {
            // clip s to xMin.
            s = s+(e-s)*(bb.xMin()-s.x())/(e.x()-s.x());
        }

        if (e.x()>bb.xMax())
        {
            // clip e to xMax.
            e = s+(e-s)*(bb.xMax()-s.x())/(e.x()-s.x());
        }
    }
    else
    {
        if (s.x()<bb.xMin()) return false;
        if (e.x()>bb.xMax()) return false;

        if (e.x()<bb.xMin())
        {
            // clip s to xMin.
            e = s+(e-s)*(bb.xMin()-s.x())/(e.x()-s.x());
        }

        if (s.x()>bb.xMax())
        {
            // clip e to xMax.
            s = s+(e-s)*(bb.xMax()-s.x())/(e.x()-s.x());
        }
    }

    // compate s and e against the yMin to yMax range of bb.
    if (s.y()<=e.y())
    {

        // trivial reject of segment wholely outside.
        if (e.y()<bb.yMin()) return false;
        if (s.y()>bb.yMax()) return false;

        if (s.y()<bb.yMin())
        {
            // clip s to yMin.
            s = s+(e-s)*(bb.yMin()-s.y())/(e.y()-s.y());
        }

        if (e.y()>bb.yMax())
        {
            // clip e to yMax.
            e = s+(e-s)*(bb.yMax()-s.y())/(e.y()-s.y());
        }
    }
    else
    {
        if (s.y()<bb.yMin()) return false;
        if (e.y()>bb.yMax()) return false;

        if (e.y()<bb.yMin())
        {
            // clip s to yMin.
            e = s+(e-s)*(bb.yMin()-s.y())/(e.y()-s.y());
        }

        if (s.y()>bb.yMax())
        {
            // clip e to yMax.
            s = s+(e-s)*(bb.yMax()-s.y())/(e.y()-s.y());
        }
    }

    // compate s and e against the zMin to zMax range of bb.
    if (s.z()<=e.z())
    {

        // trivial reject of segment wholely outside.
        if (e.z()<bb.zMin()) return false;
        if (s.z()>bb.zMax()) return false;

        if (s.z()<bb.zMin())
        {
            // clip s to zMin.
            s = s+(e-s)*(bb.zMin()-s.z())/(e.z()-s.z());
        }

        if (e.z()>bb.zMax())
        {
            // clip e to zMax.
            e = s+(e-s)*(bb.zMax()-s.z())/(e.z()-s.z());
        }
    }
    else
    {
        if (s.z()<bb.zMin()) return false;
        if (e.z()>bb.zMax()) return false;

        if (e.z()<bb.zMin())
        {
            // clip s to zMin.
            e = s+(e-s)*(bb.zMin()-s.z())/(e.z()-s.z());
        }

        if (s.z()>bb.zMax())
        {
            // clip e to zMax.
            s = s+(e-s)*(bb.zMax()-s.z())/(e.z()-s.z());
        }
    }

    return true;
}

bool LineSegment::intersect(const BoundingBox& bb) const
{
    if (!bb.valid()) return false;

    vec_type s=_s,e=_e;
    return intersectAndClip(s,e,bb);
}

bool LineSegment::intersect(const BoundingBox& bb,float& r1,float& r2) const
{
    if (!bb.valid()) return false;

    vec_type s=_s,e=_e;
    bool result = intersectAndClip(s,e,bb);
    if (result)
    {
        float len = (_e-_s).length();
        if (len>0.0f)
        {
            float inv_len = 1.0f/len;
            r1 = (s-_s).length()*inv_len;
            r2 = (e-_e).length()*inv_len;
        }
        else
        {
            r1 = 0.0f;
            r2 = 0.0f;
        }
    }
    return result;
}

bool LineSegment::intersect(const BoundingSphere& bs,float& r1,float& r2) const
{
    vec_type sm = _s-bs._center;
    float c = sm.length2()-bs._radius*bs._radius;

    vec_type se = _e-_s;
    float a = se.length2();

    // check for zero length segment.
    if (a==0.0)
    {
        // check if start point outside sphere radius
        if (c>0.0) return false;

        // length segment within radius of bounding sphere but zero length
        // so return true, and set the ratio so the start point is the one
        // to be used.
        r1 = 1.0f;
        r2 = 0.0f;
        return true;
    }

    float b = sm*se*2.0f;

    float d = b*b-4.0f*a*c;

    if (d<0.0f) return false;

    d = sqrtf(d);

    float div = 1.0f/(2.0f*a);

    r1 = (-b-d)*div;
    r2 = (-b+d)*div;

    if (r1<=0.0f && r2<=0.0f) return false;

    if (r1>=1.0f && r2>=1.0f) return false;

    return true;
}

bool LineSegment::intersect(const BoundingSphere& bs) const
{
    vec_type sm = _s-bs._center;
    float c = sm.length2()-bs._radius*bs._radius;
    if (c<0.0f) return true;

    vec_type se = _e-_s;
    float a = se.length2();

    float b = (sm*se)*2.0f;

    float d = b*b-4.0f*a*c;

    if (d<0.0f) return false;

    d = sqrtf(d);

    float div = 1.0f/(2.0f*a);

    float r1 = (-b-d)*div;
    float r2 = (-b+d)*div;

    if (r1<=0.0f && r2<=0.0f) return false;

    if (r1>=1.0f && r2>=1.0f) return false;

    return true;
}

bool LineSegment::intersect(const Vec3& v1,const Vec3& v2,const Vec3& v3,float& r)
{
    if (v1==v2 || v2==v3 || v1==v3) return false;

    vec_type vse = _e-_s;

    vec_type v12 = v2-v1;
    vec_type n12 = v12^vse;
    float ds12 = (_s-v1)*n12;
    float d312 = (v3-v1)*n12;
    if (d312>=0.0f)
    {
        if (ds12<0.0f) return false;
        if (ds12>d312) return false;
    }
    else                         // d312 < 0
    {
        if (ds12>0.0f) return false;
        if (ds12<d312) return false;
    }

    vec_type v23 = v3-v2;
    vec_type n23 = v23^vse;
    float ds23 = (_s-v2)*n23;
    float d123 = (v1-v2)*n23;
    if (d123>=0.0f)
    {
        if (ds23<0.0f) return false;
        if (ds23>d123) return false;
    }
    else                         // d123 < 0
    {
        if (ds23>0.0f) return false;
        if (ds23<d123) return false;
    }

    vec_type v31 = v1-v3;
    vec_type n31 = v31^vse;
    float ds31 = (_s-v3)*n31;
    float d231 = (v2-v3)*n31;
    if (d231>=0.0f)
    {
        if (ds31<0.0f) return false;
        if (ds31>d231) return false;
    }
    else                         // d231 < 0
    {
        if (ds31>0.0f) return false;
        if (ds31<d231) return false;
    }

    float r3 = ds12/d312;
    float r1 = ds23/d123;
    float r2 = ds31/d231;

    //    float rt = r1+r2+r3;

    vec_type in = v1*r1+v2*r2+v3*r3;

    float length = vse.length();
    vse /= length;
    float d = (in-_s)*vse;

    if (d<0.0f) return false;
    if (d>length) return false;

    r = d/length;

    return true;
}
<commit_msg>From Andy Skinner, "I've taken this another step, to use value_type inside the intersect calls. I did choose to use sqrt() instead of sqrtf()."<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
 *
 * This library is open source and may be redistributed and/or modified under
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 *
 * 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
 * OpenSceneGraph Public License for more details.
*/
#include <osg/LineSegment>

using namespace osg;

LineSegment::~LineSegment()
{
}

bool LineSegment::intersectAndClip(vec_type& s,vec_type& e,const BoundingBox& bb)
{
    // compate s and e against the xMin to xMax range of bb.
    if (s.x()<=e.x())
    {

        // trivial reject of segment wholely outside.
        if (e.x()<bb.xMin()) return false;
        if (s.x()>bb.xMax()) return false;

        if (s.x()<bb.xMin())
        {
            // clip s to xMin.
            s = s+(e-s)*(bb.xMin()-s.x())/(e.x()-s.x());
        }

        if (e.x()>bb.xMax())
        {
            // clip e to xMax.
            e = s+(e-s)*(bb.xMax()-s.x())/(e.x()-s.x());
        }
    }
    else
    {
        if (s.x()<bb.xMin()) return false;
        if (e.x()>bb.xMax()) return false;

        if (e.x()<bb.xMin())
        {
            // clip s to xMin.
            e = s+(e-s)*(bb.xMin()-s.x())/(e.x()-s.x());
        }

        if (s.x()>bb.xMax())
        {
            // clip e to xMax.
            s = s+(e-s)*(bb.xMax()-s.x())/(e.x()-s.x());
        }
    }

    // compate s and e against the yMin to yMax range of bb.
    if (s.y()<=e.y())
    {

        // trivial reject of segment wholely outside.
        if (e.y()<bb.yMin()) return false;
        if (s.y()>bb.yMax()) return false;

        if (s.y()<bb.yMin())
        {
            // clip s to yMin.
            s = s+(e-s)*(bb.yMin()-s.y())/(e.y()-s.y());
        }

        if (e.y()>bb.yMax())
        {
            // clip e to yMax.
            e = s+(e-s)*(bb.yMax()-s.y())/(e.y()-s.y());
        }
    }
    else
    {
        if (s.y()<bb.yMin()) return false;
        if (e.y()>bb.yMax()) return false;

        if (e.y()<bb.yMin())
        {
            // clip s to yMin.
            e = s+(e-s)*(bb.yMin()-s.y())/(e.y()-s.y());
        }

        if (s.y()>bb.yMax())
        {
            // clip e to yMax.
            s = s+(e-s)*(bb.yMax()-s.y())/(e.y()-s.y());
        }
    }

    // compate s and e against the zMin to zMax range of bb.
    if (s.z()<=e.z())
    {

        // trivial reject of segment wholely outside.
        if (e.z()<bb.zMin()) return false;
        if (s.z()>bb.zMax()) return false;

        if (s.z()<bb.zMin())
        {
            // clip s to zMin.
            s = s+(e-s)*(bb.zMin()-s.z())/(e.z()-s.z());
        }

        if (e.z()>bb.zMax())
        {
            // clip e to zMax.
            e = s+(e-s)*(bb.zMax()-s.z())/(e.z()-s.z());
        }
    }
    else
    {
        if (s.z()<bb.zMin()) return false;
        if (e.z()>bb.zMax()) return false;

        if (e.z()<bb.zMin())
        {
            // clip s to zMin.
            e = s+(e-s)*(bb.zMin()-s.z())/(e.z()-s.z());
        }

        if (s.z()>bb.zMax())
        {
            // clip e to zMax.
            s = s+(e-s)*(bb.zMax()-s.z())/(e.z()-s.z());
        }
    }

    return true;
}

bool LineSegment::intersect(const BoundingBox& bb) const
{
    if (!bb.valid()) return false;

    vec_type s=_s,e=_e;
    return intersectAndClip(s,e,bb);
}

bool LineSegment::intersect(const BoundingBox& bb,float& r1,float& r2) const
{
    if (!bb.valid()) return false;

    vec_type s=_s,e=_e;
    bool result = intersectAndClip(s,e,bb);
    if (result)
    {
        value_type len = (_e-_s).length();
        if (len>0.0f)
        {
            value_type inv_len = 1.0f/len;
            r1 = (float)((s-_s).length()*inv_len);
            r2 = (float)((e-_e).length()*inv_len);
        }
        else
        {
            r1 = 0.0f;
            r2 = 0.0f;
        }
    }
    return result;
}

bool LineSegment::intersect(const BoundingSphere& bs,float& r1,float& r2) const
{
    vec_type sm = _s-bs._center;
    value_type c = sm.length2()-bs._radius*bs._radius;

    vec_type se = _e-_s;
    value_type a = se.length2();

    // check for zero length segment.
    if (a==0.0)
    {
        // check if start point outside sphere radius
        if (c>0.0) return false;

        // length segment within radius of bounding sphere but zero length
        // so return true, and set the ratio so the start point is the one
        // to be used.
        r1 = 1.0f;
        r2 = 0.0f;
        return true;
    }

    value_type b = sm*se*2.0f;

    value_type d = b*b-4.0f*a*c;

    if (d<0.0f) return false;

    d = (value_type)sqrt(d);

    value_type div = 1.0f/(2.0f*a);

    r1 = (float)((-b-d)*div);
    r2 = (float)((-b+d)*div);

    if (r1<=0.0f && r2<=0.0f) return false;

    if (r1>=1.0f && r2>=1.0f) return false;

    return true;
}

bool LineSegment::intersect(const BoundingSphere& bs) const
{
    vec_type sm = _s-bs._center;
    value_type c = sm.length2()-bs._radius*bs._radius;
    if (c<0.0f) return true;

    vec_type se = _e-_s;
    value_type a = se.length2();

    value_type b = (sm*se)*2.0f;

    value_type d = b*b-4.0f*a*c;

    if (d<0.0f) return false;

    d = (value_type) sqrt(d);

    value_type div = 1.0f/(2.0f*a);

    value_type r1 = (-b-d)*div;
    value_type r2 = (-b+d)*div;

    if (r1<=0.0f && r2<=0.0f) return false;

    if (r1>=1.0f && r2>=1.0f) return false;

    return true;
}

bool LineSegment::intersect(const Vec3& v1,const Vec3& v2,const Vec3& v3,float& r)
{
    if (v1==v2 || v2==v3 || v1==v3) return false;

    vec_type vse = _e-_s;

    vec_type v12 = v2-v1;
    vec_type n12 = v12^vse;
    value_type ds12 = (_s-v1)*n12;
    value_type d312 = (v3-v1)*n12;
    if (d312>=0.0f)
    {
        if (ds12<0.0f) return false;
        if (ds12>d312) return false;
    }
    else                         // d312 < 0
    {
        if (ds12>0.0f) return false;
        if (ds12<d312) return false;
    }

    vec_type v23 = v3-v2;
    vec_type n23 = v23^vse;
    value_type ds23 = (_s-v2)*n23;
    value_type d123 = (v1-v2)*n23;
    if (d123>=0.0f)
    {
        if (ds23<0.0f) return false;
        if (ds23>d123) return false;
    }
    else                         // d123 < 0
    {
        if (ds23>0.0f) return false;
        if (ds23<d123) return false;
    }

    vec_type v31 = v1-v3;
    vec_type n31 = v31^vse;
    value_type ds31 = (_s-v3)*n31;
    value_type d231 = (v2-v3)*n31;
    if (d231>=0.0f)
    {
        if (ds31<0.0f) return false;
        if (ds31>d231) return false;
    }
    else                         // d231 < 0
    {
        if (ds31>0.0f) return false;
        if (ds31<d231) return false;
    }

    value_type r3 = ds12/d312;
    value_type r1 = ds23/d123;
    value_type r2 = ds31/d231;

    //    value_type rt = r1+r2+r3;

    vec_type in = v1*r1+v2*r2+v3*r3;

    value_type length = vse.length();
    vse /= length;
    value_type d = (in-_s)*vse;

    if (d<0.0f) return false;
    if (d>length) return false;

    r = (float) d/length;

    return true;
}
<|endoftext|>


<commit_before>#include "ViewportWrapper.h"
#define LIBRARY_EXPORTS

EXPORT_API VIEWPORT_HANDLE Viewport_Create(float fX, float fY, unsigned int nWidth, unsigned int nHeight) {
	return Iris2D::Viewport::Create(fX, fY, nWidth, nHeight);
}

EXPORT_API VIEWPORT_HANDLE Viewport_Create2(const RECT_HANDLE pRect) {
	const auto pCastedRect = reinterpret_cast<Iris2D::Rect*>(pRect);

	return Iris2D::Viewport::Create(pCastedRect);
}

EXPORT_API void Viewport_Release(VIEWPORT_HANDLE* pViewport) {
	auto pCastedViewport = reinterpret_cast<Iris2D::Viewport*&>(pViewport);

	Iris2D::Viewport::Release(pCastedViewport);
}

EXPORT_API void Viewport_ForceRelease(VIEWPORT_HANDLE* pViewport) {
	auto pCastedViewport = reinterpret_cast<Iris2D::Viewport*&>(pViewport);

	Iris2D::Viewport::ForceRelease(pCastedViewport);
}

EXPORT_API void Viewport_SetOX(VIEWPORT_HANDLE hHandle, float fOX) {
	const auto pViewport = reinterpret_cast<Iris2D::Viewport*>(hHandle);

	pViewport->SetOX(fOX);
}
EXPORT_API float Viewport_GetOX(VIEWPORT_HANDLE hHandle) {
	const auto pViewport = reinterpret_cast<Iris2D::Viewport*>(hHandle);

	return pViewport->GetOX();
}

EXPORT_API void Viewport_SetOY(VIEWPORT_HANDLE hHandle, float fOY) {
	const auto pViewport = reinterpret_cast<Iris2D::Viewport*>(hHandle);

	pViewport->SetOY(fOY);
}
EXPORT_API float Viewport_GetOY(VIEWPORT_HANDLE hHandle) {
	const auto pViewport = reinterpret_cast<Iris2D::Viewport*>(hHandle);

	return pViewport->GetOY();
}

EXPORT_API void Viewport_SetSrcRect(VIEWPORT_HANDLE hHandle, RECT_HANDLE* pSrcRect) {
	const auto pViewport = reinterpret_cast<Iris2D::Viewport*>(hHandle);
	const auto pCastedSrcRect = reinterpret_cast<Iris2D::Rect*&>(pSrcRect);

	pViewport->SetSrcRect(pCastedSrcRect);
}

EXPORT_API RECT_HANDLE Viewport_GetSrcRect(VIEWPORT_HANDLE hHandle) {
	const auto pViewport = reinterpret_cast<Iris2D::Viewport*>(hHandle);

	return pViewport->GetSrcRect();
}

EXPORT_API void Viewport_SetTone(VIEWPORT_HANDLE hHandle, COLOR_HANDLE* pTone) {
	const auto pViewport = reinterpret_cast<Iris2D::Viewport*>(hHandle);
	const auto pCastedTone = reinterpret_cast<Iris2D::Color*&>(pTone);

	pViewport->SetTone(pCastedTone);
}

EXPORT_API COLOR_HANDLE Viewport_GetTone(VIEWPORT_HANDLE hHandle) {
	const auto pViewport = reinterpret_cast<Iris2D::Viewport*>(hHandle);

	return pViewport->GetTone();
}

EXPORT_API void Viewport_SetZ(VIEWPORT_HANDLE hHandle, float fZ) {
	const auto pViewport = reinterpret_cast<Iris2D::Viewport*>(hHandle);

	pViewport->SetZ(fZ);
}

EXPORT_API float Viewport_GetZ(VIEWPORT_HANDLE hHandle) {
	const auto pViewport = reinterpret_cast<Iris2D::Viewport*>(hHandle);

	return pViewport->GetZ();
}

EXPORT_API unsigned int Viewport_GetWidth(VIEWPORT_HANDLE hHandle) {
	const auto pViewport = reinterpret_cast<Iris2D::Viewport*>(hHandle);

	return pViewport->GetWidth();
}

EXPORT_API unsigned int Viewport_GetHeight(VIEWPORT_HANDLE hHandle) {
	const auto pViewport = reinterpret_cast<Iris2D::Viewport*>(hHandle);

	return pViewport->GetHeight();
}<commit_msg>Fix viewport bugs<commit_after>#define LIBRARY_EXPORTS
#include "ViewportWrapper.h"

EXPORT_API VIEWPORT_HANDLE Viewport_Create(float fX, float fY, unsigned int nWidth, unsigned int nHeight) {
	return Iris2D::Viewport::Create(fX, fY, nWidth, nHeight);
}

EXPORT_API VIEWPORT_HANDLE Viewport_Create2(const RECT_HANDLE pRect) {
	const auto pCastedRect = reinterpret_cast<Iris2D::Rect*>(pRect);

	return Iris2D::Viewport::Create(pCastedRect);
}

EXPORT_API void Viewport_Release(VIEWPORT_HANDLE* pViewport) {
	auto pCastedViewport = reinterpret_cast<Iris2D::Viewport*&>(*pViewport);

	Iris2D::Viewport::Release(pCastedViewport);
}

EXPORT_API void Viewport_ForceRelease(VIEWPORT_HANDLE* pViewport) {
	auto pCastedViewport = reinterpret_cast<Iris2D::Viewport*&>(*pViewport);

	Iris2D::Viewport::ForceRelease(pCastedViewport);
}

EXPORT_API void Viewport_SetOX(VIEWPORT_HANDLE hHandle, float fOX) {
	const auto pViewport = reinterpret_cast<Iris2D::Viewport*>(hHandle);

	pViewport->SetOX(fOX);
}
EXPORT_API float Viewport_GetOX(VIEWPORT_HANDLE hHandle) {
	const auto pViewport = reinterpret_cast<Iris2D::Viewport*>(hHandle);

	return pViewport->GetOX();
}

EXPORT_API void Viewport_SetOY(VIEWPORT_HANDLE hHandle, float fOY) {
	const auto pViewport = reinterpret_cast<Iris2D::Viewport*>(hHandle);

	pViewport->SetOY(fOY);
}
EXPORT_API float Viewport_GetOY(VIEWPORT_HANDLE hHandle) {
	const auto pViewport = reinterpret_cast<Iris2D::Viewport*>(hHandle);

	return pViewport->GetOY();
}

EXPORT_API void Viewport_SetSrcRect(VIEWPORT_HANDLE hHandle, RECT_HANDLE* pSrcRect) {
	const auto pViewport = reinterpret_cast<Iris2D::Viewport*>(hHandle);
	auto pCastedSrcRect = reinterpret_cast<Iris2D::Rect*&>(*pSrcRect);

	pViewport->SetSrcRect(pCastedSrcRect);
}

EXPORT_API RECT_HANDLE Viewport_GetSrcRect(VIEWPORT_HANDLE hHandle) {
	const auto pViewport = reinterpret_cast<Iris2D::Viewport*>(hHandle);

	return pViewport->GetSrcRect();
}

EXPORT_API void Viewport_SetTone(VIEWPORT_HANDLE hHandle, COLOR_HANDLE* pTone) {
	const auto pViewport = reinterpret_cast<Iris2D::Viewport*>(hHandle);
	auto pCastedTone = reinterpret_cast<Iris2D::Color*&>(*pTone);

	pViewport->SetTone(pCastedTone);
}

EXPORT_API COLOR_HANDLE Viewport_GetTone(VIEWPORT_HANDLE hHandle) {
	const auto pViewport = reinterpret_cast<Iris2D::Viewport*>(hHandle);

	return pViewport->GetTone();
}

EXPORT_API void Viewport_SetZ(VIEWPORT_HANDLE hHandle, float fZ) {
	const auto pViewport = reinterpret_cast<Iris2D::Viewport*>(hHandle);

	pViewport->SetZ(fZ);
}

EXPORT_API float Viewport_GetZ(VIEWPORT_HANDLE hHandle) {
	const auto pViewport = reinterpret_cast<Iris2D::Viewport*>(hHandle);

	return pViewport->GetZ();
}

EXPORT_API unsigned int Viewport_GetWidth(VIEWPORT_HANDLE hHandle) {
	const auto pViewport = reinterpret_cast<Iris2D::Viewport*>(hHandle);

	return pViewport->GetWidth();
}

EXPORT_API unsigned int Viewport_GetHeight(VIEWPORT_HANDLE hHandle) {
	const auto pViewport = reinterpret_cast<Iris2D::Viewport*>(hHandle);

	return pViewport->GetHeight();
}<|endoftext|>


<commit_before><commit_msg>Use bool<commit_after><|endoftext|>


<commit_before>#ifndef TCL_BUFFER_HPP
#define TCL_BUFFER_HPP

#ifdef __APPLE__
#include <OpenCL/opencl.h>
#else
#include <CL\cl.h>
#endif

#include <vector>
#include <array>
#include <mutex>
#include "CLInformation.hpp"

namespace tcl
{
	// CLExecuteŏzQƂĂ܂
	class CLExecute;

	/**
	* foCẌ̃bp[NX
	*/
	template <typename T>
	class CLBuffer
	{
	private:
		cl_mem memory;
		size_t size;
		T* hostDataPtr;

	public:
		/**
		* mۂeʂ擾
		* \return mۂe
		*/
		inline const size_t Size() const {
			return size;
		}

		/**
		* mۂIuWFNg擾
		* \return mۂIuWFNg
		*/
		inline cl_mem& Memory() {
			return memory;
		}

	private:
		/**
		* Rs[֎~
		*/
		CLBuffer(const CLBuffer& copy) { }

		template <typename T>
		void SizeTest(const size_t& size) const
		{
			auto argSize = size * sizeof(T);
			if (this->size < argSize)
			{
				throw CLFailedAllacException("obt@̃TCYzXg̃TCY̕傫");
			}
		}

		void ResultTest(const cl_int result) const
		{
			if (result != CL_SUCCESS)
			{
				throw CLException("WriteReadɎs܂", result);
			}
		}

		void ReadTest(const cl_uint result) const
		{
			if (result != CL_SUCCESS)
			{
				switch (result)
				{
				case CL_INVALID_COMMAND_QUEUE:
					throw CLException("R}hL[ł");
				case CL_INVALID_CONTEXT:
					throw CLException("ReNXgł");
				case CL_INVALID_MEM_OBJECT:
					throw CLException("obt@IuWFNgł");
				case CL_INVALID_VALUE:
					throw CLException("w肵ǂݍݗ̈悪͈͊Oł");
				case CL_INVALID_EVENT_WAIT_LIST:
					throw CLException("Cxg҂Xgł");
				case CL_MISALIGNED_SUB_BUFFER_OFFSET:
					throw CLException("Tuobt@̃ItZbgACgĂ܂");
				case CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST:
					throw CLException("ǂݍ݃R}hubLOǂ");
				case CL_MEM_OBJECT_ALLOCATION_FAILURE:
					throw CLException("obt@Ɗ֘Atꂽf[^ۑ̈ւ̃mۂɎs");
				case CL_OUT_OF_RESOURCES:
					throw CLException("foCX̃\[X̊mۂɎs");
				case CL_OUT_OF_HOST_MEMORY:
					throw CLException("zXg̃\[X̊mۂɎs");
				}
			}
		}

		void SafeEnqueueRead(CLExecute& exec)
		{
			auto result = clEnqueueReadBuffer(
				exec.CommandQueue(), memory, CL_TRUE,
				0, size, hostDataPtr,
				0, NULL, NULL);
			ReadTest(result);
		}

		void SafeEnqueueWrite(CLExecute& exec)
		{
			auto result = clEnqueueWriteBuffer(
				exec.CommandQueue(), memory, CL_TRUE,
				0, size, hostDataPtr,
				0, NULL, NULL);
			ResultTest(result);
		}

		cl_mem CreateBuffer(const cl_mem_flags& flag)
		{
			return clCreateBuffer(information.context, flag, size, NULL, &information.result)
		}

	protected:
		/**
		* ň̂͊댯Ȃ̂ŃftHgRXgN^͋֎~
		*/
		CLBuffer()
			: size(0) {}

		//template <typename T>
		//CLBuffer(const cl_mem_flags flag, const size_t& size, void* hostPtr, T* hostDataPtr)
		//	: size(size), hostDataPtr(hostDataPtr)
		//{
		//	memory = clCreateBuffer(information.context, flag, size, hostPtr, &information.result);
		//}

		template <typename T>
		CLBuffer(const cl_mem_flags& flag, std::vector<T>& data)
			: size(data.size() * sizeof(T)), hostDataPtr(&data[0])
		{
			memory = CreateBuffer(flag);
		}

		template <typename T, size_t NUM>
		CLBuffer(const cl_mem_flags& flag, std::array<T, NUM>& data)
			: size(data.size() * sizeof(T)), hostDataPtr(&data[0])
		{
			memory = CreateBuffer(flag);
		}

		template <typename T>
		CLBuffer(const cl_mem_flags& flag, T& data)
			: size(sizeof(T)), hostDataPtr(&data)
		{
			memory = CreateBuffer(flag);
		}

		template <typename T>
		CLBuffer(const cl_mem_flags& flag, T* data, const size_t& num)
			: size(sizeof(T) * num), hostDataPtr(data)
		{
			memory = CreateBuffer(flag);
		}

	public:
		virtual ~CLBuffer()
		{
			clReleaseMemObject(memory);
		}

		/**
		* zXgfoCXɓ]
		*/
		CLBuffer& Write(CLExecute& exec)
		{
			SafeEnqueueWrite(exec);
			return *this;
		}

		/**
		* foCXzXgɓ]
		*/
		CLBuffer& Read(CLExecute& exec)
		{
			SafeEnqueueRead(exec);
			return *this;
		}
	};
}

#endif<commit_msg>void*で統一する<commit_after>#ifndef TCL_BUFFER_HPP
#define TCL_BUFFER_HPP

#ifdef __APPLE__
#include <OpenCL/opencl.h>
#else
#include <CL\cl.h>
#endif

#include <vector>
#include <array>
#include <mutex>
#include "CLInformation.hpp"

namespace tcl
{
	// CLExecuteŏzQƂĂ܂
	class CLExecute;

	/**
	* foCẌ̃bp[NX
	*/
	class CLBuffer
	{
	private:
		cl_mem memory;
		size_t size;
		void* hostDataPtr;

	public:
		/**
		* mۂeʂ擾
		* \return mۂe
		*/
		inline const size_t Size() const {
			return size;
		}

		/**
		* mۂIuWFNg擾
		* \return mۂIuWFNg
		*/
		inline cl_mem& Memory() {
			return memory;
		}

	private:
		/**
		* Rs[֎~
		*/
		CLBuffer(const CLBuffer& copy) { }

		template <typename T>
		void SizeTest(const size_t& size) const
		{
			auto argSize = size * sizeof(T);
			if (this->size < argSize)
			{
				throw CLFailedAllacException("obt@̃TCYzXg̃TCY̕傫");
			}
		}

		void ResultTest(const cl_int result) const
		{
			if (result != CL_SUCCESS)
			{
				throw CLException("WriteReadɎs܂", result);
			}
		}

		void ReadTest(const cl_uint result) const
		{
			if (result != CL_SUCCESS)
			{
				switch (result)
				{
				case CL_INVALID_COMMAND_QUEUE:
					throw CLException("R}hL[ł");
				case CL_INVALID_CONTEXT:
					throw CLException("ReNXgł");
				case CL_INVALID_MEM_OBJECT:
					throw CLException("obt@IuWFNgł");
				case CL_INVALID_VALUE:
					throw CLException("w肵ǂݍݗ̈悪͈͊Oł");
				case CL_INVALID_EVENT_WAIT_LIST:
					throw CLException("Cxg҂Xgł");
				case CL_MISALIGNED_SUB_BUFFER_OFFSET:
					throw CLException("Tuobt@̃ItZbgACgĂ܂");
				case CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST:
					throw CLException("ǂݍ݃R}hubLOǂ");
				case CL_MEM_OBJECT_ALLOCATION_FAILURE:
					throw CLException("obt@Ɗ֘Atꂽf[^ۑ̈ւ̃mۂɎs");
				case CL_OUT_OF_RESOURCES:
					throw CLException("foCX̃\[X̊mۂɎs");
				case CL_OUT_OF_HOST_MEMORY:
					throw CLException("zXg̃\[X̊mۂɎs");
				}
			}
		}

		void SafeEnqueueRead(CLExecute& exec)
		{
			auto result = clEnqueueReadBuffer(
				exec.CommandQueue(), memory, CL_TRUE,
				0, size, hostDataPtr,
				0, NULL, NULL);
			ReadTest(result);
		}

		void SafeEnqueueWrite(CLExecute& exec)
		{
			auto result = clEnqueueWriteBuffer(
				exec.CommandQueue(), memory, CL_TRUE,
				0, size, hostDataPtr,
				0, NULL, NULL);
			ResultTest(result);
		}

		cl_mem CreateBuffer(const cl_mem_flags& flag)
		{
			return clCreateBuffer(information.context, flag, size, NULL, &information.result);
		}

	protected:
		/**
		* ň̂͊댯Ȃ̂ŃftHgRXgN^͋֎~
		*/
		CLBuffer()
			: size(0) {}

		//template <typename T>
		//CLBuffer(const cl_mem_flags flag, const size_t& size, void* hostPtr, T* hostDataPtr)
		//	: size(size), hostDataPtr(hostDataPtr)
		//{
		//	memory = clCreateBuffer(information.context, flag, size, hostPtr, &information.result);
		//}

		template <typename T>
		CLBuffer(const cl_mem_flags& flag, std::vector<T>& data)
			: size(data.size() * sizeof(T)), hostDataPtr(&data[0])
		{
			memory = CreateBuffer(flag);
		}

		template <typename T, size_t NUM>
		CLBuffer(const cl_mem_flags& flag, std::array<T, NUM>& data)
			: size(data.size() * sizeof(T)), hostDataPtr(&data[0])
		{
			memory = CreateBuffer(flag);
		}

		template <typename T>
		CLBuffer(const cl_mem_flags& flag, T& data)
			: size(sizeof(T)), hostDataPtr(&data)
		{
			memory = CreateBuffer(flag);
		}

		template <typename T>
		CLBuffer(const cl_mem_flags& flag, T* data, const size_t& num)
			: size(sizeof(T) * num), hostDataPtr(data)
		{
			memory = CreateBuffer(flag);
		}

	public:
		virtual ~CLBuffer()
		{
			clReleaseMemObject(memory);
		}

		/**
		* zXgfoCXɓ]
		*/
		CLBuffer& Write(CLExecute& exec)
		{
			SafeEnqueueWrite(exec);
			return *this;
		}

		/**
		* foCXzXgɓ]
		*/
		CLBuffer& Read(CLExecute& exec)
		{
			SafeEnqueueRead(exec);
			return *this;
		}
	};
}

#endif<|endoftext|>


<commit_before>#include <cstdio>
#include "parser.h"
#include "common.h"

void TParser::ParseStatement(TSymtabNode* pRoutineId) {
    InsertLineMarker();

    switch (token) {
        case tcIdentifier: ParseAssignment(pRoutineId);
            break;
        case tcConst:
            GetToken();
            ParseConstantDeclarations(pRoutineId);
            break;
        case tcEnum:
            GetToken();
            ParseTypeDefinitions(pRoutineId);
            break;
        case tcDo: ParseDO(pRoutineId);
            break;
        case tcWhile: ParseWHILE(pRoutineId);
            break;
        case tcIf: ParseIF(pRoutineId);
            break;
        case tcFor: ParseFOR(pRoutineId);
            break;
        case tcSwitch: ParseSWITCH(pRoutineId);
            break;
        case tcCase:
        case tcDefault:ParseCaseLabel(pRoutineId);
            break;
        case tcBreak: GetTokenAppend();
            break;
        case tcLBracket: ParseCompound(pRoutineId);
            break;
        case tcReturn: ParseRETURN(pRoutineId);
            break;
    }

    if (token != tcEndOfFile) {
        Resync(tlStatementFollow, tlStatementStart);
    }
}

void TParser::ParseStatementList(TSymtabNode* pRoutineId, TTokenCode terminator) {

    do {
        ParseStatement(pRoutineId);

        //if (TokenIn(token, tlStatementStart)) {
        //  Error(errMissingSemicolon);
        //} else
        while (token == tcSemicolon)GetTokenAppend();
    } while ((token != terminator) && (token != tcEndOfFile));
}

void TParser::ParseAssignment(TSymtabNode* pRoutineId) {
    TSymtabNode *pTargetNode = SearchAll(pToken->String());

    if (!pTargetNode) pTargetNode = EnterLocal(pToken->String());

    icode.Put(pTargetNode);
    GetTokenAppend();

    switch (token) {
        case tcEqual:
            //Resync(tcEqual, tlExpressionStart);
            //CondGetTokenAppend(tcEqual, errMissingEqual);
            GetTokenAppend();
            ParseExpression();
            break;
        case tcPlusPlus:
            //Resync(tcPlusPlus, tlExpressionFollow);
            GetTokenAppend();
            break;
        case tcMinusMinus:
            //Resync(tcMinusMinus, tlExpressionFollow);
            GetTokenAppend();
            break;
        case tcPlusEqual:
            //Resync(tcPlusEqual, tlExpressionStart);
            GetTokenAppend();
            ParseExpression();
            break;
        case tcMinusEqual:
            //Resync(tcMinusEqual, tlExpressionStart);
            GetTokenAppend();
            ParseExpression();
            break;
        case tcStarEqual:
            //Resync(tcStarEqual, tlExpressionStart);
            GetTokenAppend();
            ParseExpression();
            break;
        case tcForwardSlashEqual:
            //Resync(tcForwardSlashEqual, tlExpressionStart);
            GetTokenAppend();
            ParseExpression();
            break;
        case tcModEqual:
            //Resync(tcModEqual, tlExpressionStart);
            GetTokenAppend();
            ParseExpression();
            break;
        case tcBitLeftShiftEqual:
            //Resync(tcBitLeftShiftEqual, tlExpressionStart);
            GetTokenAppend();
            ParseExpression();
            break;
        case tcBitRightShiftEqual:
            //Resync(tcBitRightShiftEqual, tlExpressionStart);
            GetTokenAppend();
            ParseExpression();
            break;
        case tcBitANDEqual:
            //Resync(tcBitANDEqual, tlExpressionStart);
            GetTokenAppend();
            ParseExpression();
            break;
        case tcBitXOREqual:
            //Resync(tcBitXOREqual, tlExpressionStart);
            GetTokenAppend();
            ParseExpression();
            break;
        case tcBitOREqual:
            //Resync(tcBitOREqual, tlExpressionStart);
            GetTokenAppend();
            ParseExpression();
            break;
        default:
            Error(errInvalidAssignment);
            break;
    }
}

void TParser::ParseDO(TSymtabNode* pRoutineId) {
    GetTokenAppend();

    ParseStatementList(pRoutineId, tcWhile);

    CondGetTokenAppend(tcWhile, errMissingWHILE);
    CondGetTokenAppend(tcLParen, errMissingLeftParen);

    InsertLineMarker();
    ParseExpression();

    CondGetTokenAppend(tcRParen, errMissingRightParen);

}

void TParser::ParseWHILE(TSymtabNode* pRoutineId) {
    GetTokenAppend();
    ParseExpression();

    CondGetTokenAppend(tcLBracket, errMissingLeftBracket);

    ParseStatement(pRoutineId);
}

void TParser::ParseIF(TSymtabNode* pRoutineId) {

    GetTokenAppend();
    CondGetTokenAppend(tcLParen, errMissingLeftParen);

    ParseExpression();

    CondGetTokenAppend(tcRParen, errMissingRightParen);

    ParseStatement(pRoutineId);

    if (token == tcSemicolon) GetTokenAppend();

    if (token == tcElse) {
        GetTokenAppend();
        ParseStatement(pRoutineId);
    }
}

void TParser::ParseFOR(TSymtabNode* pRoutineId) {

    GetTokenAppend();
    CondGetTokenAppend(tcLParen, errMissingLeftParen);

    if ((token == tcIdentifier) && (!SearchAll(pToken->String()))) {
        Error(errUndefinedIdentifier);
    }

    if (token != tcSemicolon) {

        // declaration would go here //

        CondGetTokenAppend(tcIdentifier, errMissingIdentifier);

        //Resync(tcEqual, tlExpressionStart);
        CondGetTokenAppend(tcEqual, errMissingEqual);
        // expr 1
        ParseExpression();

        CondGetTokenAppend(tcSemicolon, errMissingSemicolon);
    } else GetTokenAppend();

    if (token != tcSemicolon) {

        // expr 2
        ParseExpression();

        CondGetTokenAppend(tcSemicolon, errMissingSemicolon);
    } else GetTokenAppend();

    if (token != tcRParen) {
        // expr 3
        ParseExpression();

    }

    CondGetTokenAppend(tcRParen, errMissingRightParen);

    ParseStatement(pRoutineId);
}

void TParser::ParseSWITCH(TSymtabNode* pRoutineId) {

    GetTokenAppend();
    CondGetTokenAppend(tcLParen, errMissingLeftParen);

    ParseExpression();

    CondGetTokenAppend(tcRParen, errMissingRightParen);

    ParseStatement(pRoutineId);

}

void TParser::ParseCaseBranch(TSymtabNode* pRoutineId) {
    // c switch easier to parse that Pascal???
}

void TParser::ParseCaseLabel(TSymtabNode* pRoutineId) {
    GetTokenAppend();

    bool signFlag(false);

    if (TokenIn(token, tlUnaryOps)) {
        signFlag = true;
        GetTokenAppend();
    }

    switch (token) {
        case tcIdentifier:
            if (!SearchAll(pToken->String())) {
                Error(errUndefinedIdentifier);
            }

            GetTokenAppend();
            break;
        case tcNumber:
            if (pToken->Type() != tyInteger) Error(errInvalidConstant);
            GetTokenAppend();
            break;
        case tcString:
            if (signFlag || (strlen(pToken->String()) != 3)) {
                Error(errInvalidConstant);
            }
    }

    CondGetTokenAppend(tcColon, errMissingColon);

    ParseStatementList(pRoutineId, tcBreak);
}

void TParser::ParseCompound(TSymtabNode* pRoutineId) {
    GetTokenAppend();

    ParseStatementList(pRoutineId, tcRBracket);

    CondGetTokenAppend(tcRBracket, errMissingRightBracket);

}

void TParser::ParseRETURN(TSymtabNode* pRoutineId) {
    GetTokenAppend();

    ParseExpression();
}<commit_msg>adding types<commit_after>#include <cstdio>
#include "parser.h"
#include "common.h"

void TParser::ParseStatement(TSymtabNode* pRoutineId) {
    InsertLineMarker();

    switch (token) {
        case tcIdentifier:
            ParseAssignment(pRoutineId);
            break;
        case tcConst:
            GetToken();
            ParseConstantDeclarations(pRoutineId);
            break;
        case tcEnum:
            GetToken();
            ParseTypeDefinitions(pRoutineId);
            break;
        case tcDo: ParseDO(pRoutineId);
            break;
        case tcWhile: ParseWHILE(pRoutineId);
            break;
        case tcIf: ParseIF(pRoutineId);
            break;
        case tcFor: ParseFOR(pRoutineId);
            break;
        case tcSwitch: ParseSWITCH(pRoutineId);
            break;
        case tcCase:
        case tcDefault:ParseCaseLabel(pRoutineId);
            break;
        case tcBreak: GetTokenAppend();
            break;
        case tcLBracket: ParseCompound(pRoutineId);
            break;
        case tcReturn: ParseRETURN(pRoutineId);
            break;
    }

    if (token != tcEndOfFile) {
        Resync(tlStatementFollow, tlStatementStart);
    }
}

void TParser::ParseStatementList(TSymtabNode* pRoutineId, TTokenCode terminator) {

    do {
        ParseStatement(pRoutineId);

        //if (TokenIn(token, tlStatementStart)) {
        //  Error(errMissingSemicolon);
        //} else
        while (token == tcSemicolon)GetTokenAppend();
    } while ((token != terminator) && (token != tcEndOfFile));
}

void TParser::ParseAssignment(TSymtabNode* pRoutineId) {
    TSymtabNode *pTargetNode = SearchAll(pToken->String());

    if (!pTargetNode) pTargetNode = EnterLocal(pToken->String());

    icode.Put(pTargetNode);
    GetTokenAppend();

    switch (token) {
        case tcEqual:
            //Resync(tcEqual, tlExpressionStart);
            //CondGetTokenAppend(tcEqual, errMissingEqual);
            GetTokenAppend();
            ParseExpression();
            break;
        case tcPlusPlus:
            //Resync(tcPlusPlus, tlExpressionFollow);
            GetTokenAppend();
            break;
        case tcMinusMinus:
            //Resync(tcMinusMinus, tlExpressionFollow);
            GetTokenAppend();
            break;
        case tcPlusEqual:
            //Resync(tcPlusEqual, tlExpressionStart);
            GetTokenAppend();
            ParseExpression();
            break;
        case tcMinusEqual:
            //Resync(tcMinusEqual, tlExpressionStart);
            GetTokenAppend();
            ParseExpression();
            break;
        case tcStarEqual:
            //Resync(tcStarEqual, tlExpressionStart);
            GetTokenAppend();
            ParseExpression();
            break;
        case tcForwardSlashEqual:
            //Resync(tcForwardSlashEqual, tlExpressionStart);
            GetTokenAppend();
            ParseExpression();
            break;
        case tcModEqual:
            //Resync(tcModEqual, tlExpressionStart);
            GetTokenAppend();
            ParseExpression();
            break;
        case tcBitLeftShiftEqual:
            //Resync(tcBitLeftShiftEqual, tlExpressionStart);
            GetTokenAppend();
            ParseExpression();
            break;
        case tcBitRightShiftEqual:
            //Resync(tcBitRightShiftEqual, tlExpressionStart);
            GetTokenAppend();
            ParseExpression();
            break;
        case tcBitANDEqual:
            //Resync(tcBitANDEqual, tlExpressionStart);
            GetTokenAppend();
            ParseExpression();
            break;
        case tcBitXOREqual:
            //Resync(tcBitXOREqual, tlExpressionStart);
            GetTokenAppend();
            ParseExpression();
            break;
        case tcBitOREqual:
            //Resync(tcBitOREqual, tlExpressionStart);
            GetTokenAppend();
            ParseExpression();
            break;
        default:
            Error(errInvalidAssignment);
            break;
    }
}

void TParser::ParseDO(TSymtabNode* pRoutineId) {
    GetTokenAppend();

    ParseStatementList(pRoutineId, tcWhile);

    CondGetTokenAppend(tcWhile, errMissingWHILE);
    CondGetTokenAppend(tcLParen, errMissingLeftParen);

    InsertLineMarker();
    ParseExpression();

    CondGetTokenAppend(tcRParen, errMissingRightParen);

}

void TParser::ParseWHILE(TSymtabNode* pRoutineId) {
    GetTokenAppend();
    ParseExpression();

    CondGetTokenAppend(tcLBracket, errMissingLeftBracket);

    ParseStatement(pRoutineId);
}

void TParser::ParseIF(TSymtabNode* pRoutineId) {

    GetTokenAppend();
    CondGetTokenAppend(tcLParen, errMissingLeftParen);

    ParseExpression();

    CondGetTokenAppend(tcRParen, errMissingRightParen);

    ParseStatement(pRoutineId);

    if (token == tcSemicolon) GetTokenAppend();

    if (token == tcElse) {
        GetTokenAppend();
        ParseStatement(pRoutineId);
    }
}

void TParser::ParseFOR(TSymtabNode* pRoutineId) {

    GetTokenAppend();
    CondGetTokenAppend(tcLParen, errMissingLeftParen);

    if ((token == tcIdentifier) && (!SearchAll(pToken->String()))) {
        Error(errUndefinedIdentifier);
    }

    if (token != tcSemicolon) {

        // declaration would go here //

        CondGetTokenAppend(tcIdentifier, errMissingIdentifier);

        //Resync(tcEqual, tlExpressionStart);
        CondGetTokenAppend(tcEqual, errMissingEqual);
        // expr 1
        ParseExpression();

        CondGetTokenAppend(tcSemicolon, errMissingSemicolon);
    } else GetTokenAppend();

    if (token != tcSemicolon) {

        // expr 2
        ParseExpression();

        CondGetTokenAppend(tcSemicolon, errMissingSemicolon);
    } else GetTokenAppend();

    if (token != tcRParen) {
        // expr 3
        ParseExpression();

    }

    CondGetTokenAppend(tcRParen, errMissingRightParen);

    ParseStatement(pRoutineId);
}

void TParser::ParseSWITCH(TSymtabNode* pRoutineId) {

    GetTokenAppend();
    CondGetTokenAppend(tcLParen, errMissingLeftParen);

    ParseExpression();

    CondGetTokenAppend(tcRParen, errMissingRightParen);

    ParseStatement(pRoutineId);

}

void TParser::ParseCaseBranch(TSymtabNode* pRoutineId) {
    // c switch easier to parse that Pascal???
}

void TParser::ParseCaseLabel(TSymtabNode* pRoutineId) {
    GetTokenAppend();

    bool signFlag(false);

    if (TokenIn(token, tlUnaryOps)) {
        signFlag = true;
        GetTokenAppend();
    }

    switch (token) {
        case tcIdentifier:
            if (!SearchAll(pToken->String())) {
                Error(errUndefinedIdentifier);
            }

            GetTokenAppend();
            break;
        case tcNumber:
            if (pToken->Type() != tyInteger) Error(errInvalidConstant);
            GetTokenAppend();
            break;
        case tcString:
            if (signFlag || (strlen(pToken->String()) != 3)) {
                Error(errInvalidConstant);
            }
    }

    CondGetTokenAppend(tcColon, errMissingColon);

    ParseStatementList(pRoutineId, tcBreak);
}

void TParser::ParseCompound(TSymtabNode* pRoutineId) {
    GetTokenAppend();

    ParseStatementList(pRoutineId, tcRBracket);

    CondGetTokenAppend(tcRBracket, errMissingRightBracket);

}

void TParser::ParseRETURN(TSymtabNode* pRoutineId) {
    GetTokenAppend();

    ParseExpression();
}<|endoftext|>


<commit_before>/* <x0/plugins/ssl/ssl.cpp>
 *
 * This file is part of the x0 web server project and is released under LGPL-3.
 * http://www.xzero.ws/
 *
 * (c) 2009-2010 Christian Parpart <trapni@gentoo.org>
 */

#include "SslContext.h"
#include "SslDriver.h"
#include "SslSocket.h"
#include <x0/http/HttpPlugin.h>
#include <x0/http/HttpServer.h>
#include <x0/http/HttpListener.h>
#include <x0/http/HttpRequest.h>
#include <x0/http/HttpResponse.h>
#include <x0/http/HttpHeader.h>
#include <x0/io/BufferSource.h>
#include <x0/strutils.h>
#include <x0/Types.h>

#include <boost/lexical_cast.hpp>

#include <cstring>
#include <cerrno>
#include <cstddef>

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>

#include <gnutls/gnutls.h>
#include <gnutls/x509.h>
#include <gnutls/extra.h>
#include <pthread.h>
#include <gcrypt.h>
GCRY_THREAD_OPTION_PTHREAD_IMPL;

#define TRACE(msg...) DEBUG("ssl: " msg)

/**
 * \ingroup plugins
 * \brief SSL plugin
 */
class ssl_plugin :
	public x0::HttpPlugin,
	public SslContextSelector
{
public:
	ssl_plugin(x0::HttpServer& srv, const std::string& name) :
		x0::HttpPlugin(srv, name)
	{
		gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);

		int rv = gnutls_global_init();
		if (rv != GNUTLS_E_SUCCESS)
		{
			TRACE("gnutls_global_init: %s", gnutls_strerror(rv));
			return; //Error::CouldNotInitializeSslLibrary;
		}

		gnutls_global_init_extra();

		declareCVar("SslLogLevel", x0::HttpContext::server, &ssl_plugin::setupLogLevel);

		auto cmask = x0::HttpContext::server | x0::HttpContext::host;

		declareCVar("SslEnabled", cmask, &ssl_plugin::setupEnabled, 0);
		declareCVar("SslCertFile", cmask, &ssl_plugin::setupCertFile, 1);
		declareCVar("SslKeyFile", cmask, &ssl_plugin::setupKeyFile, 1);
		declareCVar("SslCrlFile", cmask, &ssl_plugin::setupCrlFile, 1);
		declareCVar("SslTrustFile", cmask, &ssl_plugin::setupTrustFile, 1);
		declareCVar("SslPriorities", cmask, &ssl_plugin::setupPriorities, 1);

		server().addComponent(std::string("GnuTLS/") + gnutls_check_version(NULL));
	}

	~ssl_plugin()
	{
		gnutls_global_deinit();
	}

	std::vector<SslContext *> contexts_;

	virtual SslContext *select(const std::string& dnsName) const
	{
		for (auto i = contexts_.begin(), e = contexts_.end(); i != e; ++i)
		{
			SslContext *cx = *i;

			if (cx->isValidDnsName(dnsName))
			{
				TRACE("select SslContext: CN:%s, dnsName:%s", cx->commonName().c_str(), dnsName.c_str());
				return cx;
			}
		}

		return NULL;
	}

	// {{{ post_config
	bool post_config()
	{
		// iterate through all virtual hosts and install the SslDriver if SSL was configured on it.
		auto hostnames = server().hostnames();
		for (auto i = hostnames.begin(), e = hostnames.end(); i != e; ++i)
		{
			SslContext *cx = server().resolveHost(*i)->get<SslContext>(this);
			x0::HttpListener *listener = server().listenerByHost(*i);
			auto aliases = server().hostnamesOf(*i);

			// XXX skip if no SSL was confgiured/enabled on this virtual host (or no TCP listener was found)
			if (!listener || !cx || !cx->enabled)
				continue;

			// XXX require every alias to match the cert CN (wildcard)
			for (auto k = aliases.begin(), m = aliases.end(); k != m; ++k)
			{
				std::string host(x0::extract_host_from_hostid(*k));

				TRACE("Checking SSL CN:%s against hostname/alias:%s", cx->commonName().c_str(), host.c_str());
				if (!cx->isValidDnsName(host))
				{
					log(x0::Severity::error, "SSL Certificates Common Name (CN) '%s' does not match the hostname/alias '%s'", cx->commonName().c_str(), host.c_str());
					return false;
				}
			}

			log(x0::Severity::debug, "Enabling SSL on host: %s", i->c_str());

			contexts_.push_back(cx);

			SslDriver *driver = new SslDriver(server().loop(), this);
			listener->setSocketDriver(driver);
			cx->setDriver(driver);

			if (!cx->post_config())
				return false;
		}
		return true;
	} // }}}

	// {{{ config
private:
	std::error_code setupLogLevel(const x0::SettingsValue& cvar, x0::Scope& s)
	{
		TRACE("setupLogLevel(cvar, scope)");
		//int level = 0;
		//if (cvar.load(level))
		//	setLogLevel(level);
		setLogLevel(cvar.as<int>());

		return std::error_code();
	}

	void setLogLevel(int value)
	{
		value = std::max(-10, std::min(10, value));
		TRACE("setLogLevel: %d", value);

		gnutls_global_set_log_level(value);
		gnutls_global_set_log_function(&ssl_plugin::gnutls_logger);
	}

	static void gnutls_logger(int level, const char *message)
	{
		std::string msg(message);
		msg.resize(msg.size() - 1);

		TRACE("gnutls [%d] %s", level, msg.c_str());
	}

	SslContext *acquire(x0::Scope& s)
	{
		SslContext *cx = s.acquire<SslContext>(this);
		cx->setLogger(server().logger());
		return cx;
	}

	std::error_code setupEnabled(const x0::SettingsValue& cvar, x0::Scope& s)
	{
		return cvar.load(acquire(s)->enabled);
	}

	std::error_code setupCertFile(const x0::SettingsValue& cvar, x0::Scope& s)
	{
		return cvar.load(acquire(s)->certFile);
	}

	std::error_code setupKeyFile(const x0::SettingsValue& cvar, x0::Scope& s)
	{
		return cvar.load(acquire(s)->keyFile);
	}

	std::error_code setupCrlFile(const x0::SettingsValue& cvar, x0::Scope& s)
	{
		return cvar.load(acquire(s)->crlFile);
	}

	std::error_code setupTrustFile(const x0::SettingsValue& cvar, x0::Scope& s)
	{
		return cvar.load(acquire(s)->trustFile);
	}

	std::error_code setupPriorities(const x0::SettingsValue& cvar, x0::Scope& s)
	{
		return cvar.load(acquire(s)->priorities);
	}
	// }}}
};

X0_EXPORT_PLUGIN(ssl);
<commit_msg>[plugins] ssl: added check against mixed secure/unsecure hosts on same listener port<commit_after>/* <x0/plugins/ssl/ssl.cpp>
 *
 * This file is part of the x0 web server project and is released under LGPL-3.
 * http://www.xzero.ws/
 *
 * (c) 2009-2010 Christian Parpart <trapni@gentoo.org>
 */

#include "SslContext.h"
#include "SslDriver.h"
#include "SslSocket.h"
#include <x0/http/HttpPlugin.h>
#include <x0/http/HttpServer.h>
#include <x0/http/HttpListener.h>
#include <x0/http/HttpRequest.h>
#include <x0/http/HttpResponse.h>
#include <x0/http/HttpHeader.h>
#include <x0/io/BufferSource.h>
#include <x0/strutils.h>
#include <x0/Types.h>

#include <boost/lexical_cast.hpp>

#include <cstring>
#include <cerrno>
#include <cstddef>

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>

#include <gnutls/gnutls.h>
#include <gnutls/x509.h>
#include <gnutls/extra.h>
#include <pthread.h>
#include <gcrypt.h>
GCRY_THREAD_OPTION_PTHREAD_IMPL;

#define TRACE(msg...) DEBUG("ssl: " msg)

/**
 * \ingroup plugins
 * \brief SSL plugin
 */
class ssl_plugin :
	public x0::HttpPlugin,
	public SslContextSelector
{
public:
	ssl_plugin(x0::HttpServer& srv, const std::string& name) :
		x0::HttpPlugin(srv, name)
	{
		gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);

		int rv = gnutls_global_init();
		if (rv != GNUTLS_E_SUCCESS)
		{
			TRACE("gnutls_global_init: %s", gnutls_strerror(rv));
			return; //Error::CouldNotInitializeSslLibrary;
		}

		gnutls_global_init_extra();

		declareCVar("SslLogLevel", x0::HttpContext::server, &ssl_plugin::setupLogLevel);

		auto cmask = x0::HttpContext::server | x0::HttpContext::host;

		declareCVar("SslEnabled", cmask, &ssl_plugin::setupEnabled, 0);
		declareCVar("SslCertFile", cmask, &ssl_plugin::setupCertFile, 1);
		declareCVar("SslKeyFile", cmask, &ssl_plugin::setupKeyFile, 1);
		declareCVar("SslCrlFile", cmask, &ssl_plugin::setupCrlFile, 1);
		declareCVar("SslTrustFile", cmask, &ssl_plugin::setupTrustFile, 1);
		declareCVar("SslPriorities", cmask, &ssl_plugin::setupPriorities, 1);

		server().addComponent(std::string("GnuTLS/") + gnutls_check_version(NULL));
	}

	~ssl_plugin()
	{
		gnutls_global_deinit();
	}

	std::vector<SslContext *> contexts_;

	virtual SslContext *select(const std::string& dnsName) const
	{
		for (auto i = contexts_.begin(), e = contexts_.end(); i != e; ++i)
		{
			SslContext *cx = *i;

			if (cx->isValidDnsName(dnsName))
			{
				TRACE("select SslContext: CN:%s, dnsName:%s", cx->commonName().c_str(), dnsName.c_str());
				return cx;
			}
		}

		return NULL;
	}

	virtual bool post_config() // {{{ post_config
	{
		// iterate through all virtual hosts and install the SslDriver if SSL was configured on it.
		auto hostnames = server().hostnames();
		for (auto i = hostnames.begin(), e = hostnames.end(); i != e; ++i)
		{
			SslContext *cx = server().resolveHost(*i)->get<SslContext>(this);
			x0::HttpListener *listener = server().listenerByHost(*i);
			auto aliases = server().hostnamesOf(*i);

			// XXX skip if no SSL was confgiured/enabled on this virtual host (or no TCP listener was found)
			if (!listener || !cx || !cx->enabled)
				continue;

			// XXX require every alias to match the cert CN (wildcard)
			for (auto k = aliases.begin(), m = aliases.end(); k != m; ++k)
			{
				std::string host(x0::extract_host_from_hostid(*k));

				TRACE("Checking SSL CN:%s against hostname/alias:%s", cx->commonName().c_str(), host.c_str());
				if (!cx->isValidDnsName(host))
				{
					log(x0::Severity::error, "SSL Certificates Common Name (CN) '%s' does not match the hostname/alias '%s'", cx->commonName().c_str(), host.c_str());
					return false;
				}
			}

			log(x0::Severity::debug, "Enabling SSL on host: %s", i->c_str());

			contexts_.push_back(cx);

			SslDriver *driver = new SslDriver(server().loop(), this);
			listener->setSocketDriver(driver);
			cx->setDriver(driver);

			if (!cx->post_config())
				return false;
		}
		return true;
	} // }}}

	virtual bool post_check()
	{
		auto hostnames = server().hostnames();
		for (auto i = hostnames.begin(), e = hostnames.end(); i != e; ++i)
		{
			x0::HttpListener *listener = server().listenerByHost(*i);
			if (!listener || !listener->isSecure())
				continue;

			// {{{ verify listener to not mix secured/unsecured virtual hosts
			auto hosts = server_.getHostsByPort(listener->port());
			for (auto k = hosts.begin(), m = hosts.end(); k != m; ++k)
			{
				if (!server().resolveHost(*i)->get<SslContext>(this))
				{
					log(x0::Severity::error, "Mixing (SSL) secured and unsecured hosts on same listener port (%d). %s", listener->port(), (*k)->id().c_str());
					return false;
				}
			}
			// }}}
		}

		return true;
	}

	// {{{ config
private:
	std::error_code setupLogLevel(const x0::SettingsValue& cvar, x0::Scope& s)
	{
		TRACE("setupLogLevel(cvar, scope)");
		//int level = 0;
		//if (cvar.load(level))
		//	setLogLevel(level);
		setLogLevel(cvar.as<int>());

		return std::error_code();
	}

	void setLogLevel(int value)
	{
		value = std::max(-10, std::min(10, value));
		TRACE("setLogLevel: %d", value);

		gnutls_global_set_log_level(value);
		gnutls_global_set_log_function(&ssl_plugin::gnutls_logger);
	}

	static void gnutls_logger(int level, const char *message)
	{
		std::string msg(message);
		msg.resize(msg.size() - 1);

		TRACE("gnutls [%d] %s", level, msg.c_str());
	}

	SslContext *acquire(x0::Scope& s)
	{
		SslContext *cx = s.acquire<SslContext>(this);
		cx->setLogger(server().logger());
		return cx;
	}

	std::error_code setupEnabled(const x0::SettingsValue& cvar, x0::Scope& s)
	{
		return cvar.load(acquire(s)->enabled);
	}

	std::error_code setupCertFile(const x0::SettingsValue& cvar, x0::Scope& s)
	{
		return cvar.load(acquire(s)->certFile);
	}

	std::error_code setupKeyFile(const x0::SettingsValue& cvar, x0::Scope& s)
	{
		return cvar.load(acquire(s)->keyFile);
	}

	std::error_code setupCrlFile(const x0::SettingsValue& cvar, x0::Scope& s)
	{
		return cvar.load(acquire(s)->crlFile);
	}

	std::error_code setupTrustFile(const x0::SettingsValue& cvar, x0::Scope& s)
	{
		return cvar.load(acquire(s)->trustFile);
	}

	std::error_code setupPriorities(const x0::SettingsValue& cvar, x0::Scope& s)
	{
		return cvar.load(acquire(s)->priorities);
	}
	// }}}
};

X0_EXPORT_PLUGIN(ssl);
<|endoftext|>


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

// constructor provides customized dimensions and number of
// sequential pieces (x) it takes to win the game
ConnectX::ConnectX(int wide, int high, int x)
{
	//invalid input resets everything to default settings
	if( wide <= 0 || high <= 0 || x <= 0)
	{
		wide=DEFAULT_WIDTH;
		high=DEFAULT_HEIGHT;
		x=DEFAULT_TO_WIN;
	}

	board.resize(high);
	for(int i=0; i<high; i++)
	{
		board[i].resize(wide);
		for(int j=0; j<wide; j++)
		{
			board[i][j] = EMPTY;
		}
	}
	width = wide;
	height = high;
	toWin = x;
	turn = BLACK;
}

// changes turn to reflect whose turn it is
void ConnectX::toggleTurn()
{
	if(turn == WHITE)
	{
		turn = BLACK;
	}
	else
		turn = WHITE;
}

// returns whether or not the provided location is a valid
// space in the board
bool ConnectX::inBounds(int w, int h)
{
	bool inside;
	if( w>=width || w<0 )
		inside = false;
	else
		inside = true;

	if( h<0 || h>=height )
		inside = false;
	else
		inside = true;

	return inside;
}

// Prints out the board to the command line, showing both
// empty places and where each player has placed pieces
void ConnectX::showBoard()
{
	std::cout<<"   ";
	for(int w = 0; w < width; w++)
	{
		std::cout<<"["<<w<<"]";
	}
	std::cout<<std::endl;
	for(int h = 0; h < height; h++)
	{
		std::cout<<"["<<h<<"]";
		for(int w = 0; w < width; w++)
		{
			char place;
			Piece val = at(w,h);
			if(val == BLACK)
				place = 'B';
			else if( val == WHITE )
				place = 'W';
			else
				place = ' ';
			std::cout<<"["<<place<<"]";
		}
		std::cout<<std::endl;
	}
}

// Returns whose turn it is (BLACK or WHITE)
Piece ConnectX::whoseTurn()
{
	return turn;
}

// Retrieves the value at a provided (w,h) location in the board or returns
// INVALID if the provided location is not within the board
Piece ConnectX::at(int w, int h)
{
	if( inBounds(w,h) )
	{
		return board[h][w];
	}
	else
		return INVALID;
}

// Puts the current player's piece in a vertical column, where the piece falls
// to the lowest empty position available in the board. Placing a piece in a
// "bad" column (such as a column that doesn't exist or is already full of
// pieces) results in the player just losing their turn
void ConnectX::placePiece(int column)
{
	for(int i=height-1; i>=0; i--)
	{
		if( at(column,i) == EMPTY && inBounds(column,i) )
		{
			board[i][column] = turn;
			break;
		}
	}

	toggleTurn();
}
<commit_msg>Connectx.cpp<commit_after>#include "ConnectX.h"
#include <iostream>

// constructor provides customized dimensions and number of
// sequential pieces (x) it takes to win the game
ConnectX::ConnectX(int wide, int high, int x)
{
	//invalid input resets everything to default settings
	if( wide <= 0 || high <= 0 || x <= 0)
	{
		wide=DEFAULT_WIDTH;
		high=DEFAULT_HEIGHT;
		x=DEFAULT_TO_WIN;
	}

	board.resize(high);
	for(int i=0; i<high; i++)
	{
		board[i].resize(wide);
		for(int j=0; j<wide; j++)
		{
			board[i][j] = EMPTY;
		}
	}
	width = wide;
	height = high;
	toWin = x;
	turn = BLACK;
}

// changes turn to reflect whose turn it is
void ConnectX::toggleTurn()
{
	if(turn == WHITE)
	{
		turn = BLACK;
	}
	else
		turn = WHITE;
}

// returns whether or not the provided location is a valid
// space in the board
bool ConnectX::inBounds(int w, int h)
{
	bool inside;
	if( w>=width || w<0 )
		inside = false;
	else
		inside = true;

	if( h<0 || h>=height )
		inside = false;
	else
		inside = true;

	return inside;
}

// Prints out the board to the command line, showing both
// empty places and where each player has placed pieces
void ConnectX::showBoard()
{
	std::cout<<"   ";
	for(int w = 0; w < width; w++)
	{
		std::cout<<"["<<w<<"]";
	}
	std::cout<<std::endl;
	for(int h = 0; h < height; h++)
	{
		std::cout<<"["<<h<<"]";
		for(int w = 0; w < width; w++)
		{
			char place;
			Piece val = at(w,h);
			if(val == BLACK)
				place = 'B';
			else if( val == WHITE )
				place = 'W';
			else
				place = ' ';
			std::cout<<"["<<place<<"]";
		}
		std::cout<<std::endl;
	}
}

// Returns whose turn it is (BLACK or WHITE)
Piece ConnectX::whoseTurn()
{
	return turn;
}

// Retrieves the value at a provided (w,h) location in the board or returns
// INVALID if the provided location is not within the board
Piece ConnectX::at(int w, int h)
{
	if( inBounds(w,h) )
	{
		return board[h][w];
	}
	else
		return INVALID;
}

// Puts the current player's piece in a vertical column, where the piece falls
// to the lowest empty position available in the board. Placing a piece in a
// "bad" column (such as a column that doesn't exist or is already full of
// pieces) results in the player just losing their turn
void ConnectX::placePiece(int column)
{
	for(int i=height-1; i>=0; i--)
	{
		if( at(column,i) == EMPTY && inBounds(column,i) )
		{
			board[i][column] = turn;
			break;
		}
	}

	toggleTurn();
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2017, James Jackson and Daniel Koch, BYU MAGICC Lab
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice, this
 *   list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 * * Neither the name of the copyright holder nor the names of its
 *   contributors may be used to endorse or promote products derived from
 *   this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "airbourne_board.h"

namespace rosflight_firmware
{

AirbourneBoard::AirbourneBoard()
{
}

void AirbourneBoard::init_board()
{
  systemInit();
  led2_.init(LED2_GPIO, LED2_PIN);
  led1_.init(LED1_GPIO, LED1_PIN);

  int_i2c_.init(&i2c_config[BARO_I2C]);
  ext_i2c_.init(&i2c_config[EXTERNAL_I2C]);
  spi1_.init(&spi_config[MPU6000_SPI]);
  spi3_.init(&spi_config[FLASH_SPI]);

  current_serial_ = &vcp_;    //uncomment this to switch to VCP as the main output
}

void AirbourneBoard::board_reset(bool bootloader)
{
  (void)bootloader;
  NVIC_SystemReset();
}

// clock
uint32_t AirbourneBoard::clock_millis()
{
  return millis();
}

uint64_t AirbourneBoard::clock_micros()
{
  return micros();
}

void AirbourneBoard::clock_delay(uint32_t milliseconds)
{
  delay(milliseconds);
}

// serial
void AirbourneBoard::serial_init(uint32_t baud_rate, uint32_t dev)
{
  if (dev == 3)
  {
    uart3_.init(&uart_config[UART3], baud_rate);
    current_serial_ = &uart3_;
    secondary_serial_device_ = dev;
  }
  else
  {
    secondary_serial_device_ = dev;
    vcp_.init();
    current_serial_ = &vcp_;
  }
}

void AirbourneBoard::serial_write(const uint8_t *src, size_t len)
{
  current_serial_->write(src, len);
}

uint16_t AirbourneBoard::serial_bytes_available()
{
  return current_serial_->rx_bytes_waiting();
}

uint8_t AirbourneBoard::serial_read()
{
  if (vcp_.connected())
    current_serial_ = &vcp_;
  else if (secondary_serial_device_ == 3)
    current_serial_ = &uart3_;

  return current_serial_->read_byte();
}

void AirbourneBoard::serial_flush()
{
  current_serial_->flush();
}

// sensors
void AirbourneBoard::sensors_init()
{
  while(millis() < 50) {} // wait for sensors to boot up
  imu_.init(&spi1_);

  baro_.init(&int_i2c_);
  mag_.init(&int_i2c_);
  sonar_.init(&ext_i2c_);
  airspeed_.init(&ext_i2c_);
}

uint16_t AirbourneBoard::num_sensor_errors()
{
  return ext_i2c_.num_errors();
}

bool AirbourneBoard::new_imu_data()
{
  return imu_.new_data();
}

bool AirbourneBoard::imu_read(float accel[3], float* temperature, float gyro[3], uint64_t* time_us)
{
  float read_accel[3], read_gyro[3];
  imu_.read(read_accel, read_gyro, temperature, time_us);

  accel[0] = -read_accel[1];
  accel[1] = -read_accel[0];
  accel[2] = -read_accel[2];

  gyro[0] = -read_gyro[1];
  gyro[1] = -read_gyro[0];
  gyro[2] = -read_gyro[2];

  return true;
}

void AirbourneBoard::imu_not_responding_error()
{
  sensors_init();
}

bool AirbourneBoard::mag_present()
{
  mag_.update();
  return mag_.present();
}

void AirbourneBoard::mag_update()
{
  mag_.update();
}

void AirbourneBoard::mag_read(float mag[3])
{
  mag_.update();
  mag_.read(mag);
}
bool AirbourneBoard::baro_present()
{
  baro_.update();
  return baro_.present();
}

void AirbourneBoard::baro_update()
{
  baro_.update();
}

void AirbourneBoard::baro_read(float *pressure, float *temperature)
{
  baro_.update();
  baro_.read(pressure, temperature);
}

bool AirbourneBoard::diff_pressure_present()
{
  return airspeed_.present();
}

void AirbourneBoard::diff_pressure_update()
{
  airspeed_.update();
}

void AirbourneBoard::diff_pressure_read(float *diff_pressure, float *temperature)
{
  (void) diff_pressure;
  (void) temperature;
  airspeed_.update();
  airspeed_.read(diff_pressure, temperature);
}

bool AirbourneBoard::sonar_present()
{
  return sonar_.present();
}

void AirbourneBoard::sonar_update()
{
  sonar_.update();
}

float AirbourneBoard::sonar_read()
{
  return sonar_.read();
}

// PWM
void AirbourneBoard::rc_init(rc_type_t rc_type)
{
  switch (rc_type)
  {
  case RC_TYPE_SBUS:
    sbus_uart_.init(&uart_config[0], 100000, UART::MODE_8E2);
    inv_pin_.init(SBUS_INV_GPIO, SBUS_INV_PIN, GPIO::OUTPUT);
    rc_sbus_.init(&inv_pin_, &sbus_uart_);
    rc_ = &rc_sbus_;
    break;
  case RC_TYPE_PPM:
  default:
    rc_ppm_.init(&pwm_config[RC_PPM_PIN]);
    rc_ = &rc_ppm_;
    break;
  }
}

float AirbourneBoard::rc_read(uint8_t channel)
{
  return rc_->read(channel);
}

void AirbourneBoard::pwm_init(uint32_t refresh_rate, uint16_t idle_pwm)
{
  for (int i = 0; i < PWM_NUM_OUTPUTS; i++)
  {
    esc_out_[i].init(&pwm_config[i], refresh_rate, 2000, 1000);
    esc_out_[i].writeUs(idle_pwm);
  }
}

void AirbourneBoard::pwm_write(uint8_t channel, float value)
{
  esc_out_[channel].write(value);
}

bool AirbourneBoard::rc_lost()
{
  return rc_->lost();
}

// non-volatile memory
void AirbourneBoard::memory_init()
{
  return flash_.init(&spi3_);
}

bool AirbourneBoard::memory_read(void * data, size_t len)
{
  return flash_.read_config(reinterpret_cast<uint8_t*>(data), len);
}

bool AirbourneBoard::memory_write(const void * data, size_t len)
{
  return flash_.write_config(reinterpret_cast<const uint8_t*>(data), len);
}

// LED
void AirbourneBoard::led0_on() { led1_.on(); }
void AirbourneBoard::led0_off() { led1_.off(); }
void AirbourneBoard::led0_toggle() { led1_.toggle(); }

void AirbourneBoard::led1_on() { led2_.on(); }
void AirbourneBoard::led1_off() { led2_.off(); }
void AirbourneBoard::led1_toggle() { led2_.toggle(); }

} // namespace rosflight_firmware
<commit_msg>working on my desk with 3DR radio!<commit_after>/*
 * Copyright (c) 2017, James Jackson and Daniel Koch, BYU MAGICC Lab
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice, this
 *   list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 * * Neither the name of the copyright holder nor the names of its
 *   contributors may be used to endorse or promote products derived from
 *   this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "airbourne_board.h"

namespace rosflight_firmware
{

AirbourneBoard::AirbourneBoard()
{
}

void AirbourneBoard::init_board()
{
  systemInit();
  led2_.init(LED2_GPIO, LED2_PIN);
  led1_.init(LED1_GPIO, LED1_PIN);

  int_i2c_.init(&i2c_config[BARO_I2C]);
  ext_i2c_.init(&i2c_config[EXTERNAL_I2C]);
  spi1_.init(&spi_config[MPU6000_SPI]);
  spi3_.init(&spi_config[FLASH_SPI]);

  current_serial_ = &vcp_;    //uncomment this to switch to VCP as the main output
}

void AirbourneBoard::board_reset(bool bootloader)
{
  (void)bootloader;
  NVIC_SystemReset();
}

// clock
uint32_t AirbourneBoard::clock_millis()
{
  return millis();
}

uint64_t AirbourneBoard::clock_micros()
{
  return micros();
}

void AirbourneBoard::clock_delay(uint32_t milliseconds)
{
  delay(milliseconds);
}

// serial
void AirbourneBoard::serial_init(uint32_t baud_rate, uint32_t dev)
{
  vcp_.init();
  if (dev == 3)
  {
    uart3_.init(&uart_config[UART3], baud_rate);
    current_serial_ = &uart3_;
    secondary_serial_device_ = dev;
  }
  else
  {
    secondary_serial_device_ = dev;
    current_serial_ = &vcp_;
  }
}

void AirbourneBoard::serial_write(const uint8_t *src, size_t len)
{
  current_serial_->write(src, len);
}

uint16_t AirbourneBoard::serial_bytes_available()
{
  if (vcp_.connected())
    current_serial_ = &vcp_;
  else if (secondary_serial_device_ == 3)
    current_serial_ = &uart3_;

  return current_serial_->rx_bytes_waiting();
}

uint8_t AirbourneBoard::serial_read()
{

  return current_serial_->read_byte();
}

void AirbourneBoard::serial_flush()
{
  current_serial_->flush();
}

// sensors
void AirbourneBoard::sensors_init()
{
  while(millis() < 50) {} // wait for sensors to boot up
  imu_.init(&spi1_);

  baro_.init(&int_i2c_);
  mag_.init(&int_i2c_);
  sonar_.init(&ext_i2c_);
  airspeed_.init(&ext_i2c_);
}

uint16_t AirbourneBoard::num_sensor_errors()
{
  return ext_i2c_.num_errors();
}

bool AirbourneBoard::new_imu_data()
{
  return imu_.new_data();
}

bool AirbourneBoard::imu_read(float accel[3], float* temperature, float gyro[3], uint64_t* time_us)
{
  float read_accel[3], read_gyro[3];
  imu_.read(read_accel, read_gyro, temperature, time_us);

  accel[0] = -read_accel[1];
  accel[1] = -read_accel[0];
  accel[2] = -read_accel[2];

  gyro[0] = -read_gyro[1];
  gyro[1] = -read_gyro[0];
  gyro[2] = -read_gyro[2];

  return true;
}

void AirbourneBoard::imu_not_responding_error()
{
  sensors_init();
}

bool AirbourneBoard::mag_present()
{
  mag_.update();
  return mag_.present();
}

void AirbourneBoard::mag_update()
{
  mag_.update();
}

void AirbourneBoard::mag_read(float mag[3])
{
  mag_.update();
  mag_.read(mag);
}
bool AirbourneBoard::baro_present()
{
  baro_.update();
  return baro_.present();
}

void AirbourneBoard::baro_update()
{
  baro_.update();
}

void AirbourneBoard::baro_read(float *pressure, float *temperature)
{
  baro_.update();
  baro_.read(pressure, temperature);
}

bool AirbourneBoard::diff_pressure_present()
{
  return airspeed_.present();
}

void AirbourneBoard::diff_pressure_update()
{
  airspeed_.update();
}

void AirbourneBoard::diff_pressure_read(float *diff_pressure, float *temperature)
{
  (void) diff_pressure;
  (void) temperature;
  airspeed_.update();
  airspeed_.read(diff_pressure, temperature);
}

bool AirbourneBoard::sonar_present()
{
  return sonar_.present();
}

void AirbourneBoard::sonar_update()
{
  sonar_.update();
}

float AirbourneBoard::sonar_read()
{
  return sonar_.read();
}

// PWM
void AirbourneBoard::rc_init(rc_type_t rc_type)
{
  switch (rc_type)
  {
  case RC_TYPE_SBUS:
    sbus_uart_.init(&uart_config[0], 100000, UART::MODE_8E2);
    inv_pin_.init(SBUS_INV_GPIO, SBUS_INV_PIN, GPIO::OUTPUT);
    rc_sbus_.init(&inv_pin_, &sbus_uart_);
    rc_ = &rc_sbus_;
    break;
  case RC_TYPE_PPM:
  default:
    rc_ppm_.init(&pwm_config[RC_PPM_PIN]);
    rc_ = &rc_ppm_;
    break;
  }
}

float AirbourneBoard::rc_read(uint8_t channel)
{
  return rc_->read(channel);
}

void AirbourneBoard::pwm_init(uint32_t refresh_rate, uint16_t idle_pwm)
{
  for (int i = 0; i < PWM_NUM_OUTPUTS; i++)
  {
    esc_out_[i].init(&pwm_config[i], refresh_rate, 2000, 1000);
    esc_out_[i].writeUs(idle_pwm);
  }
}

void AirbourneBoard::pwm_write(uint8_t channel, float value)
{
  esc_out_[channel].write(value);
}

bool AirbourneBoard::rc_lost()
{
  return rc_->lost();
}

// non-volatile memory
void AirbourneBoard::memory_init()
{
  return flash_.init(&spi3_);
}

bool AirbourneBoard::memory_read(void * data, size_t len)
{
  return flash_.read_config(reinterpret_cast<uint8_t*>(data), len);
}

bool AirbourneBoard::memory_write(const void * data, size_t len)
{
  return flash_.write_config(reinterpret_cast<const uint8_t*>(data), len);
}

// LED
void AirbourneBoard::led0_on() { led1_.on(); }
void AirbourneBoard::led0_off() { led1_.off(); }
void AirbourneBoard::led0_toggle() { led1_.toggle(); }

void AirbourneBoard::led1_on() { led2_.on(); }
void AirbourneBoard::led1_off() { led2_.off(); }
void AirbourneBoard::led1_toggle() { led2_.toggle(); }

} // namespace rosflight_firmware
<|endoftext|>


<commit_before><commit_msg>Runtime/Input: Replace bitfield unions with constructor initializers<commit_after><|endoftext|>


<commit_before>#include "Zookeeper.hpp"

Breakpoint::Breakpoint(uint32_t _addr) : addr(_addr) {
	enable();
}

void Breakpoint::enable() {
	if(enabled)
		return;
	saved = box->cpu->read_memory<uint8_t>(addr);
	box->cpu->write_memory<uint8_t>(addr, 0xCC);
	box->cpu->invalidate_tlb();
	enabled = true;
}

void Breakpoint::disable() {
	if(!enabled)
		return;
	box->cpu->write_memory(addr, saved);
	box->cpu->invalidate_tlb();
	enabled = false;
}

Debugger::Debugger() {
}

#define MAX_FRAMES 8
void Debugger::stack_trace() {
	cout << "Stack trace:" << endl;

	auto ebp = box->cpu->rreg(HV_X86_RBP);
	for(auto i = 0; i < MAX_FRAMES; ++i) {
		if(ebp == 0)
			break;
		auto eip = box->cpu->read_memory<uint32_t>(ebp + 4);
		cout << hex << eip << endl;
		ebp = box->cpu->read_memory<uint32_t>(ebp);
	}

	cout << endl;
}

#define MAX_LENGTH 20
void Debugger::dump_stack() {
	auto esp = box->cpu->rreg(HV_X86_RSP);
	for(auto i = 0; i < MAX_LENGTH; ++i)
		cout << format("%08x") % box->cpu->read_memory<uint32_t>(esp + i * 4) << endl;
}

void Debugger::enter(uint32_t reason) {
	auto eip = box->cpu->rreg(HV_X86_RIP);

	if(breakpoints.find(eip) != breakpoints.end()) {
		cout << format("Hit breakpoint at 0x%08x") % eip << endl;
		breakpoints[eip]->disable();
		box->cpu->single_step = 1;
	}

	while(1) {
		cout << format("[%i] %08x > ") % box->tm->current_thread() % eip << flush;

		string line;
		if(!getline(cin, line)) {
			cout << endl;
			exit(0);
		}
		line = boost::regex_replace(line, boost::regex("[\\s]{2,}"), " ");

		vector<string> v;
		split(v, line, is_space());
		if(v.size() == 0 || v[0] == "")
			continue;

		auto cmd = v[0];
		if(cmd == "c" || cmd == "cont" || cmd == "continue")
			break;
		else if(cmd == "s" || cmd == "step") {
			box->cpu->single_step = 2;
			break;
		} else if(cmd == "b" || cmd == "bp" || cmd == "break") {
			assert(v.size() >= 2);
			auto addr = stoul(v[1], nullptr, 16);
			if(breakpoints.find(addr) != breakpoints.end())
				cout << format("Breakpoint already exists at %08x") % addr << endl;
			else {
				breakpoints[addr] = new Breakpoint(addr);
				cout << format("Added breakpoint at addr %08x") % addr << endl;
			}
		} else if(cmd == "trace") {
			stack_trace();
		} else if(cmd == "stack") {
			dump_stack();
		} else if(cmd == "r" || cmd == "regs") {
			cout << format("eax  %08x    ebx  %08x") % box->cpu->rreg(HV_X86_RAX) % box->cpu->rreg(HV_X86_RBX) << endl;
			cout << format("ecx  %08x    edx  %08x") % box->cpu->rreg(HV_X86_RCX) % box->cpu->rreg(HV_X86_RDX) << endl;
			cout << format("edi  %08x    esi  %08x") % box->cpu->rreg(HV_X86_RDI) % box->cpu->rreg(HV_X86_RSI) << endl;
			cout << format("ebp  %08x    esp  %08x") % box->cpu->rreg(HV_X86_RBP) % box->cpu->rreg(HV_X86_RSP) << endl;
			cout << format("eflags  %08x") % box->cpu->rreg(HV_X86_RFLAGS) << endl;
		} else {
			cout << "Unknown command" << endl;
		}
	}
}

void Debugger::reenable() {
	for(auto bp : breakpoints) {
		bp.second->enable();
	}
}
<commit_msg>Added read memory command to debugger.<commit_after>#include "Zookeeper.hpp"

Breakpoint::Breakpoint(uint32_t _addr) : addr(_addr) {
	enable();
}

void Breakpoint::enable() {
	if(enabled)
		return;
	saved = box->cpu->read_memory<uint8_t>(addr);
	box->cpu->write_memory<uint8_t>(addr, 0xCC);
	box->cpu->invalidate_tlb();
	enabled = true;
}

void Breakpoint::disable() {
	if(!enabled)
		return;
	box->cpu->write_memory(addr, saved);
	box->cpu->invalidate_tlb();
	enabled = false;
}

Debugger::Debugger() {
}

#define MAX_FRAMES 8
void Debugger::stack_trace() {
	cout << "Stack trace:" << endl;

	auto ebp = box->cpu->rreg(HV_X86_RBP);
	for(auto i = 0; i < MAX_FRAMES; ++i) {
		if(ebp == 0)
			break;
		auto eip = box->cpu->read_memory<uint32_t>(ebp + 4);
		cout << hex << eip << endl;
		ebp = box->cpu->read_memory<uint32_t>(ebp);
	}

	cout << endl;
}

#define MAX_LENGTH 20
void Debugger::dump_stack() {
	auto esp = box->cpu->rreg(HV_X86_RSP);
	for(auto i = 0; i < MAX_LENGTH; ++i)
		cout << format("%08x") % box->cpu->read_memory<uint32_t>(esp + i * 4) << endl;
}

void Debugger::enter(uint32_t reason) {
	auto eip = box->cpu->rreg(HV_X86_RIP);

	if(breakpoints.find(eip) != breakpoints.end()) {
		cout << format("Hit breakpoint at 0x%08x") % eip << endl;
		breakpoints[eip]->disable();
		box->cpu->single_step = 1;
	}

	while(1) {
		cout << format("[%i] %08x > ") % box->tm->current_thread() % eip << flush;

		string line;
		if(!getline(cin, line)) {
			cout << endl;
			exit(0);
		}
		line = boost::regex_replace(line, boost::regex("[\\s]{2,}"), " ");

		vector<string> v;
		split(v, line, is_space());
		if(v.size() == 0 || v[0] == "")
			continue;

		auto cmd = v[0];
		if(cmd == "c" || cmd == "cont" || cmd == "continue")
			break;
		else if(cmd == "s" || cmd == "step") {
			box->cpu->single_step = 2;
			break;
		} else if(cmd == "b" || cmd == "bp" || cmd == "break") {
			assert(v.size() >= 2);
			auto addr = stoul(v[1], nullptr, 16);
			if(breakpoints.find(addr) != breakpoints.end())
				cout << format("Breakpoint already exists at %08x") % addr << endl;
			else {
				breakpoints[addr] = new Breakpoint(addr);
				cout << format("Added breakpoint at addr %08x") % addr << endl;
			}
		} else if(cmd == "trace") {
			stack_trace();
		} else if(cmd == "stack") {
			dump_stack();
		} else if(cmd == "r" || cmd == "regs") {
			cout << format("eax  %08x    ebx  %08x") % box->cpu->rreg(HV_X86_RAX) % box->cpu->rreg(HV_X86_RBX) << endl;
			cout << format("ecx  %08x    edx  %08x") % box->cpu->rreg(HV_X86_RCX) % box->cpu->rreg(HV_X86_RDX) << endl;
			cout << format("edi  %08x    esi  %08x") % box->cpu->rreg(HV_X86_RDI) % box->cpu->rreg(HV_X86_RSI) << endl;
			cout << format("ebp  %08x    esp  %08x") % box->cpu->rreg(HV_X86_RBP) % box->cpu->rreg(HV_X86_RSP) << endl;
			cout << format("eflags  %08x") % box->cpu->rreg(HV_X86_RFLAGS) << endl;
		} else if(cmd == "rm" || cmd == "read") {
			string type = "u32";
			auto offset = 1;
			if(v.size() == 3) {
				type = v[1];
				offset = 2;
			}
			auto addr = stoul(v[offset], nullptr, 16);
			if(type == "u8")
				cout << format("*0x%08x == 0x%02x") % addr % (uint32_t) box->cpu->read_memory<uint8_t>(addr) << endl;
			else if(type == "u16")
				cout << format("*0x%08x == 0x%04x") % addr % (uint32_t) box->cpu->read_memory<uint16_t>(addr) << endl;
			else if(type == "u32")
				cout << format("*0x%08x == 0x%08x") % addr % box->cpu->read_memory<uint32_t>(addr) << endl;
			else
				cout << "Unknown type (try u8, u16, or u32)" << endl;
		} else {
			cout << "Unknown command" << endl;
		}
	}
}

void Debugger::reenable() {
	for(auto bp : breakpoints) {
		bp.second->enable();
	}
}
<|endoftext|>