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

CV_IMPL CvKalman*
cvCreateKalman( int DP, int MP, int CP )
{
    CvKalman *kalman = 0;

    if( DP <= 0 || MP <= 0 )
        CV_Error( CV_StsOutOfRange,
        "state and measurement vectors must have positive number of dimensions" );

    if( CP < 0 )
        CP = DP;

    /* allocating memory for the structure */
    kalman = (CvKalman *)cvAlloc( sizeof( CvKalman ));
    memset( kalman, 0, sizeof(*kalman));

    kalman->DP = DP;
    kalman->MP = MP;
    kalman->CP = CP;

    kalman->state_pre = cvCreateMat( DP, 1, CV_32FC1 );
    cvZero( kalman->state_pre );

    kalman->state_post = cvCreateMat( DP, 1, CV_32FC1 );
    cvZero( kalman->state_post );

    kalman->transition_matrix = cvCreateMat( DP, DP, CV_32FC1 );
    cvSetIdentity( kalman->transition_matrix );

    kalman->process_noise_cov = cvCreateMat( DP, DP, CV_32FC1 );
    cvSetIdentity( kalman->process_noise_cov );

    kalman->measurement_matrix = cvCreateMat( MP, DP, CV_32FC1 );
    cvZero( kalman->measurement_matrix );

    kalman->measurement_noise_cov = cvCreateMat( MP, MP, CV_32FC1 );
    cvSetIdentity( kalman->measurement_noise_cov );

    kalman->error_cov_pre = cvCreateMat( DP, DP, CV_32FC1 );

    kalman->error_cov_post = cvCreateMat( DP, DP, CV_32FC1 );
    cvZero( kalman->error_cov_post );

    kalman->gain = cvCreateMat( DP, MP, CV_32FC1 );

    if( CP > 0 )
    {
        kalman->control_matrix = cvCreateMat( DP, CP, CV_32FC1 );
        cvZero( kalman->control_matrix );
    }

    kalman->temp1 = cvCreateMat( DP, DP, CV_32FC1 );
    kalman->temp2 = cvCreateMat( MP, DP, CV_32FC1 );
    kalman->temp3 = cvCreateMat( MP, MP, CV_32FC1 );
    kalman->temp4 = cvCreateMat( MP, DP, CV_32FC1 );
    kalman->temp5 = cvCreateMat( MP, 1, CV_32FC1 );

#if 1
    kalman->PosterState = kalman->state_pre->data.fl;
    kalman->PriorState = kalman->state_post->data.fl;
    kalman->DynamMatr = kalman->transition_matrix->data.fl;
    kalman->MeasurementMatr = kalman->measurement_matrix->data.fl;
    kalman->MNCovariance = kalman->measurement_noise_cov->data.fl;
    kalman->PNCovariance = kalman->process_noise_cov->data.fl;
    kalman->KalmGainMatr = kalman->gain->data.fl;
    kalman->PriorErrorCovariance = kalman->error_cov_pre->data.fl;
    kalman->PosterErrorCovariance = kalman->error_cov_post->data.fl;
#endif

    return kalman;
}

CV_IMPL void
cvReleaseKalman( CvKalman** _kalman )
{
    CvKalman *kalman;

    if( !_kalman )
        CV_Error( CV_StsNullPtr, "" );

    kalman = *_kalman;
    if( !kalman )
        return;

    /* freeing the memory */
    cvReleaseMat( &kalman->state_pre );
    cvReleaseMat( &kalman->state_post );
    cvReleaseMat( &kalman->transition_matrix );
    cvReleaseMat( &kalman->control_matrix );
    cvReleaseMat( &kalman->measurement_matrix );
    cvReleaseMat( &kalman->process_noise_cov );
    cvReleaseMat( &kalman->measurement_noise_cov );
    cvReleaseMat( &kalman->error_cov_pre );
    cvReleaseMat( &kalman->gain );
    cvReleaseMat( &kalman->error_cov_post );
    cvReleaseMat( &kalman->temp1 );
    cvReleaseMat( &kalman->temp2 );
    cvReleaseMat( &kalman->temp3 );
    cvReleaseMat( &kalman->temp4 );
    cvReleaseMat( &kalman->temp5 );

    memset( kalman, 0, sizeof(*kalman));

    /* deallocating the structure */
    cvFree( _kalman );
}

CV_IMPL const CvMat*
cvKalmanPredict( CvKalman* kalman, const CvMat* control )
{
    if( !kalman )
        CV_Error( CV_StsNullPtr, "" );

    /* update the state */
    /* x'(k) = A*x(k) */
    cvMatMulAdd( kalman->transition_matrix, kalman->state_post, 0, kalman->state_pre );

    if( control && kalman->CP > 0 )
        /* x'(k) = x'(k) + B*u(k) */
        cvMatMulAdd( kalman->control_matrix, control, kalman->state_pre, kalman->state_pre );

    /* update error covariance matrices */
    /* temp1 = A*P(k) */
    cvMatMulAdd( kalman->transition_matrix, kalman->error_cov_post, 0, kalman->temp1 );

    /* P'(k) = temp1*At + Q */
    cvGEMM( kalman->temp1, kalman->transition_matrix, 1, kalman->process_noise_cov, 1,
                     kalman->error_cov_pre, CV_GEMM_B_T );

    /* handle the case when there will be measurement before the next predict */
    cvCopy(kalman->state_pre, kalman->state_post);

    return kalman->state_pre;
}

CV_IMPL const CvMat*
cvKalmanCorrect( CvKalman* kalman, const CvMat* measurement )
{
    if( !kalman || !measurement )
        CV_Error( CV_StsNullPtr, "" );

    /* temp2 = H*P'(k) */
    cvMatMulAdd( kalman->measurement_matrix, kalman->error_cov_pre, 0, kalman->temp2 );
    /* temp3 = temp2*Ht + R */
    cvGEMM( kalman->temp2, kalman->measurement_matrix, 1,
            kalman->measurement_noise_cov, 1, kalman->temp3, CV_GEMM_B_T );

    /* temp4 = inv(temp3)*temp2 = Kt(k) */
    cvSolve( kalman->temp3, kalman->temp2, kalman->temp4, CV_SVD );

    /* K(k) */
    cvTranspose( kalman->temp4, kalman->gain );

    /* temp5 = z(k) - H*x'(k) */
    cvGEMM( kalman->measurement_matrix, kalman->state_pre, -1, measurement, 1, kalman->temp5 );

    /* x(k) = x'(k) + K(k)*temp5 */
    cvMatMulAdd( kalman->gain, kalman->temp5, kalman->state_pre, kalman->state_post );

    /* P(k) = P'(k) - K(k)*temp2 */
    cvGEMM( kalman->gain, kalman->temp2, -1, kalman->error_cov_pre, 1,
                     kalman->error_cov_post, 0 );

    return kalman->state_post;
}

namespace cv
{

KalmanFilter::KalmanFilter() {}
KalmanFilter::KalmanFilter(int dynamParams, int measureParams, int controlParams, int type)
{
    init(dynamParams, measureParams, controlParams, type);
}

void KalmanFilter::init(int DP, int MP, int CP, int type)
{
    CV_Assert( DP > 0 && MP > 0 );
    CV_Assert( type == CV_32F || type == CV_64F );
    CP = std::max(CP, 0);

    statePre = Mat::zeros(DP, 1, type);
    statePost = Mat::zeros(DP, 1, type);
    transitionMatrix = Mat::eye(DP, DP, type);

    processNoiseCov = Mat::eye(DP, DP, type);
    measurementMatrix = Mat::zeros(MP, DP, type);
    measurementNoiseCov = Mat::eye(MP, MP, type);

    errorCovPre = Mat::zeros(DP, DP, type);
    errorCovPost = Mat::zeros(DP, DP, type);
    gain = Mat::zeros(DP, MP, type);

    if( CP > 0 )
        controlMatrix = Mat::zeros(DP, CP, type);
    else
        controlMatrix.release();

    temp1.create(DP, DP, type);
    temp2.create(MP, DP, type);
    temp3.create(MP, MP, type);
    temp4.create(MP, DP, type);
    temp5.create(MP, 1, type);
}

const Mat& KalmanFilter::predict(const Mat& control)
{
    // update the state: x'(k) = A*x(k)
    statePre = transitionMatrix*statePost;

    if( control.data )
        // x'(k) = x'(k) + B*u(k)
        statePre += controlMatrix*control;

    // update error covariance matrices: temp1 = A*P(k)
    temp1 = transitionMatrix*errorCovPost;

    // P'(k) = temp1*At + Q
    gemm(temp1, transitionMatrix, 1, processNoiseCov, 1, errorCovPre, GEMM_2_T);

    // handle the case when there will be measurement before the next predict.
    statePre.copyTo(statePost);

    return statePre;
}

const Mat& KalmanFilter::correct(const Mat& measurement)
{
    // temp2 = H*P'(k)
    temp2 = measurementMatrix * errorCovPre;

    // temp3 = temp2*Ht + R
    gemm(temp2, measurementMatrix, 1, measurementNoiseCov, 1, temp3, GEMM_2_T);

    // temp4 = inv(temp3)*temp2 = Kt(k)
    solve(temp3, temp2, temp4, DECOMP_SVD);

    // K(k)
    gain = temp4.t();

    // temp5 = z(k) - H*x'(k)
    temp5 = measurement - measurementMatrix*statePre;

    // x(k) = x'(k) + K(k)*temp5
    statePost = statePre + gain*temp5;

    // P(k) = P'(k) - K(k)*temp2
    errorCovPost = errorCovPre - gain*temp2;

    return statePost;
}

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

CV_IMPL CvKalman*
cvCreateKalman( int DP, int MP, int CP )
{
    CvKalman *kalman = 0;

    if( DP <= 0 || MP <= 0 )
        CV_Error( CV_StsOutOfRange,
        "state and measurement vectors must have positive number of dimensions" );

    if( CP < 0 )
        CP = DP;

    /* allocating memory for the structure */
    kalman = (CvKalman *)cvAlloc( sizeof( CvKalman ));
    memset( kalman, 0, sizeof(*kalman));

    kalman->DP = DP;
    kalman->MP = MP;
    kalman->CP = CP;

    kalman->state_pre = cvCreateMat( DP, 1, CV_32FC1 );
    cvZero( kalman->state_pre );

    kalman->state_post = cvCreateMat( DP, 1, CV_32FC1 );
    cvZero( kalman->state_post );

    kalman->transition_matrix = cvCreateMat( DP, DP, CV_32FC1 );
    cvSetIdentity( kalman->transition_matrix );

    kalman->process_noise_cov = cvCreateMat( DP, DP, CV_32FC1 );
    cvSetIdentity( kalman->process_noise_cov );

    kalman->measurement_matrix = cvCreateMat( MP, DP, CV_32FC1 );
    cvZero( kalman->measurement_matrix );

    kalman->measurement_noise_cov = cvCreateMat( MP, MP, CV_32FC1 );
    cvSetIdentity( kalman->measurement_noise_cov );

    kalman->error_cov_pre = cvCreateMat( DP, DP, CV_32FC1 );

    kalman->error_cov_post = cvCreateMat( DP, DP, CV_32FC1 );
    cvZero( kalman->error_cov_post );

    kalman->gain = cvCreateMat( DP, MP, CV_32FC1 );

    if( CP > 0 )
    {
        kalman->control_matrix = cvCreateMat( DP, CP, CV_32FC1 );
        cvZero( kalman->control_matrix );
    }

    kalman->temp1 = cvCreateMat( DP, DP, CV_32FC1 );
    kalman->temp2 = cvCreateMat( MP, DP, CV_32FC1 );
    kalman->temp3 = cvCreateMat( MP, MP, CV_32FC1 );
    kalman->temp4 = cvCreateMat( MP, DP, CV_32FC1 );
    kalman->temp5 = cvCreateMat( MP, 1, CV_32FC1 );

#if 1
    kalman->PosterState = kalman->state_pre->data.fl;
    kalman->PriorState = kalman->state_post->data.fl;
    kalman->DynamMatr = kalman->transition_matrix->data.fl;
    kalman->MeasurementMatr = kalman->measurement_matrix->data.fl;
    kalman->MNCovariance = kalman->measurement_noise_cov->data.fl;
    kalman->PNCovariance = kalman->process_noise_cov->data.fl;
    kalman->KalmGainMatr = kalman->gain->data.fl;
    kalman->PriorErrorCovariance = kalman->error_cov_pre->data.fl;
    kalman->PosterErrorCovariance = kalman->error_cov_post->data.fl;
#endif

    return kalman;
}

CV_IMPL void
cvReleaseKalman( CvKalman** _kalman )
{
    CvKalman *kalman;

    if( !_kalman )
        CV_Error( CV_StsNullPtr, "" );

    kalman = *_kalman;
    if( !kalman )
        return;

    /* freeing the memory */
    cvReleaseMat( &kalman->state_pre );
    cvReleaseMat( &kalman->state_post );
    cvReleaseMat( &kalman->transition_matrix );
    cvReleaseMat( &kalman->control_matrix );
    cvReleaseMat( &kalman->measurement_matrix );
    cvReleaseMat( &kalman->process_noise_cov );
    cvReleaseMat( &kalman->measurement_noise_cov );
    cvReleaseMat( &kalman->error_cov_pre );
    cvReleaseMat( &kalman->gain );
    cvReleaseMat( &kalman->error_cov_post );
    cvReleaseMat( &kalman->temp1 );
    cvReleaseMat( &kalman->temp2 );
    cvReleaseMat( &kalman->temp3 );
    cvReleaseMat( &kalman->temp4 );
    cvReleaseMat( &kalman->temp5 );

    memset( kalman, 0, sizeof(*kalman));

    /* deallocating the structure */
    cvFree( _kalman );
}

CV_IMPL const CvMat*
cvKalmanPredict( CvKalman* kalman, const CvMat* control )
{
    if( !kalman )
        CV_Error( CV_StsNullPtr, "" );

    /* update the state */
    /* x'(k) = A*x(k) */
    cvMatMulAdd( kalman->transition_matrix, kalman->state_post, 0, kalman->state_pre );

    if( control && kalman->CP > 0 )
        /* x'(k) = x'(k) + B*u(k) */
        cvMatMulAdd( kalman->control_matrix, control, kalman->state_pre, kalman->state_pre );

    /* update error covariance matrices */
    /* temp1 = A*P(k) */
    cvMatMulAdd( kalman->transition_matrix, kalman->error_cov_post, 0, kalman->temp1 );

    /* P'(k) = temp1*At + Q */
    cvGEMM( kalman->temp1, kalman->transition_matrix, 1, kalman->process_noise_cov, 1,
                     kalman->error_cov_pre, CV_GEMM_B_T );

    /* handle the case when there will be measurement before the next predict */
    cvCopy(kalman->state_pre, kalman->state_post);

    return kalman->state_pre;
}

CV_IMPL const CvMat*
cvKalmanCorrect( CvKalman* kalman, const CvMat* measurement )
{
    if( !kalman || !measurement )
        CV_Error( CV_StsNullPtr, "" );

    /* temp2 = H*P'(k) */
    cvMatMulAdd( kalman->measurement_matrix, kalman->error_cov_pre, 0, kalman->temp2 );
    /* temp3 = temp2*Ht + R */
    cvGEMM( kalman->temp2, kalman->measurement_matrix, 1,
            kalman->measurement_noise_cov, 1, kalman->temp3, CV_GEMM_B_T );

    /* temp4 = inv(temp3)*temp2 = Kt(k) */
    cvSolve( kalman->temp3, kalman->temp2, kalman->temp4, CV_SVD );

    /* K(k) */
    cvTranspose( kalman->temp4, kalman->gain );

    /* temp5 = z(k) - H*x'(k) */
    cvGEMM( kalman->measurement_matrix, kalman->state_pre, -1, measurement, 1, kalman->temp5 );

    /* x(k) = x'(k) + K(k)*temp5 */
    cvMatMulAdd( kalman->gain, kalman->temp5, kalman->state_pre, kalman->state_post );

    /* P(k) = P'(k) - K(k)*temp2 */
    cvGEMM( kalman->gain, kalman->temp2, -1, kalman->error_cov_pre, 1,
                     kalman->error_cov_post, 0 );

    return kalman->state_post;
}

namespace cv
{

KalmanFilter::KalmanFilter() {}
KalmanFilter::KalmanFilter(int dynamParams, int measureParams, int controlParams, int type)
{
    init(dynamParams, measureParams, controlParams, type);
}

void KalmanFilter::init(int DP, int MP, int CP, int type)
{
    CV_Assert( DP > 0 && MP > 0 );
    CV_Assert( type == CV_32F || type == CV_64F );
    CP = std::max(CP, 0);

    statePre = Mat::zeros(DP, 1, type);
    statePost = Mat::zeros(DP, 1, type);
    transitionMatrix = Mat::eye(DP, DP, type);

    processNoiseCov = Mat::eye(DP, DP, type);
    measurementMatrix = Mat::zeros(MP, DP, type);
    measurementNoiseCov = Mat::eye(MP, MP, type);

    errorCovPre = Mat::zeros(DP, DP, type);
    errorCovPost = Mat::zeros(DP, DP, type);
    gain = Mat::zeros(DP, MP, type);

    if( CP > 0 )
        controlMatrix = Mat::zeros(DP, CP, type);
    else
        controlMatrix.release();

    temp1.create(DP, DP, type);
    temp2.create(MP, DP, type);
    temp3.create(MP, MP, type);
    temp4.create(MP, DP, type);
    temp5.create(MP, 1, type);
}

const Mat& KalmanFilter::predict(const Mat& control)
{
    // update the state: x'(k) = A*x(k)
    statePre = transitionMatrix*statePost;

    if( control.data )
        // x'(k) = x'(k) + B*u(k)
        statePre += controlMatrix*control;

    // update error covariance matrices: temp1 = A*P(k)
    temp1 = transitionMatrix*errorCovPost;

    // P'(k) = temp1*At + Q
    gemm(temp1, transitionMatrix, 1, processNoiseCov, 1, errorCovPre, GEMM_2_T);

    // handle the case when there will be measurement before the next predict.
    statePre.copyTo(statePost);
    errorCovPre.copyTo(errorCovPost);

    return statePre;
}

const Mat& KalmanFilter::correct(const Mat& measurement)
{
    // temp2 = H*P'(k)
    temp2 = measurementMatrix * errorCovPre;

    // temp3 = temp2*Ht + R
    gemm(temp2, measurementMatrix, 1, measurementNoiseCov, 1, temp3, GEMM_2_T);

    // temp4 = inv(temp3)*temp2 = Kt(k)
    solve(temp3, temp2, temp4, DECOMP_SVD);

    // K(k)
    gain = temp4.t();

    // temp5 = z(k) - H*x'(k)
    temp5 = measurement - measurementMatrix*statePre;

    // x(k) = x'(k) + K(k)*temp5
    statePost = statePre + gain*temp5;

    // P(k) = P'(k) - K(k)*temp2
    errorCovPost = errorCovPre - gain*temp2;

    return statePost;
}

};
<|endoftext|>


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

#include "dmlab2d/lib/env_lua_api/properties.h"

#include <string>

#include "absl/strings/string_view.h"
#include "dmlab2d/lib/lua/bind.h"
#include "dmlab2d/lib/lua/call.h"
#include "dmlab2d/lib/lua/lua.h"
#include "dmlab2d/lib/lua/n_results_or.h"
#include "dmlab2d/lib/lua/push.h"
#include "dmlab2d/lib/lua/read.h"
#include "dmlab2d/lib/lua/stack_resetter.h"
#include "dmlab2d/lib/lua/table_ref.h"
#include "dmlab2d/lib/support/logging.h"
#include "third_party/rl_api/env_c_api.h"

namespace deepmind::lab2d {
namespace {

EnvCApi_PropertyResult ProcessResult(lua_State* L, lua::NResultsOr result,
                                     absl::string_view call) {
  if (result.n_results() == 0) {
    LOG_IF(ERROR, !result.ok()) << "[" << call << "] - " << result.error();
    return EnvCApi_PropertyResult_PermissionDenied;
  }
  int prop_result;
  if (IsFound(lua::Read(L, 1, &prop_result))) {
    switch (prop_result) {
      case EnvCApi_PropertyResult_Success:
        return EnvCApi_PropertyResult_Success;
      case EnvCApi_PropertyResult_NotFound:
        return EnvCApi_PropertyResult_NotFound;
      case EnvCApi_PropertyResult_PermissionDenied:
        return EnvCApi_PropertyResult_PermissionDenied;
      case EnvCApi_PropertyResult_InvalidArgument:
        return EnvCApi_PropertyResult_InvalidArgument;
    }
  }

  LOG(ERROR) << "[" << call
             << "] - "
                "- Invalid return type from write! "
                "Must return integer in range [0, 3] - "
                "0 (properties.SUCCESS), "
                "1 (properties.NOT_FOUND), "
                "2 (properties.PERMISSION_DENIED), "
                "3 (properties.INVALID_ARGUMENT)";
  return EnvCApi_PropertyResult_PermissionDenied;
}

struct PropertyListCallbackData {
  void* userdata;
  void (*call)(void* userdata, const char* key,
               EnvCApi_PropertyAttributes flags);
};

lua::NResultsOr PropertyListCallBackFunction(lua_State* L) {
  auto* callback_data = static_cast<PropertyListCallbackData*>(
      lua_touserdata(L, lua_upvalueindex(1)));
  std::string key;
  absl::string_view mode;

  if (!IsFound(lua::Read(L, 1, &key))) {
    return "[propertyList.callback] - Missing Arg 1 - Key";
  }
  if (!IsFound(lua::Read(L, 2, &mode))) {
    return "[propertyList.callback] -  Missing Arg 2 - Mode";
  }

  for (auto c : mode) {
    switch (c) {
      case 'w':
      case 'r':
      case 'l':
        break;
      default:
        return "Type mismatch mode must in the format [r][w][l] of: "
               " 'r' - read-only,"
               " 'w' - write-only,"
               " 'l' - listable";
    }
  }

  int flags = 0;
  if (mode.find('w') != std::string::npos) {
    flags |= EnvCApi_PropertyAttributes_Writable;
  }
  if (mode.find('r') != std::string::npos) {
    flags |= EnvCApi_PropertyAttributes_Readable;
  }
  if (mode.find('l') != std::string::npos) {
    flags |= EnvCApi_PropertyAttributes_Listable;
  }
  if (flags != 0) {
    callback_data->call(callback_data->userdata, key.c_str(),
                        static_cast<EnvCApi_PropertyAttributes>(flags));
  }
  return 0;
}

}  // namespace

lua::NResultsOr Properties::Module(lua_State* L) {
  auto module = lua::TableRef::Create(L);
  module.Insert("SUCCESS", static_cast<int>(EnvCApi_PropertyResult_Success));
  module.Insert("NOT_FOUND", static_cast<int>(EnvCApi_PropertyResult_NotFound));
  module.Insert("PERMISSION_DENIED",
                static_cast<int>(EnvCApi_PropertyResult_PermissionDenied));
  module.Insert("INVALID_ARGUMENT",
                static_cast<int>(EnvCApi_PropertyResult_InvalidArgument));
  lua::Push(L, module);
  return 1;
}

EnvCApi_PropertyResult Properties::WriteProperty(const char* key,
                                                 const char* value) {
  lua_State* L = script_table_ref_.LuaState();
  lua::StackResetter stack_resetter(L);
  script_table_ref_.PushMemberFunction("writeProperty");
  if (lua_isnil(L, -2)) {
    return EnvCApi_PropertyResult_NotFound;
  }
  lua::Push(L, key);
  lua::Push(L, value);
  return ProcessResult(L, lua::Call(L, 3), "writeProperty");
}

EnvCApi_PropertyResult Properties::ReadProperty(const char* key,
                                                const char** value) {
  lua_State* L = script_table_ref_.LuaState();
  lua::StackResetter stack_resetter(L);
  script_table_ref_.PushMemberFunction("readProperty");
  if (lua_isnil(L, -2)) {
    return EnvCApi_PropertyResult_NotFound;
  }
  lua::Push(L, key);
  auto result = lua::Call(L, 2);
  if (result.n_results() == 1) {
    if (IsFound(lua::Read(L, 1, &property_storage_))) {
      *value = property_storage_.c_str();
      return EnvCApi_PropertyResult_Success;
    }
  }

  *value = "";
  return ProcessResult(L, result, "readProperty");
}

EnvCApi_PropertyResult Properties::ListProperty(
    void* userdata, const char* list_key,
    void (*prop_callback)(void* userdata, const char* key,
                          EnvCApi_PropertyAttributes flags)) {
  lua_State* L = script_table_ref_.LuaState();
  lua::StackResetter stack_resetter(L);
  script_table_ref_.PushMemberFunction("listProperty");
  if (lua_isnil(L, -2)) {
    return EnvCApi_PropertyResult_NotFound;
  }
  lua::Push(L, list_key);
  PropertyListCallbackData callback_data{userdata, prop_callback};
  lua_pushlightuserdata(L, &callback_data);
  lua_pushcclosure(L, lua::Bind<PropertyListCallBackFunction>, 1);
  return ProcessResult(L, lua::Call(L, 3), "listProperty");
}

}  // namespace deepmind::lab2d
<commit_msg>[lib/env_lua_api] Use absl::StrContains instead of find != npos<commit_after>// Copyright (C) 2018-2019 The DMLab2D Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////

#include "dmlab2d/lib/env_lua_api/properties.h"

#include <string>

#include "absl/strings/match.h"
#include "absl/strings/string_view.h"
#include "dmlab2d/lib/lua/bind.h"
#include "dmlab2d/lib/lua/call.h"
#include "dmlab2d/lib/lua/lua.h"
#include "dmlab2d/lib/lua/n_results_or.h"
#include "dmlab2d/lib/lua/push.h"
#include "dmlab2d/lib/lua/read.h"
#include "dmlab2d/lib/lua/stack_resetter.h"
#include "dmlab2d/lib/lua/table_ref.h"
#include "dmlab2d/lib/support/logging.h"
#include "third_party/rl_api/env_c_api.h"

namespace deepmind::lab2d {
namespace {

EnvCApi_PropertyResult ProcessResult(lua_State* L, lua::NResultsOr result,
                                     absl::string_view call) {
  if (result.n_results() == 0) {
    LOG_IF(ERROR, !result.ok()) << "[" << call << "] - " << result.error();
    return EnvCApi_PropertyResult_PermissionDenied;
  }
  int prop_result;
  if (IsFound(lua::Read(L, 1, &prop_result))) {
    switch (prop_result) {
      case EnvCApi_PropertyResult_Success:
        return EnvCApi_PropertyResult_Success;
      case EnvCApi_PropertyResult_NotFound:
        return EnvCApi_PropertyResult_NotFound;
      case EnvCApi_PropertyResult_PermissionDenied:
        return EnvCApi_PropertyResult_PermissionDenied;
      case EnvCApi_PropertyResult_InvalidArgument:
        return EnvCApi_PropertyResult_InvalidArgument;
    }
  }

  LOG(ERROR) << "[" << call
             << "] - "
                "- Invalid return type from write! "
                "Must return integer in range [0, 3] - "
                "0 (properties.SUCCESS), "
                "1 (properties.NOT_FOUND), "
                "2 (properties.PERMISSION_DENIED), "
                "3 (properties.INVALID_ARGUMENT)";
  return EnvCApi_PropertyResult_PermissionDenied;
}

struct PropertyListCallbackData {
  void* userdata;
  void (*call)(void* userdata, const char* key,
               EnvCApi_PropertyAttributes flags);
};

lua::NResultsOr PropertyListCallBackFunction(lua_State* L) {
  auto* callback_data = static_cast<PropertyListCallbackData*>(
      lua_touserdata(L, lua_upvalueindex(1)));
  std::string key;
  absl::string_view mode;

  if (!IsFound(lua::Read(L, 1, &key))) {
    return "[propertyList.callback] - Missing Arg 1 - Key";
  }
  if (!IsFound(lua::Read(L, 2, &mode))) {
    return "[propertyList.callback] -  Missing Arg 2 - Mode";
  }

  for (auto c : mode) {
    switch (c) {
      case 'w':
      case 'r':
      case 'l':
        break;
      default:
        return "Type mismatch mode must in the format [r][w][l] of: "
               " 'r' - read-only,"
               " 'w' - write-only,"
               " 'l' - listable";
    }
  }

  int flags = 0;
  if (absl::StrContains(mode, 'w')) {
    flags |= EnvCApi_PropertyAttributes_Writable;
  }
  if (absl::StrContains(mode, 'r')) {
    flags |= EnvCApi_PropertyAttributes_Readable;
  }
  if (absl::StrContains(mode, 'l')) {
    flags |= EnvCApi_PropertyAttributes_Listable;
  }
  if (flags != 0) {
    callback_data->call(callback_data->userdata, key.c_str(),
                        static_cast<EnvCApi_PropertyAttributes>(flags));
  }
  return 0;
}

}  // namespace

lua::NResultsOr Properties::Module(lua_State* L) {
  auto module = lua::TableRef::Create(L);
  module.Insert("SUCCESS", static_cast<int>(EnvCApi_PropertyResult_Success));
  module.Insert("NOT_FOUND", static_cast<int>(EnvCApi_PropertyResult_NotFound));
  module.Insert("PERMISSION_DENIED",
                static_cast<int>(EnvCApi_PropertyResult_PermissionDenied));
  module.Insert("INVALID_ARGUMENT",
                static_cast<int>(EnvCApi_PropertyResult_InvalidArgument));
  lua::Push(L, module);
  return 1;
}

EnvCApi_PropertyResult Properties::WriteProperty(const char* key,
                                                 const char* value) {
  lua_State* L = script_table_ref_.LuaState();
  lua::StackResetter stack_resetter(L);
  script_table_ref_.PushMemberFunction("writeProperty");
  if (lua_isnil(L, -2)) {
    return EnvCApi_PropertyResult_NotFound;
  }
  lua::Push(L, key);
  lua::Push(L, value);
  return ProcessResult(L, lua::Call(L, 3), "writeProperty");
}

EnvCApi_PropertyResult Properties::ReadProperty(const char* key,
                                                const char** value) {
  lua_State* L = script_table_ref_.LuaState();
  lua::StackResetter stack_resetter(L);
  script_table_ref_.PushMemberFunction("readProperty");
  if (lua_isnil(L, -2)) {
    return EnvCApi_PropertyResult_NotFound;
  }
  lua::Push(L, key);
  auto result = lua::Call(L, 2);
  if (result.n_results() == 1) {
    if (IsFound(lua::Read(L, 1, &property_storage_))) {
      *value = property_storage_.c_str();
      return EnvCApi_PropertyResult_Success;
    }
  }

  *value = "";
  return ProcessResult(L, result, "readProperty");
}

EnvCApi_PropertyResult Properties::ListProperty(
    void* userdata, const char* list_key,
    void (*prop_callback)(void* userdata, const char* key,
                          EnvCApi_PropertyAttributes flags)) {
  lua_State* L = script_table_ref_.LuaState();
  lua::StackResetter stack_resetter(L);
  script_table_ref_.PushMemberFunction("listProperty");
  if (lua_isnil(L, -2)) {
    return EnvCApi_PropertyResult_NotFound;
  }
  lua::Push(L, list_key);
  PropertyListCallbackData callback_data{userdata, prop_callback};
  lua_pushlightuserdata(L, &callback_data);
  lua_pushcclosure(L, lua::Bind<PropertyListCallBackFunction>, 1);
  return ProcessResult(L, lua::Call(L, 3), "listProperty");
}

}  // namespace deepmind::lab2d
<|endoftext|>


<commit_before>#include "Graphics/Window.h"
#include "GameEngine/GameEngine.h"
#include "Events/Event.hpp"
#include "Audio/AudioSystem.hpp"

int main()
{
	Graphics::Window window(L"OWO");
	ASSB::GameEngine Engine(window);

  // Events thing
  Events::Event e;

  // Test audio system
  Audio::AudioSystem a(10);
  Audio::AudioFile af{ "../../Assets/Audio/Confirm1.wav" };
  a.PreloadFile(af);
  a.PlayFile(af, true);

	bool run = true;
	MSG msg;

  // Primary loop
	while (run)
	{
		while (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
			if (msg.message == WM_QUIT)
				run = false;
		}

		Engine.UpdateCamera();
		Engine.Loop();
	}

	return 0;
}<commit_msg>confirmed BEEP<commit_after>#include "Graphics/Window.h"
#include "GameEngine/GameEngine.h"
#include "Events/Event.hpp"
#include "Audio/AudioSystem.hpp"

int main()
{
	Graphics::Window window(L"OWO");
	ASSB::GameEngine Engine(window);

  // Events thing
  Events::Event e;

  // Test audio system
  Audio::AudioSystem a(10);
  Audio::AudioFile af{ "../../../Assets/Audio/Confirm1.wav" };
  a.PreloadFile(af);
  a.PlayFile(af, true);

	bool run = true;
	MSG msg;

  // Primary loop
	while (run)
	{
		while (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
			if (msg.message == WM_QUIT)
				run = false;
		}

		Engine.UpdateCamera();
		Engine.Loop();
	}

	return 0;
}<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#ifndef ETL_DYN_VECTOR_HPP
#define ETL_DYN_VECTOR_HPP

#include <cstddef>
#include <type_traits>
#include <utility>
#include <algorithm>
#include <array>
#include <vector>
#include <numeric>
#include <initializer_list>

#include "assert.hpp"
#include "tmp.hpp"
#include "fast_op.hpp"
#include "fast_expr.hpp"

namespace etl {

template<typename T>
struct dyn_vector {
public:
    using         value_type = T;
    using       storage_impl = std::vector<value_type>;
    using           iterator = typename storage_impl::iterator;
    using     const_iterator = typename storage_impl::const_iterator;

private:
    storage_impl _data;
    const std::size_t rows;

public:

    //{{{ Construction

    dyn_vector(std::size_t rows) : _data(rows), rows(rows) {
        //Nothing else to init
    }

    dyn_vector(std::size_t rows, const value_type& value) : _data(rows, value), rows(rows) {
        //Nothing else to init
    }

    //TODO Probably a better way in order to move elements
    dyn_vector(std::initializer_list<value_type> l) : _data(l), rows(l.size()){
        //Nothing else to init
    }

    explicit dyn_vector(const std::vector<value_type>& v) : _data(v), rows(v.size()){
        //Nothing else to init
    }

    template<typename LE, typename Op, typename RE>
    dyn_vector(const binary_expr<value_type, LE, Op, RE>& e) : _data(::size(e)), rows(::size(e)) {
        for(std::size_t i = 0; i < size(); ++i){
            _data[i] = e[i];
        }
    }

    template<typename E, typename Op>
    dyn_vector(const unary_expr<value_type, E, Op>& e) : _data(::size(e)), rows(::size(e)) {
        for(std::size_t i = 0; i < size(); ++i){
            _data[i] = e[i];
        }
    }

    //Prohibit copy
    dyn_vector(const dyn_vector& rhs) = delete;

    //Move is possible
    dyn_vector(dyn_vector&& rhs) = default;

    //}}}

    //{{{Assignment

    //Set every element to the same scalar
    void operator=(const value_type& value){
        std::fill(_data.begin(), _data.end(), value);
    }

    //Copy
    dyn_vector& operator=(const dyn_vector& rhs){
        ensure_same_size(*this, rhs);

        for(std::size_t i = 0; i < size(); ++i){
            _data[i] = rhs[i];
        }

        return *this;
    }

    //Move is possible
    dyn_vector& operator=(dyn_vector&& rhs) = default;

    //Construct from expression

    template<typename LE, typename Op, typename RE>
    dyn_vector& operator=(const binary_expr<value_type, LE, Op, RE>&& e){
        ensure_same_size(*this, e);

        for(std::size_t i = 0; i < size(); ++i){
            _data[i] = e[i];
        }

        return *this;
    }

    template<typename E, typename Op>
    dyn_vector& operator=(const unary_expr<value_type, E, Op>&& e){
        ensure_same_size(*this, e);

        for(std::size_t i = 0; i < size(); ++i){
            _data[i] = e[i];
        }

        return *this;
    }

    //Allow copy from other containers

    template<typename Container, enable_if_u<std::is_same<typename Container::value_type, value_type>::value> = detail::dummy>
    dyn_vector& operator=(const Container& vec){
        etl_assert(vec.size() == size(), "Cannot copy from a vector of different size");

        for(std::size_t i = 0; i < size(); ++i){
            _data[i] = vec[i];
        }

        return *this;
    }

    //}}}

    //{{{ Accessors

    size_t size() const {
        return rows;
    }

    value_type& operator()(size_t i){
        etl_assert(i < rows, "Out of bounds");

        return _data[i];
    }

    const value_type& operator()(size_t i) const {
        etl_assert(i < rows, "Out of bounds");

        return _data[i];
    }

    value_type& operator[](size_t i){
        etl_assert(i < rows, "Out of bounds");

        return _data[i];
    }

    const value_type& operator[](size_t i) const {
        etl_assert(i < rows, "Out of bounds");

        return _data[i];
    }

    const_iterator begin() const {
        return _data.begin();
    }

    iterator begin(){
        return _data.begin();
    }

    const_iterator end() const {
        return _data.end();
    }

    iterator end(){
        return _data.end();
    }

    //}}}
};

} //end of namespace etl

#endif
<commit_msg>Make the constructor broader<commit_after>//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#ifndef ETL_DYN_VECTOR_HPP
#define ETL_DYN_VECTOR_HPP

#include <cstddef>
#include <type_traits>
#include <utility>
#include <algorithm>
#include <array>
#include <vector>
#include <numeric>
#include <initializer_list>

#include "assert.hpp"
#include "tmp.hpp"
#include "fast_op.hpp"
#include "fast_expr.hpp"

namespace etl {

template<typename T>
struct dyn_vector {
public:
    using         value_type = T;
    using       storage_impl = std::vector<value_type>;
    using           iterator = typename storage_impl::iterator;
    using     const_iterator = typename storage_impl::const_iterator;

private:
    storage_impl _data;
    const std::size_t rows;

public:

    //{{{ Construction

    dyn_vector(std::size_t rows) : _data(rows), rows(rows) {
        //Nothing else to init
    }

    dyn_vector(std::size_t rows, const value_type& value) : _data(rows, value), rows(rows) {
        //Nothing else to init
    }

    //TODO Probably a better way in order to move elements
    dyn_vector(std::initializer_list<value_type> l) : _data(l), rows(l.size()){
        //Nothing else to init
    }

    template<typename LE, typename Op, typename RE>
    dyn_vector(const binary_expr<value_type, LE, Op, RE>& e) : _data(::size(e)), rows(::size(e)) {
        for(std::size_t i = 0; i < size(); ++i){
            _data[i] = e[i];
        }
    }

    template<typename E, typename Op>
    dyn_vector(const unary_expr<value_type, E, Op>& e) : _data(::size(e)), rows(::size(e)) {
        for(std::size_t i = 0; i < size(); ++i){
            _data[i] = e[i];
        }
    }

    //Allow copy from other containers

    template<typename Container, enable_if_u<std::is_same<typename Container::value_type, value_type>::value> = detail::dummy>
    explicit dyn_vector(const Container& vec) : _data(vec.size()), rows(vec.size()) {
        std::copy(vec.begin(), vec.end(), begin());
    }

    //Prohibit copy
    dyn_vector(const dyn_vector& rhs) = delete;

    //Move is possible
    dyn_vector(dyn_vector&& rhs) = default;

    //}}}

    //{{{Assignment

    //Set every element to the same scalar
    void operator=(const value_type& value){
        std::fill(_data.begin(), _data.end(), value);
    }

    //Copy
    dyn_vector& operator=(const dyn_vector& rhs){
        ensure_same_size(*this, rhs);

        for(std::size_t i = 0; i < size(); ++i){
            _data[i] = rhs[i];
        }

        return *this;
    }

    //Move is possible
    dyn_vector& operator=(dyn_vector&& rhs) = default;

    //Construct from expression

    template<typename LE, typename Op, typename RE>
    dyn_vector& operator=(const binary_expr<value_type, LE, Op, RE>&& e){
        ensure_same_size(*this, e);

        for(std::size_t i = 0; i < size(); ++i){
            _data[i] = e[i];
        }

        return *this;
    }

    template<typename E, typename Op>
    dyn_vector& operator=(const unary_expr<value_type, E, Op>&& e){
        ensure_same_size(*this, e);

        for(std::size_t i = 0; i < size(); ++i){
            _data[i] = e[i];
        }

        return *this;
    }

    //Allow copy from other containers

    template<typename Container, enable_if_u<std::is_same<typename Container::value_type, value_type>::value> = detail::dummy>
    dyn_vector& operator=(const Container& vec){
        etl_assert(vec.size() == size(), "Cannot copy from a vector of different size");

        for(std::size_t i = 0; i < size(); ++i){
            _data[i] = vec[i];
        }

        return *this;
    }

    //}}}

    //{{{ Accessors

    size_t size() const {
        return rows;
    }

    value_type& operator()(size_t i){
        etl_assert(i < rows, "Out of bounds");

        return _data[i];
    }

    const value_type& operator()(size_t i) const {
        etl_assert(i < rows, "Out of bounds");

        return _data[i];
    }

    value_type& operator[](size_t i){
        etl_assert(i < rows, "Out of bounds");

        return _data[i];
    }

    const value_type& operator[](size_t i) const {
        etl_assert(i < rows, "Out of bounds");

        return _data[i];
    }

    const_iterator begin() const {
        return _data.begin();
    }

    iterator begin(){
        return _data.begin();
    }

    const_iterator end() const {
        return _data.end();
    }

    iterator end(){
        return _data.end();
    }

    //}}}
};

} //end of namespace etl

#endif
<|endoftext|>


<commit_before>// The MIT License (MIT)

// Copyright (c) 2013 Danny Y., Rapptz

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

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

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

#ifndef SOL_OBJECT_HPP
#define SOL_OBJECT_HPP

#include "reference.hpp"
#include "stack.hpp"

namespace sol {
class object : public reference {
public:
    object(lua_State* L, int index = -1): reference(L, index) {}
    object() = default;

    template<typename T>
    auto as() const -> decltype(stack::get<T>(state())) {
        push();
        type_assert(state(), -1, type_of<T>());
        return stack::get<T>(state());
    }

    template<typename T>
    bool is() const {
        push();
        auto expected = type_of<T>();
        auto actual = lua_type(state(), -1);
        return (static_cast<int>(expected) == actual) || (expected == type::poly);
    }

    explicit operator bool() const {
        return is<nil_t>();
    }
};

inline bool operator==(const object& lhs, const nil_t&) {
    return lhs.is<nil_t>();
}

inline bool operator==(const nil_t&, const object& rhs) {
    return rhs.is<nil_t>();
}

inline bool operator!=(const object& lhs, const nil_t&) {
    return !lhs.is<nil_t>();
}

inline bool operator!=(const nil_t&, const object& rhs) {
    return !rhs.is<nil_t>();
}
} // sol

#endif // SOL_OBJECT_HPP
<commit_msg>Fix explicit operator bool to be negated is<nil_t>()<commit_after>// The MIT License (MIT)

// Copyright (c) 2013 Danny Y., Rapptz

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

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

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

#ifndef SOL_OBJECT_HPP
#define SOL_OBJECT_HPP

#include "reference.hpp"
#include "stack.hpp"

namespace sol {
class object : public reference {
public:
    object(lua_State* L, int index = -1): reference(L, index) {}
    object() = default;

    template<typename T>
    auto as() const -> decltype(stack::get<T>(state())) {
        push();
        type_assert(state(), -1, type_of<T>());
        return stack::get<T>(state());
    }

    template<typename T>
    bool is() const {
        push();
        auto expected = type_of<T>();
        auto actual = lua_type(state(), -1);
        return (static_cast<int>(expected) == actual) || (expected == type::poly);
    }

    explicit operator bool() const {
        return !is<nil_t>();
    }
};

inline bool operator==(const object& lhs, const nil_t&) {
    return lhs.is<nil_t>();
}

inline bool operator==(const nil_t&, const object& rhs) {
    return rhs.is<nil_t>();
}

inline bool operator!=(const object& lhs, const nil_t&) {
    return !lhs.is<nil_t>();
}

inline bool operator!=(const nil_t&, const object& rhs) {
    return !rhs.is<nil_t>();
}
} // sol

#endif // SOL_OBJECT_HPP
<|endoftext|>


<commit_before>#include "fileIndex.h"
#include "utils/logger.h"
#include <fstream>
#include <iomanip>
#include <regex>
#include <algorithm>
#include <physfs.h>
#include <assert.h>
#include "../lib/physfs/extras/ignorecase.h"

using namespace VDFS;

FileIndex::FileIndex()
{
}

FileIndex::~FileIndex()
{
    if (PHYSFS_isInit()) PHYSFS_deinit();
}

void FileIndex::initVDFS(const char *argv0)
{
    if (!PHYSFS_isInit()) PHYSFS_init(argv0);
}

/**
* @brief Loads a VDF-File and initializes everything
*/
bool FileIndex::loadVDF(const std::string& vdf, uint32_t priority, const std::string& mountPoint)
{
    if (!PHYSFS_mount(vdf.c_str(), mountPoint.c_str(), 1))
    {
        LogInfo() << "Couldn't load VDF-Archive " << vdf << ": " << PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode());
        return false;
    }

    return true;
}

bool FileIndex::mountFolder(const std::string& path, const std::string& mountPoint)
{
    if (!PHYSFS_mount(path.c_str(), mountPoint.c_str(), 1))
    {
        LogInfo() << "Couldn't mount directory " << path << ": " << PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode());
        return false;
    }

    return true;
}

/**
* @brief Fills a vector with the data of the given file
*/
bool FileIndex::getFileData(const std::string& file, std::vector<uint8_t>& data) const
{
    assert(isFinalized());

    std::string caseSensitivePath = findCaseSensitiveNameOf(file);
    bool exists = caseSensitivePath != "";

    if (!exists) return false;

    PHYSFS_File *handle = PHYSFS_openRead(caseSensitivePath.c_str());
    if (!handle)
    {
        LogInfo() << "Cannot read file " << file << ": " << PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode());
        return false;
    }

    auto length = PHYSFS_fileLength(handle);
    data.resize(length);
    if (PHYSFS_readBytes(handle, data.data(), length) < length)
    {
        LogInfo() << "Cannot read file " << file << ": " << PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode());
        PHYSFS_close(handle);
        return false;
    }
    PHYSFS_close(handle);
    return true;
}

bool FileIndex::hasFile(const std::string& name) const
{
    assert(isFinalized());

    return findCaseSensitiveNameOf(name) != "";
}

int64_t VDFS::FileIndex::getLastModTime(const std::string& name)
{
    int64_t result = -1;
    std::ifstream infile(name);
    if (infile.good())
    {
        std::string firstLine;
        std::getline(infile, firstLine);
        struct std::tm tm;
        std::smatch match;

        // Regex of the datetime used by G1 and G2 e.g. (Thu, 19 Dec 2002 19:24:42 GMT)
        std::regex rgxG1G2("\\(.*, ([[:digit:]]*) (.*) ([[:digit:]]*) ([[:digit:]]*):([[:digit:]]*):([[:digit:]]*) GMT\\)");

        // Regex of the datetime used by G1 e.g. 19.06.2001  18:58.06
        std::regex rgxG1("([[:digit:]]*)\\.([[:digit:]]*)\\.([[:digit:]]*)  ([[:digit:]]*):([[:digit:]]*).([[:digit:]]*)");

        if (std::regex_search(firstLine, match, rgxG1G2))
        {
            std::istringstream datetime(match[1].str() + "-" + match[2].str() + "-"
                + match[3].str() + " " + match[4].str() + ":"
                + match[5].str() + ":" + match[6].str());

            datetime >> std::get_time(&tm, "%d-%b-%Y %H:%M:%S");
            if (!datetime.fail())
                result = std::mktime(&tm);
        }
        else if (std::regex_search(firstLine, match, rgxG1))
        {
            std::istringstream datetime(match[1].str() + "-" + match[2].str() + "-"
                + match[3].str() + " " + match[4].str() + ":"
                + match[5].str() + ":" + match[6].str());

            datetime >> std::get_time(&tm, "%d-%m-%Y %H:%M:%S");
            if (!datetime.fail())
                result = std::mktime(&tm);
        }

        infile.close();
    }

    return result;
}

std::vector<std::string> FileIndex::getKnownFiles(const std::string& path) const
{
    assert(isFinalized());

    std::string filePath(path);
    std::vector<std::string> vec;
    bool exists = PHYSFSEXT_locateCorrectCase(&filePath[0]) == 0;
    if (!exists) {
        return vec;
    }

    char **files = PHYSFS_enumerateFiles(filePath.c_str());
    char **i;
    for (i = files; *i != NULL; i++)
        vec.push_back(*i);
    PHYSFS_freeList(files);
    return vec;
}

void FileIndex::updateUpperedFilenamesMap()
{
    std::vector<std::string> files = getKnownFiles();

    m_FilenamesByUpperedFileNames.clear();
    for (const std::string& file : files)
    {
        std::string uppered = file;
        std::transform(uppered.begin(), uppered.end(), uppered.begin(), ::toupper);

        m_FilenamesByUpperedFileNames[uppered] = file;
    }
}

std::string FileIndex::findCaseSensitiveNameOf(const std::string& caseInsensitiveName) const
{
    assert(isFinalized());

    std::string uppered = caseInsensitiveName;
    std::transform(caseInsensitiveName.begin(), caseInsensitiveName.end(), uppered.begin(), ::toupper);

    auto it = m_FilenamesByUpperedFileNames.find(uppered);

    if (it == m_FilenamesByUpperedFileNames.end())
        return "";

    return it->second;
}

void FileIndex::finalizeLoad()
{
    // Must be called here so opening files will actually work
    updateUpperedFilenamesMap();
}

bool FileIndex::isFinalized() const
{
    return !m_FilenamesByUpperedFileNames.empty();
}
<commit_msg>VDFS: Cannot load new archives when fileindex was already finalized<commit_after>#include "fileIndex.h"
#include "utils/logger.h"
#include <fstream>
#include <iomanip>
#include <regex>
#include <algorithm>
#include <physfs.h>
#include <assert.h>
#include "../lib/physfs/extras/ignorecase.h"

using namespace VDFS;

FileIndex::FileIndex()
{
}

FileIndex::~FileIndex()
{
    if (PHYSFS_isInit()) PHYSFS_deinit();
}

void FileIndex::initVDFS(const char *argv0)
{
    if (!PHYSFS_isInit()) PHYSFS_init(argv0);
}

/**
* @brief Loads a VDF-File and initializes everything
*/
bool FileIndex::loadVDF(const std::string& vdf, uint32_t priority, const std::string& mountPoint)
{
    assert(!isFinalized());

    if (!isFinalized())
    {
        LogWarn() << "Cannot load new VDFS-archives into finalized index!";
        return false;
    }

    if (!PHYSFS_mount(vdf.c_str(), mountPoint.c_str(), 1))
    {
        LogInfo() << "Couldn't load VDF-Archive " << vdf << ": " << PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode());
        return false;
    }

    return true;
}

bool FileIndex::mountFolder(const std::string& path, const std::string& mountPoint)
{
    if (!PHYSFS_mount(path.c_str(), mountPoint.c_str(), 1))
    {
        LogInfo() << "Couldn't mount directory " << path << ": " << PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode());
        return false;
    }

    return true;
}

/**
* @brief Fills a vector with the data of the given file
*/
bool FileIndex::getFileData(const std::string& file, std::vector<uint8_t>& data) const
{
    assert(isFinalized());

    std::string caseSensitivePath = findCaseSensitiveNameOf(file);
    bool exists = caseSensitivePath != "";

    if (!exists) return false;

    PHYSFS_File *handle = PHYSFS_openRead(caseSensitivePath.c_str());
    if (!handle)
    {
        LogInfo() << "Cannot read file " << file << ": " << PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode());
        return false;
    }

    auto length = PHYSFS_fileLength(handle);
    data.resize(length);
    if (PHYSFS_readBytes(handle, data.data(), length) < length)
    {
        LogInfo() << "Cannot read file " << file << ": " << PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode());
        PHYSFS_close(handle);
        return false;
    }
    PHYSFS_close(handle);
    return true;
}

bool FileIndex::hasFile(const std::string& name) const
{
    assert(isFinalized());

    return findCaseSensitiveNameOf(name) != "";
}

int64_t VDFS::FileIndex::getLastModTime(const std::string& name)
{
    int64_t result = -1;
    std::ifstream infile(name);
    if (infile.good())
    {
        std::string firstLine;
        std::getline(infile, firstLine);
        struct std::tm tm;
        std::smatch match;

        // Regex of the datetime used by G1 and G2 e.g. (Thu, 19 Dec 2002 19:24:42 GMT)
        std::regex rgxG1G2("\\(.*, ([[:digit:]]*) (.*) ([[:digit:]]*) ([[:digit:]]*):([[:digit:]]*):([[:digit:]]*) GMT\\)");

        // Regex of the datetime used by G1 e.g. 19.06.2001  18:58.06
        std::regex rgxG1("([[:digit:]]*)\\.([[:digit:]]*)\\.([[:digit:]]*)  ([[:digit:]]*):([[:digit:]]*).([[:digit:]]*)");

        if (std::regex_search(firstLine, match, rgxG1G2))
        {
            std::istringstream datetime(match[1].str() + "-" + match[2].str() + "-"
                + match[3].str() + " " + match[4].str() + ":"
                + match[5].str() + ":" + match[6].str());

            datetime >> std::get_time(&tm, "%d-%b-%Y %H:%M:%S");
            if (!datetime.fail())
                result = std::mktime(&tm);
        }
        else if (std::regex_search(firstLine, match, rgxG1))
        {
            std::istringstream datetime(match[1].str() + "-" + match[2].str() + "-"
                + match[3].str() + " " + match[4].str() + ":"
                + match[5].str() + ":" + match[6].str());

            datetime >> std::get_time(&tm, "%d-%m-%Y %H:%M:%S");
            if (!datetime.fail())
                result = std::mktime(&tm);
        }

        infile.close();
    }

    return result;
}

std::vector<std::string> FileIndex::getKnownFiles(const std::string& path) const
{
    assert(isFinalized());

    std::string filePath(path);
    std::vector<std::string> vec;
    bool exists = PHYSFSEXT_locateCorrectCase(&filePath[0]) == 0;
    if (!exists) {
        return vec;
    }

    char **files = PHYSFS_enumerateFiles(filePath.c_str());
    char **i;
    for (i = files; *i != NULL; i++)
        vec.push_back(*i);
    PHYSFS_freeList(files);
    return vec;
}

void FileIndex::updateUpperedFilenamesMap()
{
    std::vector<std::string> files = getKnownFiles();

    m_FilenamesByUpperedFileNames.clear();
    for (const std::string& file : files)
    {
        std::string uppered = file;
        std::transform(uppered.begin(), uppered.end(), uppered.begin(), ::toupper);

        m_FilenamesByUpperedFileNames[uppered] = file;
    }
}

std::string FileIndex::findCaseSensitiveNameOf(const std::string& caseInsensitiveName) const
{
    assert(isFinalized());

    std::string uppered = caseInsensitiveName;
    std::transform(caseInsensitiveName.begin(), caseInsensitiveName.end(), uppered.begin(), ::toupper);

    auto it = m_FilenamesByUpperedFileNames.find(uppered);

    if (it == m_FilenamesByUpperedFileNames.end())
        return "";

    return it->second;
}

void FileIndex::finalizeLoad()
{
    // Must be called here so opening files will actually work
    updateUpperedFilenamesMap();
}

bool FileIndex::isFinalized() const
{
    return !m_FilenamesByUpperedFileNames.empty();
}
<|endoftext|>


<commit_before><commit_msg>Osbtacle detector - Top view x coordinate centered<commit_after><|endoftext|>


<commit_before>/*
 * This is part of the FL library, a C++ Bayesian filtering library
 * (https://github.com/filtering-library)
 *
 * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)
 * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)
 *
 * Max-Planck Institute for Intelligent Systems, AMD Lab
 * University of Southern California, CLMC Lab
 *
 * This Source Code Form is subject to the terms of the MIT License (MIT).
 * A copy of the license can be found in the LICENSE file distributed with this
 * source code.
 */

/**
 * \file random_seed.hpp
 * \date 2014
 * \author Manuel Wuthrich (manuel.wuthrich@gmail.com)
 */

#ifndef FL__UTIL__RANDOM_SEED_HPP
#define FL__UTIL__RANDOM_SEED_HPP

#include <ctime>

#define RANDOM_SEED (unsigned) std::time(0) // 1

#endif
<commit_msg>Added mt11213b mersenne twister declaration to random<commit_after>/*
 * This is part of the FL library, a C++ Bayesian filtering library
 * (https://github.com/filtering-library)
 *
 * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)
 * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)
 *
 * Max-Planck Institute for Intelligent Systems, AMD Lab
 * University of Southern California, CLMC Lab
 *
 * This Source Code Form is subject to the terms of the MIT License (MIT).
 * A copy of the license can be found in the LICENSE file distributed with this
 * source code.
 */

/**
 * \file random.hpp
 * \date 2014
 * \author Jan Issac (jan.issac@gmail.com)
 * \author Manuel Wuthrich (manuel.wuthrich@gmail.com)
 */

#ifndef FL__UTIL__RANDOM_HPP
#define FL__UTIL__RANDOM_HPP

#include <ctime>
#include <random>

/**
 * \brief global seed
 *
 * \ingroup random
 */
#ifdef USE_RANDOM_SEED
    #define RANDOM_SEED (unsigned int) std::time(0)
#else
    #define RANDOM_SEED 1
#endif

namespace fl
{

/**
 * Mersenne Twister specialization mt11213b \cite matsumoto1998mersenne
 * \ingroup random
 *
 * mt11213b is slightly faster than mt19937
 */
typedef std::mersenne_twister_engine<
                uint32_t,
                32, 351, 175, 19,
                0xccab8ee7, 11,
                0xffffffff, 7,
                0x31b6ab00, 15,
                0xffe50000, 17,
                1812433253 > mt11213b;

}

#endif
<|endoftext|>


<commit_before>// WARNING: this sample is under construction! Use it on your own risk.
#if defined _MSC_VER && _MSC_VER >= 1400
#pragma warning(disable : 4100)
#endif

#include "cvconfig.h"
#include <iostream>
#include <iomanip>
#include "opencv2/contrib/contrib.hpp"
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/gpu/gpu.hpp"

using namespace std;
using namespace cv;
using namespace cv::gpu;

#if !defined(HAVE_CUDA)
int main(int argc, const char **argv)
{
    cout << "Please compile the library with CUDA support" << endl;
    return -1;
}
#else

void help()
{
    cout << "Usage: ./cascadeclassifier <cascade_file> <image_or_video_or_cameraid>\n"
            "Using OpenCV version " << CV_VERSION << endl << endl;
}

template<class T>
void convertAndResize(const T& src, T& gray, T& resized, double scale)
{
    if (src.channels() == 3)
    {
        cvtColor( src, gray, CV_BGR2GRAY );
    }
    else
    {
        gray = src;
    }

    Size sz(cvRound(gray.cols * scale), cvRound(gray.rows * scale));

    if (scale != 1)
    {
        resize(gray, resized, sz);
    }
    else
    {
        resized = gray;
    }
}

void matPrint(Mat &img, int lineOffsY, Scalar fontColor, const ostringstream &ss)
{
    int fontFace = FONT_HERSHEY_DUPLEX;
    double fontScale = 0.8;
    int fontThickness = 2;
    Size fontSize = cv::getTextSize("T[]", fontFace, fontScale, fontThickness, 0);

    Point org;
    org.x = 1;
    org.y = 3 * fontSize.height * (lineOffsY + 1) / 2;
    putText(img, ss.str(), org, fontFace, fontScale, CV_RGB(0,0,0), 5*fontThickness/2, 16);
    putText(img, ss.str(), org, fontFace, fontScale, fontColor, fontThickness, 16);
}

void displayState(Mat &canvas, bool bHelp, bool bGpu, bool bLargestFace, bool bFilter, double fps)
{
    Scalar fontColorRed = CV_RGB(255,0,0);
    Scalar fontColorNV  = CV_RGB(118,185,0);

    ostringstream ss;
    ss << "FPS = " << setprecision(1) << fixed << fps;
    matPrint(canvas, 0, fontColorRed, ss);
    ss.str("");
    ss << "[" << canvas.cols << "x" << canvas.rows << "], " <<
        (bGpu ? "GPU, " : "CPU, ") <<
        (bLargestFace ? "OneFace, " : "MultiFace, ") <<
        (bFilter ? "Filter:ON" : "Filter:OFF");
    matPrint(canvas, 1, fontColorRed, ss);

    if (bHelp)
    {
        matPrint(canvas, 2, fontColorNV, ostringstream("Space - switch GPU / CPU"));
        matPrint(canvas, 3, fontColorNV, ostringstream("M - switch OneFace / MultiFace"));
        matPrint(canvas, 4, fontColorNV, ostringstream("F - toggle rectangles Filter"));
        matPrint(canvas, 5, fontColorNV, ostringstream("H - toggle hotkeys help"));
        matPrint(canvas, 6, fontColorNV, ostringstream("1/Q - increase/decrease scale"));
    }
    else
    {
        matPrint(canvas, 2, fontColorNV, ostringstream("H - toggle hotkeys help"));
    }
}

int main(int argc, const char *argv[])
{
    if (argc != 3)
    {
        return help(), -1;
    }

    if (getCudaEnabledDeviceCount() == 0)
    {
        return cerr << "No GPU found or the library is compiled without GPU support" << endl, -1;
    }

    VideoCapture capture;

    string cascadeName = argv[1];
    string inputName = argv[2];

    CascadeClassifier_GPU cascade_gpu;
    if (!cascade_gpu.load(cascadeName))
    {
        return cerr << "ERROR: Could not load cascade classifier \"" << cascadeName << "\"" << endl, help(), -1;
    }

    CascadeClassifier cascade_cpu;
    if (!cascade_cpu.load(cascadeName))
    {
        return cerr << "ERROR: Could not load cascade classifier \"" << cascadeName << "\"" << endl, help(), -1;
    }

    Mat image = imread(inputName);

    if (image.empty())
    {
        if (!capture.open(inputName))
        {
            int camid = -1;
            istringstream iss(inputName);
            iss >> camid;

            if (!capture.open(camid))
            {
                cout << "Can't open source" << endl;
                return help(), -1;
            }
        }
    }

    namedWindow("result", 1);

    Mat frame, frame_cpu, gray_cpu, resized_cpu, faces_downloaded, frameDisp;
    vector<Rect> facesBuf_cpu;

    GpuMat frame_gpu, gray_gpu, resized_gpu, facesBuf_gpu;

    /* parameters */
    bool useGPU = true;
    double scaleFactor = 1.0;
    bool findLargestObject = false;
    bool filterRects = true;
    bool helpScreen = false;

    int detections_num;
    for (;;)
    {
        if (capture.isOpened())
        {
            capture >> frame;
            if (frame.empty())
            {
                break;
            }
        }

        (image.empty() ? frame : image).copyTo(frame_cpu);
        frame_gpu.upload(image.empty() ? frame : image);

        convertAndResize(frame_gpu, gray_gpu, resized_gpu, scaleFactor);
        convertAndResize(frame_cpu, gray_cpu, resized_cpu, scaleFactor);

        TickMeter tm;
        tm.start();

        if (useGPU)
        {
            cascade_gpu.visualizeInPlace = true;
            cascade_gpu.findLargestObject = findLargestObject;

            detections_num = cascade_gpu.detectMultiScale(resized_gpu, facesBuf_gpu, 1.2,
                                                          (filterRects || findLargestObject) ? 4 : 0);
            facesBuf_gpu.colRange(0, detections_num).download(faces_downloaded);
        }
        else
        {
            Size minSize = cascade_gpu.getClassifierSize();
            cascade_cpu.detectMultiScale(resized_cpu, facesBuf_cpu, 1.2,
                                         (filterRects || findLargestObject) ? 4 : 0,
                                         (findLargestObject ? CV_HAAR_FIND_BIGGEST_OBJECT : 0)
                                            | CV_HAAR_SCALE_IMAGE,
                                         minSize);
            detections_num = (int)facesBuf_cpu.size();
        }

        if (!useGPU && detections_num)
        {
            for (int i = 0; i < detections_num; ++i)
            {
                rectangle(resized_cpu, facesBuf_cpu[i], Scalar(255));
            }
        }

        if (useGPU)
        {
            resized_gpu.download(resized_cpu);
        }

        tm.stop();
        double detectionTime = tm.getTimeMilli();
        double fps = 1000 / detectionTime;

        //print detections to console
        cout << setfill(' ') << setprecision(2);
        cout << setw(6) << fixed << fps << " FPS, " << detections_num << " det";
        if ((filterRects || findLargestObject) && detections_num > 0)
        {
            Rect *faceRects = useGPU ? faces_downloaded.ptr<Rect>() : &facesBuf_cpu[0];
            for (int i = 0; i < min(detections_num, 2); ++i)
            {
                cout << ", [" << setw(4) << faceRects[i].x
                     << ", " << setw(4) << faceRects[i].y
                     << ", " << setw(4) << faceRects[i].width
                     << ", " << setw(4) << faceRects[i].height << "]";
            }
        }
        cout << endl;

        cvtColor(resized_cpu, frameDisp, CV_GRAY2BGR);
        displayState(frameDisp, helpScreen, useGPU, findLargestObject, filterRects, fps);
        imshow("result", frameDisp);

        int key = waitKey(5);
        if (key == 27)
        {
            break;
        }

        switch ((char)key)
        {
        case ' ':
            useGPU = !useGPU;
            break;
        case 'm':
        case 'M':
            findLargestObject = !findLargestObject;
            break;
        case 'f':
        case 'F':
            filterRects = !filterRects;
            break;
        case '1':
            scaleFactor *= 1.05;
            break;
        case 'q':
        case 'Q':
            scaleFactor /= 1.05;
            break;
        case 'h':
        case 'H':
            helpScreen = !helpScreen;
            break;
        }
    }

    return 0;
}

#endif //!defined(HAVE_CUDA)
<commit_msg>compilation for macos<commit_after>// WARNING: this sample is under construction! Use it on your own risk.
#if defined _MSC_VER && _MSC_VER >= 1400
#pragma warning(disable : 4100)
#endif

#include "cvconfig.h"
#include <iostream>
#include <iomanip>
#include "opencv2/contrib/contrib.hpp"
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/gpu/gpu.hpp"

using namespace std;
using namespace cv;
using namespace cv::gpu;

#if !defined(HAVE_CUDA)
int main(int argc, const char **argv)
{
    cout << "Please compile the library with CUDA support" << endl;
    return -1;
}
#else

void help()
{
    cout << "Usage: ./cascadeclassifier <cascade_file> <image_or_video_or_cameraid>\n"
            "Using OpenCV version " << CV_VERSION << endl << endl;
}

template<class T>
void convertAndResize(const T& src, T& gray, T& resized, double scale)
{
    if (src.channels() == 3)
    {
        cvtColor( src, gray, CV_BGR2GRAY );
    }
    else
    {
        gray = src;
    }

    Size sz(cvRound(gray.cols * scale), cvRound(gray.rows * scale));

    if (scale != 1)
    {
        resize(gray, resized, sz);
    }
    else
    {
        resized = gray;
    }
}

void matPrint(Mat &img, int lineOffsY, Scalar fontColor, const ostringstream &ss)
{
    int fontFace = FONT_HERSHEY_DUPLEX;
    double fontScale = 0.8;
    int fontThickness = 2;
    Size fontSize = cv::getTextSize("T[]", fontFace, fontScale, fontThickness, 0);

    Point org;
    org.x = 1;
    org.y = 3 * fontSize.height * (lineOffsY + 1) / 2;
    putText(img, ss.str(), org, fontFace, fontScale, CV_RGB(0,0,0), 5*fontThickness/2, 16);
    putText(img, ss.str(), org, fontFace, fontScale, fontColor, fontThickness, 16);
}

void displayState(Mat &canvas, bool bHelp, bool bGpu, bool bLargestFace, bool bFilter, double fps)
{
    Scalar fontColorRed = CV_RGB(255,0,0);
    Scalar fontColorNV  = CV_RGB(118,185,0);

    ostringstream ss;
    ss << "FPS = " << setprecision(1) << fixed << fps;
    matPrint(canvas, 0, fontColorRed, ss);
    ss.str("");
    ss << "[" << canvas.cols << "x" << canvas.rows << "], " <<
        (bGpu ? "GPU, " : "CPU, ") <<
        (bLargestFace ? "OneFace, " : "MultiFace, ") <<
        (bFilter ? "Filter:ON" : "Filter:OFF");
    matPrint(canvas, 1, fontColorRed, ss);

    if (bHelp)
    {
        // by Anatoly. MacOS fix. ostringstream(const string&) is a private
        //matPrint(canvas, 2, fontColorNV, ostringstream("Space - switch GPU / CPU"));
        matPrint(canvas, 2, fontColorNV, (ostringstream&)(ostringstream() << "Space - switch GPU / CPU"));
        matPrint(canvas, 3, fontColorNV, (ostringstream&)(ostringstream() << "M - switch OneFace / MultiFace"));
        matPrint(canvas, 4, fontColorNV, (ostringstream&)(ostringstream() << "F - toggle rectangles Filter"));
        matPrint(canvas, 5, fontColorNV, (ostringstream&)(ostringstream() << "H - toggle hotkeys help"));
        matPrint(canvas, 6, fontColorNV, (ostringstream&)(ostringstream() << "1/Q - increase/decrease scale"));
    }
    else
    {
        matPrint(canvas, 2, fontColorNV, (ostringstream&)(ostringstream() << "H - toggle hotkeys help"));
    }
}

int main(int argc, const char *argv[])
{
    if (argc != 3)
    {
        return help(), -1;
    }

    if (getCudaEnabledDeviceCount() == 0)
    {
        return cerr << "No GPU found or the library is compiled without GPU support" << endl, -1;
    }

    VideoCapture capture;

    string cascadeName = argv[1];
    string inputName = argv[2];

    CascadeClassifier_GPU cascade_gpu;
    if (!cascade_gpu.load(cascadeName))
    {
        return cerr << "ERROR: Could not load cascade classifier \"" << cascadeName << "\"" << endl, help(), -1;
    }

    CascadeClassifier cascade_cpu;
    if (!cascade_cpu.load(cascadeName))
    {
        return cerr << "ERROR: Could not load cascade classifier \"" << cascadeName << "\"" << endl, help(), -1;
    }

    Mat image = imread(inputName);

    if (image.empty())
    {
        if (!capture.open(inputName))
        {
            int camid = -1;
            istringstream iss(inputName);
            iss >> camid;

            if (!capture.open(camid))
            {
                cout << "Can't open source" << endl;
                return help(), -1;
            }
        }
    }

    namedWindow("result", 1);

    Mat frame, frame_cpu, gray_cpu, resized_cpu, faces_downloaded, frameDisp;
    vector<Rect> facesBuf_cpu;

    GpuMat frame_gpu, gray_gpu, resized_gpu, facesBuf_gpu;

    /* parameters */
    bool useGPU = true;
    double scaleFactor = 1.0;
    bool findLargestObject = false;
    bool filterRects = true;
    bool helpScreen = false;

    int detections_num;
    for (;;)
    {
        if (capture.isOpened())
        {
            capture >> frame;
            if (frame.empty())
            {
                break;
            }
        }

        (image.empty() ? frame : image).copyTo(frame_cpu);
        frame_gpu.upload(image.empty() ? frame : image);

        convertAndResize(frame_gpu, gray_gpu, resized_gpu, scaleFactor);
        convertAndResize(frame_cpu, gray_cpu, resized_cpu, scaleFactor);

        TickMeter tm;
        tm.start();

        if (useGPU)
        {
            cascade_gpu.visualizeInPlace = true;
            cascade_gpu.findLargestObject = findLargestObject;

            detections_num = cascade_gpu.detectMultiScale(resized_gpu, facesBuf_gpu, 1.2,
                                                          (filterRects || findLargestObject) ? 4 : 0);
            facesBuf_gpu.colRange(0, detections_num).download(faces_downloaded);
        }
        else
        {
            Size minSize = cascade_gpu.getClassifierSize();
            cascade_cpu.detectMultiScale(resized_cpu, facesBuf_cpu, 1.2,
                                         (filterRects || findLargestObject) ? 4 : 0,
                                         (findLargestObject ? CV_HAAR_FIND_BIGGEST_OBJECT : 0)
                                            | CV_HAAR_SCALE_IMAGE,
                                         minSize);
            detections_num = (int)facesBuf_cpu.size();
        }

        if (!useGPU && detections_num)
        {
            for (int i = 0; i < detections_num; ++i)
            {
                rectangle(resized_cpu, facesBuf_cpu[i], Scalar(255));
            }
        }

        if (useGPU)
        {
            resized_gpu.download(resized_cpu);
        }

        tm.stop();
        double detectionTime = tm.getTimeMilli();
        double fps = 1000 / detectionTime;

        //print detections to console
        cout << setfill(' ') << setprecision(2);
        cout << setw(6) << fixed << fps << " FPS, " << detections_num << " det";
        if ((filterRects || findLargestObject) && detections_num > 0)
        {
            Rect *faceRects = useGPU ? faces_downloaded.ptr<Rect>() : &facesBuf_cpu[0];
            for (int i = 0; i < min(detections_num, 2); ++i)
            {
                cout << ", [" << setw(4) << faceRects[i].x
                     << ", " << setw(4) << faceRects[i].y
                     << ", " << setw(4) << faceRects[i].width
                     << ", " << setw(4) << faceRects[i].height << "]";
            }
        }
        cout << endl;

        cvtColor(resized_cpu, frameDisp, CV_GRAY2BGR);
        displayState(frameDisp, helpScreen, useGPU, findLargestObject, filterRects, fps);
        imshow("result", frameDisp);

        int key = waitKey(5);
        if (key == 27)
        {
            break;
        }

        switch ((char)key)
        {
        case ' ':
            useGPU = !useGPU;
            break;
        case 'm':
        case 'M':
            findLargestObject = !findLargestObject;
            break;
        case 'f':
        case 'F':
            filterRects = !filterRects;
            break;
        case '1':
            scaleFactor *= 1.05;
            break;
        case 'q':
        case 'Q':
            scaleFactor /= 1.05;
            break;
        case 'h':
        case 'H':
            helpScreen = !helpScreen;
            break;
        }
    }

    return 0;
}

#endif //!defined(HAVE_CUDA)
<|endoftext|>


<commit_before>// Copyright (c) 2009 - Decho Corp.

#include "mordor/common/http/parser.h"
#include "mordor/test/test.h"

// Simplest success case
TEST_WITH_SUITE(HTTP, simpleRequest)
{
    HTTP::Request request;
    HTTP::RequestParser parser(request);

    parser.run("GET / HTTP/1.0\r\n\r\n");
    TEST_ASSERT(!parser.error());
    TEST_ASSERT(parser.complete());
    TEST_ASSERT_EQUAL(request.requestLine.method, HTTP::GET);
    TEST_ASSERT_EQUAL(request.requestLine.uri, URI("/"));
    TEST_ASSERT_EQUAL(request.requestLine.ver, HTTP::Version(1, 0));
}

TEST_WITH_SUITE(HTTP, emptyRequest)
{
    HTTP::Request request;
    HTTP::RequestParser parser(request);

    parser.run("");
    TEST_ASSERT(!parser.error());
    TEST_ASSERT(!parser.complete());
}

TEST_WITH_SUITE(HTTP, garbageRequest)
{
    HTTP::Request request;
    HTTP::RequestParser parser(request);

    parser.run("#*((@Nflk:J");
    TEST_ASSERT(parser.error());
    TEST_ASSERT(!parser.complete());
}

TEST_WITH_SUITE(HTTP, missingNewlineRequest)
{
    HTTP::Request request;
    HTTP::RequestParser parser(request);

    parser.run("GET / HTTP/1.0\r\n");
    TEST_ASSERT(!parser.error());
    TEST_ASSERT(!parser.complete());
    // Even though it's not complete, we should have parsed as much as was there
    TEST_ASSERT_EQUAL(request.requestLine.method, HTTP::GET);
    TEST_ASSERT_EQUAL(request.requestLine.uri, URI("/"));
    TEST_ASSERT_EQUAL(request.requestLine.ver, HTTP::Version(1, 0));
}

TEST_WITH_SUITE(HTTP, requestWithSimpleHeader)
{
    HTTP::Request request;
    HTTP::RequestParser parser(request);

    parser.run("GET / HTTP/1.0\r\n"
               "Connection: close\r\n"
               "\r\n");
    TEST_ASSERT(!parser.error());
    TEST_ASSERT(parser.complete());
    TEST_ASSERT_EQUAL(request.requestLine.method, HTTP::GET);
    TEST_ASSERT_EQUAL(request.requestLine.uri, URI("/"));
    TEST_ASSERT_EQUAL(request.requestLine.ver, HTTP::Version(1, 0));
    TEST_ASSERT_EQUAL(request.general.connection.size(), 1);
    TEST_ASSERT(request.general.connection.find("close")
        != request.general.connection.end());
}

TEST_WITH_SUITE(HTTP, requestWithComplexHeader)
{
    HTTP::Request request;
    HTTP::RequestParser parser(request);

    parser.run("GET / HTTP/1.0\r\n"
               "Connection:\r\n"
               " keep-alive,  keep-alive,\r\n"
               "\t close\r\n"
               "\r\n");
    TEST_ASSERT(!parser.error());
    TEST_ASSERT(parser.complete());
    TEST_ASSERT_EQUAL(request.requestLine.method, HTTP::GET);
    TEST_ASSERT_EQUAL(request.requestLine.uri, URI("/"));
    TEST_ASSERT_EQUAL(request.requestLine.ver, HTTP::Version(1, 0));
    TEST_ASSERT_EQUAL(request.general.connection.size(), 2);
    TEST_ASSERT(request.general.connection.find("close")
        != request.general.connection.end());
    TEST_ASSERT(request.general.connection.find("keep-alive")
        != request.general.connection.end());
}

TEST_WITH_SUITE(HTTP, rangeHeader)
{
    HTTP::Request request;
    HTTP::RequestParser parser(request);

    parser.run("GET / HTTP/1.1\r\n"
               "Range: bytes=0-499, 500-999, -500, 9500-, 0-0,-1\r\n"
               " ,500-600\r\n"
               "\r\n");
    TEST_ASSERT(!parser.error());
    TEST_ASSERT(parser.complete());
    TEST_ASSERT_EQUAL(request.requestLine.method, HTTP::GET);
    TEST_ASSERT_EQUAL(request.requestLine.uri, URI("/"));
    TEST_ASSERT_EQUAL(request.requestLine.ver, HTTP::Version(1, 1));
    TEST_ASSERT_EQUAL(request.request.range.size(), 7);
    HTTP::RangeSet::const_iterator it = request.request.range.begin();
    TEST_ASSERT_EQUAL(it->first, 0);
    TEST_ASSERT_EQUAL(it->second, 499);
    ++it;
    TEST_ASSERT_EQUAL(it->first, 500);
    TEST_ASSERT_EQUAL(it->second, 999);
    ++it;
    TEST_ASSERT_EQUAL(it->first, ~0ull);
    TEST_ASSERT_EQUAL(it->second, 500);
    ++it;
    TEST_ASSERT_EQUAL(it->first, 9500);
    TEST_ASSERT_EQUAL(it->second, ~0ull);
    ++it;
    TEST_ASSERT_EQUAL(it->first, 0);
    TEST_ASSERT_EQUAL(it->second, 0);
    ++it;
    TEST_ASSERT_EQUAL(it->first, ~0ull);
    TEST_ASSERT_EQUAL(it->second, 1);
    ++it;
    TEST_ASSERT_EQUAL(it->first, 500);
    TEST_ASSERT_EQUAL(it->second, 600);
}

TEST_WITH_SUITE(HTTP, versionComparison)
{
    HTTP::Version ver10(1, 0), ver11(1, 1);
    TEST_ASSERT(ver10 == ver10);
    TEST_ASSERT(ver11 == ver11);
    TEST_ASSERT(ver10 != ver11);
    TEST_ASSERT(ver10 <= ver11);
    TEST_ASSERT(ver10 < ver11);
    TEST_ASSERT(ver11 >= ver10);
    TEST_ASSERT(ver11 > ver10);
    TEST_ASSERT(ver10 <= ver10);
    TEST_ASSERT(ver10 >= ver10);
}

TEST_WITH_SUITE(HTTP, quoting)
{
    TEST_ASSERT_EQUAL(HTTP::quote(""), "\"\"");
    TEST_ASSERT_EQUAL(HTTP::quote("token"), "token");
    TEST_ASSERT_EQUAL(HTTP::quote("multiple words"), "\"multiple words\"");
    TEST_ASSERT_EQUAL(HTTP::quote("\tlotsa  whitespace\t"),
        "\"\tlotsa  whitespace\t\"");
    TEST_ASSERT_EQUAL(HTTP::quote("\""), "\"\\\"\"");
    TEST_ASSERT_EQUAL(HTTP::quote("\\"), "\"\\\\\"");
    TEST_ASSERT_EQUAL(HTTP::quote("weird < chars >"), "\"weird < chars >\"");
    TEST_ASSERT_EQUAL(HTTP::quote("multiple\\ escape\" sequences\\  "),
        "\"multiple\\\\ escape\\\" sequences\\\\  \"");
    TEST_ASSERT_EQUAL(HTTP::quote("tom"), "tom");
    TEST_ASSERT_EQUAL(HTTP::quote("\""), "\"\\\"\"");
    TEST_ASSERT_EQUAL(HTTP::quote("co\\dy"), "\"co\\\\dy\"");
}
<commit_msg>Appease GCC.<commit_after>// Copyright (c) 2009 - Decho Corp.

#include "mordor/common/http/parser.h"
#include "mordor/test/test.h"

// Simplest success case
TEST_WITH_SUITE(HTTP, simpleRequest)
{
    HTTP::Request request;
    HTTP::RequestParser parser(request);

    parser.run("GET / HTTP/1.0\r\n\r\n");
    TEST_ASSERT(!parser.error());
    TEST_ASSERT(parser.complete());
    TEST_ASSERT_EQUAL(request.requestLine.method, HTTP::GET);
    TEST_ASSERT_EQUAL(request.requestLine.uri, URI("/"));
    TEST_ASSERT_EQUAL(request.requestLine.ver, HTTP::Version(1, 0));
}

TEST_WITH_SUITE(HTTP, emptyRequest)
{
    HTTP::Request request;
    HTTP::RequestParser parser(request);

    parser.run("");
    TEST_ASSERT(!parser.error());
    TEST_ASSERT(!parser.complete());
}

TEST_WITH_SUITE(HTTP, garbageRequest)
{
    HTTP::Request request;
    HTTP::RequestParser parser(request);

    parser.run("#*((@Nflk:J");
    TEST_ASSERT(parser.error());
    TEST_ASSERT(!parser.complete());
}

TEST_WITH_SUITE(HTTP, missingNewlineRequest)
{
    HTTP::Request request;
    HTTP::RequestParser parser(request);

    parser.run("GET / HTTP/1.0\r\n");
    TEST_ASSERT(!parser.error());
    TEST_ASSERT(!parser.complete());
    // Even though it's not complete, we should have parsed as much as was there
    TEST_ASSERT_EQUAL(request.requestLine.method, HTTP::GET);
    TEST_ASSERT_EQUAL(request.requestLine.uri, URI("/"));
    TEST_ASSERT_EQUAL(request.requestLine.ver, HTTP::Version(1, 0));
}

TEST_WITH_SUITE(HTTP, requestWithSimpleHeader)
{
    HTTP::Request request;
    HTTP::RequestParser parser(request);

    parser.run("GET / HTTP/1.0\r\n"
               "Connection: close\r\n"
               "\r\n");
    TEST_ASSERT(!parser.error());
    TEST_ASSERT(parser.complete());
    TEST_ASSERT_EQUAL(request.requestLine.method, HTTP::GET);
    TEST_ASSERT_EQUAL(request.requestLine.uri, URI("/"));
    TEST_ASSERT_EQUAL(request.requestLine.ver, HTTP::Version(1, 0));
    TEST_ASSERT_EQUAL(request.general.connection.size(), 1u);
    TEST_ASSERT(request.general.connection.find("close")
        != request.general.connection.end());
}

TEST_WITH_SUITE(HTTP, requestWithComplexHeader)
{
    HTTP::Request request;
    HTTP::RequestParser parser(request);

    parser.run("GET / HTTP/1.0\r\n"
               "Connection:\r\n"
               " keep-alive,  keep-alive,\r\n"
               "\t close\r\n"
               "\r\n");
    TEST_ASSERT(!parser.error());
    TEST_ASSERT(parser.complete());
    TEST_ASSERT_EQUAL(request.requestLine.method, HTTP::GET);
    TEST_ASSERT_EQUAL(request.requestLine.uri, URI("/"));
    TEST_ASSERT_EQUAL(request.requestLine.ver, HTTP::Version(1, 0));
    TEST_ASSERT_EQUAL(request.general.connection.size(), 2u);
    TEST_ASSERT(request.general.connection.find("close")
        != request.general.connection.end());
    TEST_ASSERT(request.general.connection.find("keep-alive")
        != request.general.connection.end());
}

TEST_WITH_SUITE(HTTP, rangeHeader)
{
    HTTP::Request request;
    HTTP::RequestParser parser(request);

    parser.run("GET / HTTP/1.1\r\n"
               "Range: bytes=0-499, 500-999, -500, 9500-, 0-0,-1\r\n"
               " ,500-600\r\n"
               "\r\n");
    TEST_ASSERT(!parser.error());
    TEST_ASSERT(parser.complete());
    TEST_ASSERT_EQUAL(request.requestLine.method, HTTP::GET);
    TEST_ASSERT_EQUAL(request.requestLine.uri, URI("/"));
    TEST_ASSERT_EQUAL(request.requestLine.ver, HTTP::Version(1, 1));
    TEST_ASSERT_EQUAL(request.request.range.size(), 7u);
    HTTP::RangeSet::const_iterator it = request.request.range.begin();
    TEST_ASSERT_EQUAL(it->first, 0u);
    TEST_ASSERT_EQUAL(it->second, 499u);
    ++it;
    TEST_ASSERT_EQUAL(it->first, 500u);
    TEST_ASSERT_EQUAL(it->second, 999u);
    ++it;
    TEST_ASSERT_EQUAL(it->first, ~0ull);
    TEST_ASSERT_EQUAL(it->second, 500u);
    ++it;
    TEST_ASSERT_EQUAL(it->first, 9500u);
    TEST_ASSERT_EQUAL(it->second, ~0ull);
    ++it;
    TEST_ASSERT_EQUAL(it->first, 0u);
    TEST_ASSERT_EQUAL(it->second, 0u);
    ++it;
    TEST_ASSERT_EQUAL(it->first, ~0ull);
    TEST_ASSERT_EQUAL(it->second, 1u);
    ++it;
    TEST_ASSERT_EQUAL(it->first, 500u);
    TEST_ASSERT_EQUAL(it->second, 600u);
}

TEST_WITH_SUITE(HTTP, versionComparison)
{
    HTTP::Version ver10(1, 0), ver11(1, 1);
    TEST_ASSERT(ver10 == ver10);
    TEST_ASSERT(ver11 == ver11);
    TEST_ASSERT(ver10 != ver11);
    TEST_ASSERT(ver10 <= ver11);
    TEST_ASSERT(ver10 < ver11);
    TEST_ASSERT(ver11 >= ver10);
    TEST_ASSERT(ver11 > ver10);
    TEST_ASSERT(ver10 <= ver10);
    TEST_ASSERT(ver10 >= ver10);
}

TEST_WITH_SUITE(HTTP, quoting)
{
    TEST_ASSERT_EQUAL(HTTP::quote(""), "\"\"");
    TEST_ASSERT_EQUAL(HTTP::quote("token"), "token");
    TEST_ASSERT_EQUAL(HTTP::quote("multiple words"), "\"multiple words\"");
    TEST_ASSERT_EQUAL(HTTP::quote("\tlotsa  whitespace\t"),
        "\"\tlotsa  whitespace\t\"");
    TEST_ASSERT_EQUAL(HTTP::quote("\""), "\"\\\"\"");
    TEST_ASSERT_EQUAL(HTTP::quote("\\"), "\"\\\\\"");
    TEST_ASSERT_EQUAL(HTTP::quote("weird < chars >"), "\"weird < chars >\"");
    TEST_ASSERT_EQUAL(HTTP::quote("multiple\\ escape\" sequences\\  "),
        "\"multiple\\\\ escape\\\" sequences\\\\  \"");
    TEST_ASSERT_EQUAL(HTTP::quote("tom"), "tom");
    TEST_ASSERT_EQUAL(HTTP::quote("\""), "\"\\\"\"");
    TEST_ASSERT_EQUAL(HTTP::quote("co\\dy"), "\"co\\\\dy\"");
}
<|endoftext|>