<commit_before>#include <caffe/caffe.hpp>
#ifdef USE_OPENCV
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#endif  // USE_OPENCV
#include <algorithm>
#include <iosfwd>
#include <memory>
#include <string>
#include <utility>
#include <vector>

#ifdef USE_OPENCV
using namespace caffe;  // NOLINT(build/namespaces)
using std::string;

/* Pair (label, confidence) representing a prediction. */
typedef std::pair<string, float> Prediction;

class Classifier {
 public:
  Classifier(const string& model_file,
             const string& trained_file,
             const string& mean_file,
             const string& label_file);

  std::vector<Prediction> Classify(const cv::Mat& img, int N = 5);

 private:
  void SetMean(const string& mean_file);

  std::vector<float> Predict(const cv::Mat& img);

  void WrapInputLayer(std::vector<cv::Mat>* input_channels);

  void Preprocess(const cv::Mat& img,
                  std::vector<cv::Mat>* input_channels);

 private:
  shared_ptr<Net<float> > net_;
  cv::Size input_geometry_;
  int num_channels_;
  cv::Mat mean_;
  std::vector<string> labels_;
};

Classifier::Classifier(const string& model_file,
                       const string& trained_file,
                       const string& mean_file,
                       const string& label_file) {
#ifdef CPU_ONLY
  Caffe::set_mode(Caffe::CPU);
#else
  Caffe::set_mode(Caffe::GPU);
#endif

  /* Load the network. */
  net_.reset(new Net<float>(model_file, TEST));
  net_->CopyTrainedLayersFrom(trained_file);

  CHECK_EQ(net_->num_inputs(), 1) << "Network should have exactly one input.";
  CHECK_EQ(net_->num_outputs(), 1) << "Network should have exactly one output.";

  Blob<float>* input_layer = net_->input_blobs()[0];
  num_channels_ = input_layer->channels();
  CHECK(num_channels_ == 3 || num_channels_ == 1)
    << "Input layer should have 1 or 3 channels.";
  input_geometry_ = cv::Size(input_layer->width(), input_layer->height());

  /* Load the binaryproto mean file. */
  SetMean(mean_file);

  /* Load labels. */
  std::ifstream labels(label_file.c_str());
  CHECK(labels) << "Unable to open labels file " << label_file;
  string line;
  while (std::getline(labels, line))
    labels_.push_back(string(line));

  Blob<float>* output_layer = net_->output_blobs()[0];
  CHECK_EQ(labels_.size(), output_layer->channels())
    << "Number of labels is different from the output layer dimension.";
}

static bool PairCompare(const std::pair<float, int>& lhs,
                        const std::pair<float, int>& rhs) {
  return lhs.first > rhs.first;
}

/* Return the indices of the top N values of vector v. */
static std::vector<int> Argmax(const std::vector<float>& v, int N) {
  std::vector<std::pair<float, int> > pairs;
  for (size_t i = 0; i < v.size(); ++i)
    pairs.push_back(std::make_pair(v[i], i));
  std::partial_sort(pairs.begin(), pairs.begin() + N, pairs.end(), PairCompare);

  std::vector<int> result;
  for (int i = 0; i < N; ++i)
    result.push_back(pairs[i].second);
  return result;
}

/* Return the top N predictions. */
std::vector<Prediction> Classifier::Classify(const cv::Mat& img, int N) {
  std::vector<float> output = Predict(img);

  N = std::min<int>(labels_.size(), N);
  std::vector<int> maxN = Argmax(output, N);
  std::vector<Prediction> predictions;
  for (int i = 0; i < N; ++i) {
    int idx = maxN[i];
    predictions.push_back(std::make_pair(labels_[idx], output[idx]));
  }

  return predictions;
}

/* Load the mean file in binaryproto format. */
void Classifier::SetMean(const string& mean_file) {
  BlobProto blob_proto;
  ReadProtoFromBinaryFileOrDie(mean_file.c_str(), &blob_proto);

  /* Convert from BlobProto to Blob<float> */
  Blob<float> mean_blob;
  mean_blob.FromProto(blob_proto);
  CHECK_EQ(mean_blob.channels(), num_channels_)
    << "Number of channels of mean file doesn't match input layer.";

  /* The format of the mean file is planar 32-bit float BGR or grayscale. */
  std::vector<cv::Mat> channels;
  float* data = mean_blob.mutable_cpu_data();
  for (int i = 0; i < num_channels_; ++i) {
    /* Extract an individual channel. */
    cv::Mat channel(mean_blob.height(), mean_blob.width(), CV_32FC1, data);
    channels.push_back(channel);
    data += mean_blob.height() * mean_blob.width();
  }

  /* Merge the separate channels into a single image. */
  cv::Mat mean;
  cv::merge(channels, mean);

  /* Compute the global mean pixel value and create a mean image
   * filled with this value. */
  cv::Scalar channel_mean = cv::mean(mean);
  mean_ = cv::Mat(input_geometry_, mean.type(), channel_mean);
}

std::vector<float> Classifier::Predict(const cv::Mat& img) {
  Blob<float>* input_layer = net_->input_blobs()[0];
  input_layer->Reshape(1, num_channels_,
                       input_geometry_.height, input_geometry_.width);
  /* Forward dimension change to all layers. */
  net_->Reshape();

  std::vector<cv::Mat> input_channels;
  WrapInputLayer(&input_channels);

  Preprocess(img, &input_channels);

  net_->Forward();

  /* Copy the output layer to a std::vector */
  Blob<float>* output_layer = net_->output_blobs()[0];
  const float* begin = output_layer->cpu_data();
  const float* end = begin + output_layer->channels();
  return std::vector<float>(begin, end);
}

/* Wrap the input layer of the network in separate cv::Mat objects
 * (one per channel). This way we save one memcpy operation and we
 * don't need to rely on cudaMemcpy2D. The last preprocessing
 * operation will write the separate channels directly to the input
 * layer. */
void Classifier::WrapInputLayer(std::vector<cv::Mat>* input_channels) {
  Blob<float>* input_layer = net_->input_blobs()[0];

  int width = input_layer->width();
  int height = input_layer->height();
  float* input_data = input_layer->mutable_cpu_data();
  for (int i = 0; i < input_layer->channels(); ++i) {
    cv::Mat channel(height, width, CV_32FC1, input_data);
    input_channels->push_back(channel);
    input_data += width * height;
  }
}

void Classifier::Preprocess(const cv::Mat& img,
                            std::vector<cv::Mat>* input_channels) {
  /* Convert the input image to the input image format of the network. */
  cv::Mat sample;
  if (img.channels() == 3 && num_channels_ == 1)
    cv::cvtColor(img, sample, cv::COLOR_BGR2GRAY);
  else if (img.channels() == 4 && num_channels_ == 1)
    cv::cvtColor(img, sample, cv::COLOR_BGRA2GRAY);
  else if (img.channels() == 4 && num_channels_ == 3)
    cv::cvtColor(img, sample, cv::COLOR_BGRA2BGR);
  else if (img.channels() == 1 && num_channels_ == 3)
    cv::cvtColor(img, sample, cv::COLOR_GRAY2BGR);
  else
    sample = img;

  cv::Mat sample_resized;
  if (sample.size() != input_geometry_)
    cv::resize(sample, sample_resized, input_geometry_);
  else
    sample_resized = sample;

  cv::Mat sample_float;
  if (num_channels_ == 3)
    sample_resized.convertTo(sample_float, CV_32FC3);
  else
    sample_resized.convertTo(sample_float, CV_32FC1);

  cv::Mat sample_normalized;
  cv::subtract(sample_float, mean_, sample_normalized);

  /* This operation will write the separate BGR planes directly to the
   * input layer of the network because it is wrapped by the cv::Mat
   * objects in input_channels. */
  cv::split(sample_normalized, *input_channels);

  CHECK(reinterpret_cast<float*>(input_channels->at(0).data)
        == net_->input_blobs()[0]->cpu_data())
    << "Input channels are not wrapping the input layer of the network.";
}

int main(int argc, char** argv) {
  if (argc != 6) {
    std::cerr << "Usage: " << argv[0]
              << " deploy.prototxt network.caffemodel"
              << " mean.binaryproto labels.txt img.jpg" << std::endl;
    return 1;
  }

  ::google::InitGoogleLogging(argv[0]);

  string model_file   = argv[1];
  string trained_file = argv[2];
  string mean_file    = argv[3];
  string label_file   = argv[4];
  Classifier classifier(model_file, trained_file, mean_file, label_file);

  string file = argv[5];

  std::cout << "---------- Prediction for "
            << file << " ----------" << std::endl;

  cv::Mat img = cv::imread(file, -1);
  CHECK(!img.empty()) << "Unable to decode image " << file;
  std::vector<Prediction> predictions = classifier.Classify(img);

  /* Print the top N predictions. */
  for (size_t i = 0; i < predictions.size(); ++i) {
    Prediction p = predictions[i];
    std::cout << std::fixed << std::setprecision(4) << p.second << " - \""
              << p.first << "\"" << std::endl;
  }
}
#else
int main(int argc, char** argv) {
  LOG(FATAL) << "This example requires OpenCV; compile with USE_OPENCV.";
}
#endif // USE_OPENCV
<commit_msg>caffe example update<commit_after>#include <caffe/caffe.hpp>
#ifdef USE_OPENCV
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#endif  // USE_OPENCV
#include <algorithm>
#include <iosfwd>
#include <memory>
#include <string>
#include <utility>
#include <vector>

#ifdef USE_OPENCV
using namespace caffe;  // NOLINT(build/namespaces)
using std::string;

/* Pair (label, confidence) representing a prediction. */
typedef std::pair<string, float> Prediction;

class Classifier {
 public:
  Classifier(const string& model_file,
             const string& trained_file,
             const string& mean_file,
             const string& label_file);

  std::vector<Prediction> Classify(const cv::Mat& img, int N = 5);

 private:
  void SetMean(const string& mean_file);

  std::vector<float> Predict(const cv::Mat& img);

  void WrapInputLayer(std::vector<cv::Mat>* input_channels);

  void Preprocess(const cv::Mat& img,
                  std::vector<cv::Mat>* input_channels);

 private:
  shared_ptr<Net<float> > net_;
  cv::Size input_geometry_;
  int num_channels_;
  cv::Mat mean_;
  std::vector<string> labels_;
};

Classifier::Classifier(const string& model_file,
                       const string& trained_file,
                       const string& mean_file,
                       const string& label_file) {
#ifdef CPU_ONLY
  Caffe::set_mode(Caffe::CPU);
#else
  Caffe::set_mode(Caffe::GPU);
#endif

  /* Load the network. */
  net_.reset(new Net<float>(model_file, TEST));
  net_->CopyTrainedLayersFrom(trained_file);

  CHECK_EQ(net_->num_inputs(), 1) << "Network should have exactly one input.";
  CHECK_EQ(net_->num_outputs(), 1) << "Network should have exactly one output.";

  Blob<float>* input_layer = net_->input_blobs()[0];
  num_channels_ = input_layer->channels();
  CHECK(num_channels_ == 3 || num_channels_ == 1)
    << "Input layer should have 1 or 3 channels.";
  input_geometry_ = cv::Size(input_layer->width(), input_layer->height());

  /* Load the binaryproto mean file. */
  SetMean(mean_file);

  /* Load labels. */
  std::ifstream labels(label_file.c_str());
  CHECK(labels) << "Unable to open labels file " << label_file;
  string line;
  while (std::getline(labels, line))
    labels_.push_back(string(line));

  Blob<float>* output_layer = net_->output_blobs()[0];
  CHECK_EQ(labels_.size(), output_layer->channels())
    << "Number of labels is different from the output layer dimension.";
}

static bool PairCompare(const std::pair<float, int>& lhs,
                        const std::pair<float, int>& rhs) {
  return lhs.first > rhs.first;
}

/* Return the indices of the top N values of vector v. */
static std::vector<int> Argmax(const std::vector<float>& v, int N) {
  std::vector<std::pair<float, int> > pairs;
  for (size_t i = 0; i < v.size(); ++i)
    pairs.push_back(std::make_pair(v[i], i));
  std::partial_sort(pairs.begin(), pairs.begin() + N, pairs.end(), PairCompare);

  std::vector<int> result;
  for (int i = 0; i < N; ++i)
    result.push_back(pairs[i].second);
  return result;
}

/* Return the top N predictions. */
std::vector<Prediction> Classifier::Classify(const cv::Mat& img, int N) {
  std::vector<float> output = Predict(img);

  N = std::min<int>(labels_.size(), N);
  std::vector<int> maxN = Argmax(output, N);
  std::vector<Prediction> predictions;
  for (int i = 0; i < N; ++i) {
    int idx = maxN[i];
    predictions.push_back(std::make_pair(labels_[idx], output[idx]));
  }

  return predictions;
}

/* Load the mean file in binaryproto format. */
void Classifier::SetMean(const string& mean_file) {
  BlobProto blob_proto;
  ReadProtoFromBinaryFileOrDie(mean_file.c_str(), &blob_proto);

  /* Convert from BlobProto to Blob<float> */
  Blob<float> mean_blob;
  mean_blob.FromProto(blob_proto);
  CHECK_EQ(mean_blob.channels(), num_channels_)
    << "Number of channels of mean file doesn't match input layer.";

  /* The format of the mean file is planar 32-bit float BGR or grayscale. */
  std::vector<cv::Mat> channels;
  float* data = mean_blob.mutable_cpu_data();
  for (int i = 0; i < num_channels_; ++i) {
    /* Extract an individual channel. */
    cv::Mat channel(mean_blob.height(), mean_blob.width(), CV_32FC1, data);
    channels.push_back(channel);
    data += mean_blob.height() * mean_blob.width();
  }

  /* Merge the separate channels into a single image. */
  cv::Mat mean;
  cv::merge(channels, mean);

  /* Compute the global mean pixel value and create a mean image
   * filled with this value. */
  cv::Scalar channel_mean = cv::mean(mean);
  mean_ = cv::Mat(input_geometry_, mean.type(), channel_mean);
}

std::vector<float> Classifier::Predict(const cv::Mat& img) {
  Blob<float>* input_layer = net_->input_blobs()[0];
  input_layer->Reshape(1, num_channels_,
                       input_geometry_.height, input_geometry_.width);
  /* Forward dimension change to all layers. */
  net_->Reshape();

  std::vector<cv::Mat> input_channels;
  WrapInputLayer(&input_channels);

  Preprocess(img, &input_channels);

  net_->ForwardPrefilled();

  /* Copy the output layer to a std::vector */
  Blob<float>* output_layer = net_->output_blobs()[0];
  const float* begin = output_layer->cpu_data();
  const float* end = begin + output_layer->channels();
  return std::vector<float>(begin, end);
}

/* Wrap the input layer of the network in separate cv::Mat objects
 * (one per channel). This way we save one memcpy operation and we
 * don't need to rely on cudaMemcpy2D. The last preprocessing
 * operation will write the separate channels directly to the input
 * layer. */
void Classifier::WrapInputLayer(std::vector<cv::Mat>* input_channels) {
  Blob<float>* input_layer = net_->input_blobs()[0];

  int width = input_layer->width();
  int height = input_layer->height();
  float* input_data = input_layer->mutable_cpu_data();
  for (int i = 0; i < input_layer->channels(); ++i) {
    cv::Mat channel(height, width, CV_32FC1, input_data);
    input_channels->push_back(channel);
    input_data += width * height;
  }
}

void Classifier::Preprocess(const cv::Mat& img,
                            std::vector<cv::Mat>* input_channels) {
  /* Convert the input image to the input image format of the network. */
  cv::Mat sample;
  if (img.channels() == 3 && num_channels_ == 1)
    cv::cvtColor(img, sample, cv::COLOR_BGR2GRAY);
  else if (img.channels() == 4 && num_channels_ == 1)
    cv::cvtColor(img, sample, cv::COLOR_BGRA2GRAY);
  else if (img.channels() == 4 && num_channels_ == 3)
    cv::cvtColor(img, sample, cv::COLOR_BGRA2BGR);
  else if (img.channels() == 1 && num_channels_ == 3)
    cv::cvtColor(img, sample, cv::COLOR_GRAY2BGR);
  else
    sample = img;

  cv::Mat sample_resized;
  if (sample.size() != input_geometry_)
    cv::resize(sample, sample_resized, input_geometry_);
  else
    sample_resized = sample;

  cv::Mat sample_float;
  if (num_channels_ == 3)
    sample_resized.convertTo(sample_float, CV_32FC3);
  else
    sample_resized.convertTo(sample_float, CV_32FC1);

  cv::Mat sample_normalized;
  cv::subtract(sample_float, mean_, sample_normalized);

  /* This operation will write the separate BGR planes directly to the
   * input layer of the network because it is wrapped by the cv::Mat
   * objects in input_channels. */
  cv::split(sample_normalized, *input_channels);

  CHECK(reinterpret_cast<float*>(input_channels->at(0).data)
        == net_->input_blobs()[0]->cpu_data())
    << "Input channels are not wrapping the input layer of the network.";
}

int main(int argc, char** argv) {
  if (argc != 6) {
    std::cerr << "Usage: " << argv[0]
              << " deploy.prototxt network.caffemodel"
              << " mean.binaryproto labels.txt img.jpg" << std::endl;
    return 1;
  }

  ::google::InitGoogleLogging(argv[0]);

  string model_file   = argv[1];
  string trained_file = argv[2];
  string mean_file    = argv[3];
  string label_file   = argv[4];
  Classifier classifier(model_file, trained_file, mean_file, label_file);

  string file = argv[5];

  std::cout << "---------- Prediction for "
            << file << " ----------" << std::endl;

  cv::Mat img = cv::imread(file, -1);
  CHECK(!img.empty()) << "Unable to decode image " << file;
  std::vector<Prediction> predictions = classifier.Classify(img);

  /* Print the top N predictions. */
  for (size_t i = 0; i < predictions.size(); ++i) {
    Prediction p = predictions[i];
    std::cout << std::fixed << std::setprecision(4) << p.second << " - \""
              << p.first << "\"" << std::endl;
  }
}
#else
int main(int argc, char** argv) {
  LOG(FATAL) << "This example requires OpenCV; compile with USE_OPENCV.";
}
#endif // USE_OPENCV
<|endoftext|>


<commit_before>#include <catch.hpp>
#include <rapidcheck-catch.h>

#include "rapidcheck/detail/ExpressionCaptor.h"

using namespace rc;
using namespace rc::detail;

namespace {

struct Box
{
    Box(int x) : value(x) {}
    int value;

    std::string str() const { return "[" + std::to_string(value) + "]"; }
};

void showValue(const Box &value, std::ostream &os)
{
    os << value.str();
}

} // namespace

namespace rc {

template<>
class Arbitrary<ExpressionCaptor> : public gen::Generator<ExpressionCaptor>
{
public:
    ExpressionCaptor generate() const override
    { return ExpressionCaptor(*gen::arbitrary<std::string>()); }
};

template<>
class Arbitrary<Box> : public gen::Generator<Box>
{
public:
    Box generate() const override { return Box(*gen::arbitrary<int>()); }
};

} // namespace rc

TEST_CASE("ExpressionCaptor") {
    SECTION("str") {
        prop("returns the current value",
             [] (const std::string &value) {
                 RC_ASSERT(ExpressionCaptor(value).str() == value);
             });
    }

    SECTION("operator->*") {
        prop("simply appends RHS",
             [](const ExpressionCaptor &captor, Box value) {
                 RC_ASSERT((std::move(captor) ->* value).str() ==
                           (captor.str() + value.str()));
            });
    }

#define TEST_BINARY_OPERATOR(op)                                        \
    SECTION("operator" op) {                                            \
        prop("joins LHS and RHS with operator string between",          \
             [](const ExpressionCaptor &captor, Box value) {            \
                 RC_ASSERT((std::move(captor) op value).str() ==        \
                           (captor.str() + " " #op " " + value.str())); \
             });                                                        \
    }

    TEST_BINARY_OPERATOR(*)
    TEST_BINARY_OPERATOR(/)
    TEST_BINARY_OPERATOR(%)

    TEST_BINARY_OPERATOR(+)
    TEST_BINARY_OPERATOR(-)

    TEST_BINARY_OPERATOR(<<)
    TEST_BINARY_OPERATOR(>>)

    TEST_BINARY_OPERATOR(<)
    TEST_BINARY_OPERATOR(>)
    TEST_BINARY_OPERATOR(>=)
    TEST_BINARY_OPERATOR(<=)

    TEST_BINARY_OPERATOR(==)
    TEST_BINARY_OPERATOR(!=)

    TEST_BINARY_OPERATOR(&)

    TEST_BINARY_OPERATOR(^)

    TEST_BINARY_OPERATOR(|)

    TEST_BINARY_OPERATOR(&&)

    TEST_BINARY_OPERATOR(||)

#undef TEST_BINARY_OPERATOR
}
<commit_msg>Fix compile error<commit_after>#include <catch.hpp>
#include <rapidcheck-catch.h>

#include "rapidcheck/detail/ExpressionCaptor.h"

using namespace rc;
using namespace rc::detail;

namespace {

struct Box
{
    Box(int x) : value(x) {}
    int value;

    std::string str() const { return "[" + std::to_string(value) + "]"; }
};

void showValue(const Box &value, std::ostream &os)
{
    os << value.str();
}

} // namespace

namespace rc {

template<>
class Arbitrary<ExpressionCaptor> : public gen::Generator<ExpressionCaptor>
{
public:
    ExpressionCaptor generate() const override
    { return ExpressionCaptor(*gen::arbitrary<std::string>()); }
};

template<>
class Arbitrary<Box> : public gen::Generator<Box>
{
public:
    Box generate() const override { return Box(*gen::arbitrary<int>()); }
};

} // namespace rc

TEST_CASE("ExpressionCaptor") {
    SECTION("str") {
        prop("returns the current value",
             [] (const std::string &value) {
                 RC_ASSERT(ExpressionCaptor(value).str() == value);
             });
    }

    SECTION("operator->*") {
        prop("simply appends RHS",
             [](const ExpressionCaptor &captor, Box value) {
                 RC_ASSERT((std::move(captor) ->* value).str() ==
                           (captor.str() + value.str()));
            });
    }

#define TEST_BINARY_OPERATOR(op)                                        \
    SECTION("operator" #op) {                                           \
        prop("joins LHS and RHS with operator string between",          \
             [](const ExpressionCaptor &captor, Box value) {            \
                 RC_ASSERT((std::move(captor) op value).str() ==        \
                           (captor.str() + " " #op " " + value.str())); \
             });                                                        \
    }

    TEST_BINARY_OPERATOR(*)
    TEST_BINARY_OPERATOR(/)
    TEST_BINARY_OPERATOR(%)

    TEST_BINARY_OPERATOR(+)
    TEST_BINARY_OPERATOR(-)

    TEST_BINARY_OPERATOR(<<)
    TEST_BINARY_OPERATOR(>>)

    TEST_BINARY_OPERATOR(<)
    TEST_BINARY_OPERATOR(>)
    TEST_BINARY_OPERATOR(>=)
    TEST_BINARY_OPERATOR(<=)

    TEST_BINARY_OPERATOR(==)
    TEST_BINARY_OPERATOR(!=)

    TEST_BINARY_OPERATOR(&)

    TEST_BINARY_OPERATOR(^)

    TEST_BINARY_OPERATOR(|)

    TEST_BINARY_OPERATOR(&&)

    TEST_BINARY_OPERATOR(||)

#undef TEST_BINARY_OPERATOR
}
<|endoftext|>


<commit_before>// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.

#include "TextureD3D11.h"
#include "core/Engine.h"
#include "RendererD3D11.h"
#include "utils/Log.h"

namespace ouzel
{
    namespace graphics
    {
        TextureD3D11::TextureD3D11()
        {
        }

        TextureD3D11::~TextureD3D11()
        {
            if (renderTargetView)
            {
                renderTargetView->Release();
            }

            if (resourceView)
            {
                resourceView->Release();
            }

            if (texture)
            {
                texture->Release();
            }

            if (samplerState)
            {
                samplerState->Release();
            }

            width = 0;
            height = 0;
        }

        bool TextureD3D11::upload()
        {
            std::lock_guard<std::mutex> lock(uploadMutex);

            if (dirty)
            {
                RendererD3D11* rendererD3D11 = static_cast<RendererD3D11*>(sharedEngine->getRenderer());

                if (dirty & DIRTY_DATA)
                {
                    if (size.v[0] > 0 &&
                        size.v[1] > 0)
                    {
                        if (!texture ||
                            static_cast<UINT>(size.v[0]) != width ||
                            static_cast<UINT>(size.v[1]) != height)
                        {
                            if (texture) texture->Release();

                            width = static_cast<UINT>(size.v[0]);
                            height = static_cast<UINT>(size.v[1]);

                            D3D11_TEXTURE2D_DESC textureDesc;
                            textureDesc.Width = width;
                            textureDesc.Height = height;
                            textureDesc.MipLevels = mipMapsGenerated ? 0 : 1;
                            textureDesc.ArraySize = 1;
                            textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
                            textureDesc.Usage = (dynamic && !renderTarget) ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_DEFAULT;
                            textureDesc.CPUAccessFlags = (dynamic && !renderTarget) ? D3D11_CPU_ACCESS_WRITE : 0;
                            textureDesc.SampleDesc.Count = sampleCount;
                            textureDesc.SampleDesc.Quality = 0;
                            textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | (renderTarget ? D3D11_BIND_RENDER_TARGET : 0);
                            textureDesc.MiscFlags = 0;

                            HRESULT hr = rendererD3D11->getDevice()->CreateTexture2D(&textureDesc, nullptr, &texture);
                            if (FAILED(hr))
                            {
                                Log(Log::Level::ERR) << "Failed to create Direct3D 11 texture";
                                return false;
                            }

                            D3D11_SHADER_RESOURCE_VIEW_DESC resourceViewDesc;
                            resourceViewDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
                            resourceViewDesc.ViewDimension = (sampleCount > 1) ? D3D11_SRV_DIMENSION_TEXTURE2DMS : D3D11_SRV_DIMENSION_TEXTURE2D;

                            if (sampleCount == 1)
                            {
                                resourceViewDesc.Texture2D.MostDetailedMip = 0;
                                resourceViewDesc.Texture2D.MipLevels = mipMapsGenerated ? static_cast<UINT>(levels.size()) : 1;
                            }

                            hr = rendererD3D11->getDevice()->CreateShaderResourceView(texture, &resourceViewDesc, &resourceView);
                            if (FAILED(hr))
                            {
                                Log(Log::Level::ERR) << "Failed to create Direct3D 11 shader resource view";
                                return false;
                            }

                            if (renderTarget)
                            {
                                if (!renderTargetView)
                                {
                                    D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc;
                                    renderTargetViewDesc.Format = textureDesc.Format;
                                    renderTargetViewDesc.ViewDimension = (sampleCount > 1) ? D3D11_RTV_DIMENSION_TEXTURE2DMS : D3D11_RTV_DIMENSION_TEXTURE2D;

                                    if (sampleCount == 1)
                                    {
                                        renderTargetViewDesc.Texture2D.MipSlice = 0;
                                    }

                                    HRESULT hr = rendererD3D11->getDevice()->CreateRenderTargetView(texture, &renderTargetViewDesc, &renderTargetView);
                                    if (FAILED(hr))
                                    {
                                        Log(Log::Level::ERR) << "Failed to create Direct3D 11 render target view";
                                        return false;
                                    }
                                }
                            }

                            if (depth)
                            {
                                D3D11_TEXTURE2D_DESC depthStencilDesc;
                                depthStencilDesc.Width = width;
                                depthStencilDesc.Height = height;
                                depthStencilDesc.MipLevels = 1;
                                depthStencilDesc.ArraySize = 1;
                                depthStencilDesc.Format = DXGI_FORMAT_D32_FLOAT;
                                depthStencilDesc.SampleDesc.Count = sampleCount;
                                depthStencilDesc.SampleDesc.Quality = 0;
                                depthStencilDesc.Usage = D3D11_USAGE_DEFAULT;
                                depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
                                depthStencilDesc.CPUAccessFlags = 0;
                                depthStencilDesc.MiscFlags = 0;
                                hr = rendererD3D11->getDevice()->CreateTexture2D(&depthStencilDesc, nullptr, &depthStencilTexture);
                                if (FAILED(hr))
                                {
                                    Log(Log::Level::ERR) << "Failed to create Direct3D 11 depth stencil texture";
                                    return false;
                                }

                                hr = rendererD3D11->getDevice()->CreateDepthStencilView(depthStencilTexture, nullptr, &depthStencilView);
                                if (FAILED(hr))
                                {
                                    Log(Log::Level::ERR) << "Failed to create Direct3D 11 depth stencil view";
                                    return false;
                                }
                            }
                        }

                        for (size_t level = 0; level < levels.size(); ++level)
                        {
                            if (!levels[level].data.empty())
                            {
                                rendererD3D11->getContext()->UpdateSubresource(texture, static_cast<UINT>(level),
                                                                               nullptr, levels[level].data.data(),
                                                                               static_cast<UINT>(levels[level].pitch), 0);
                            }
                        }
                    }
                }

                if (dirty & DIRTY_DATA)
                {
                    clearFrameBufferView = clearColorBuffer;
                    clearDepthBufferView = clearDepthBuffer;

                    frameBufferClearColor[0] = clearColor.normR();
                    frameBufferClearColor[1] = clearColor.normG();
                    frameBufferClearColor[2] = clearColor.normB();
                    frameBufferClearColor[3] = clearColor.normA();

                    RendererD3D11::SamplerStateDesc samplerDesc;
                    samplerDesc.filter = (filter == Texture::Filter::DEFAULT) ? rendererD3D11->getTextureFilter() : filter;
                    samplerDesc.addressX = addressX;
                    samplerDesc.addressY = addressY;
                    samplerDesc.maxAnisotropy = (maxAnisotropy == 0) ? rendererD3D11->getMaxAnisotropy() : maxAnisotropy;

                    samplerState = rendererD3D11->getSamplerState(samplerDesc);

                    if (!samplerState)
                    {
                        Log(Log::Level::ERR) << "Failed to get D3D11 sampler state";
                        return false;
                    }

                    samplerState->AddRef();
                }

                dirty = 0;
            }

            return true;
        }
    } // namespace graphics
} // namespace ouzel
<commit_msg>Fix memory leak in TextureD3D11<commit_after>// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.

#include "TextureD3D11.h"
#include "core/Engine.h"
#include "RendererD3D11.h"
#include "utils/Log.h"

namespace ouzel
{
    namespace graphics
    {
        TextureD3D11::TextureD3D11()
        {
        }

        TextureD3D11::~TextureD3D11()
        {
            if (renderTargetView)
            {
                renderTargetView->Release();
            }

            if (resourceView)
            {
                resourceView->Release();
            }

            if (texture)
            {
                texture->Release();
            }

            if (samplerState)
            {
                samplerState->Release();
            }

            width = 0;
            height = 0;
        }

        bool TextureD3D11::upload()
        {
            std::lock_guard<std::mutex> lock(uploadMutex);

            if (dirty)
            {
                RendererD3D11* rendererD3D11 = static_cast<RendererD3D11*>(sharedEngine->getRenderer());

                if (dirty & DIRTY_DATA)
                {
                    if (size.v[0] > 0 &&
                        size.v[1] > 0)
                    {
                        if (!texture ||
                            static_cast<UINT>(size.v[0]) != width ||
                            static_cast<UINT>(size.v[1]) != height)
                        {
                            if (texture) texture->Release();

                            width = static_cast<UINT>(size.v[0]);
                            height = static_cast<UINT>(size.v[1]);

                            D3D11_TEXTURE2D_DESC textureDesc;
                            textureDesc.Width = width;
                            textureDesc.Height = height;
                            textureDesc.MipLevels = mipMapsGenerated ? 0 : 1;
                            textureDesc.ArraySize = 1;
                            textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
                            textureDesc.Usage = (dynamic && !renderTarget) ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_DEFAULT;
                            textureDesc.CPUAccessFlags = (dynamic && !renderTarget) ? D3D11_CPU_ACCESS_WRITE : 0;
                            textureDesc.SampleDesc.Count = sampleCount;
                            textureDesc.SampleDesc.Quality = 0;
                            textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | (renderTarget ? D3D11_BIND_RENDER_TARGET : 0);
                            textureDesc.MiscFlags = 0;

                            HRESULT hr = rendererD3D11->getDevice()->CreateTexture2D(&textureDesc, nullptr, &texture);
                            if (FAILED(hr))
                            {
                                Log(Log::Level::ERR) << "Failed to create Direct3D 11 texture";
                                return false;
                            }

                            D3D11_SHADER_RESOURCE_VIEW_DESC resourceViewDesc;
                            resourceViewDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
                            resourceViewDesc.ViewDimension = (sampleCount > 1) ? D3D11_SRV_DIMENSION_TEXTURE2DMS : D3D11_SRV_DIMENSION_TEXTURE2D;

                            if (sampleCount == 1)
                            {
                                resourceViewDesc.Texture2D.MostDetailedMip = 0;
                                resourceViewDesc.Texture2D.MipLevels = mipMapsGenerated ? static_cast<UINT>(levels.size()) : 1;
                            }

                            hr = rendererD3D11->getDevice()->CreateShaderResourceView(texture, &resourceViewDesc, &resourceView);
                            if (FAILED(hr))
                            {
                                Log(Log::Level::ERR) << "Failed to create Direct3D 11 shader resource view";
                                return false;
                            }

                            if (renderTarget)
                            {
                                if (!renderTargetView)
                                {
                                    D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc;
                                    renderTargetViewDesc.Format = textureDesc.Format;
                                    renderTargetViewDesc.ViewDimension = (sampleCount > 1) ? D3D11_RTV_DIMENSION_TEXTURE2DMS : D3D11_RTV_DIMENSION_TEXTURE2D;

                                    if (sampleCount == 1)
                                    {
                                        renderTargetViewDesc.Texture2D.MipSlice = 0;
                                    }

                                    HRESULT hr = rendererD3D11->getDevice()->CreateRenderTargetView(texture, &renderTargetViewDesc, &renderTargetView);
                                    if (FAILED(hr))
                                    {
                                        Log(Log::Level::ERR) << "Failed to create Direct3D 11 render target view";
                                        return false;
                                    }
                                }
                            }

                            if (depth)
                            {
                                D3D11_TEXTURE2D_DESC depthStencilDesc;
                                depthStencilDesc.Width = width;
                                depthStencilDesc.Height = height;
                                depthStencilDesc.MipLevels = 1;
                                depthStencilDesc.ArraySize = 1;
                                depthStencilDesc.Format = DXGI_FORMAT_D32_FLOAT;
                                depthStencilDesc.SampleDesc.Count = sampleCount;
                                depthStencilDesc.SampleDesc.Quality = 0;
                                depthStencilDesc.Usage = D3D11_USAGE_DEFAULT;
                                depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
                                depthStencilDesc.CPUAccessFlags = 0;
                                depthStencilDesc.MiscFlags = 0;
                                hr = rendererD3D11->getDevice()->CreateTexture2D(&depthStencilDesc, nullptr, &depthStencilTexture);
                                if (FAILED(hr))
                                {
                                    Log(Log::Level::ERR) << "Failed to create Direct3D 11 depth stencil texture";
                                    return false;
                                }

                                hr = rendererD3D11->getDevice()->CreateDepthStencilView(depthStencilTexture, nullptr, &depthStencilView);
                                if (FAILED(hr))
                                {
                                    Log(Log::Level::ERR) << "Failed to create Direct3D 11 depth stencil view";
                                    return false;
                                }
                            }
                        }

                        for (size_t level = 0; level < levels.size(); ++level)
                        {
                            if (!levels[level].data.empty())
                            {
                                rendererD3D11->getContext()->UpdateSubresource(texture, static_cast<UINT>(level),
                                                                               nullptr, levels[level].data.data(),
                                                                               static_cast<UINT>(levels[level].pitch), 0);
                            }
                        }
                    }
                }

                if (dirty & DIRTY_DATA)
                {
                    clearFrameBufferView = clearColorBuffer;
                    clearDepthBufferView = clearDepthBuffer;

                    frameBufferClearColor[0] = clearColor.normR();
                    frameBufferClearColor[1] = clearColor.normG();
                    frameBufferClearColor[2] = clearColor.normB();
                    frameBufferClearColor[3] = clearColor.normA();

                    if (samplerState) samplerState->Release();

                    RendererD3D11::SamplerStateDesc samplerDesc;
                    samplerDesc.filter = (filter == Texture::Filter::DEFAULT) ? rendererD3D11->getTextureFilter() : filter;
                    samplerDesc.addressX = addressX;
                    samplerDesc.addressY = addressY;
                    samplerDesc.maxAnisotropy = (maxAnisotropy == 0) ? rendererD3D11->getMaxAnisotropy() : maxAnisotropy;

                    samplerState = rendererD3D11->getSamplerState(samplerDesc);

                    if (!samplerState)
                    {
                        Log(Log::Level::ERR) << "Failed to get D3D11 sampler state";
                        return false;
                    }

                    samplerState->AddRef();
                }

                dirty = 0;
            }

            return true;
        }
    } // namespace graphics
} // namespace ouzel
<|endoftext|>


<commit_before>#include "../include/FidoControlSystem.h"

#include <cassert>
#include <float.h>
#include <algorithm>

#include "../include/NeuralNet.h"
#include "../include/Backpropagation.h"
#include "../include/Adadelta.h"
#include "../include/Pruner.h"
#include "../include/LSInterpolator.h"

using namespace rl;

FidoControlSystem::FidoControlSystem(int stateDimensions, Action minAction, Action maxAction, int baseOfDimensions) : WireFitQLearn(stateDimensions, minAction.size(), 1, 12, 6, minAction, maxAction, baseOfDimensions, new rl::LSInterpolator(), new net::Adadelta(0.95, 0.15, 10000), 1, 0)  {
	explorationLevel = initialExploration;
}

std::vector<double> FidoControlSystem::chooseBoltzmanActionDynamic(State state) {
	return WireFitQLearn::chooseBoltzmanAction(state, explorationLevel);
}

void FidoControlSystem::applyReinforcementToLastAction(double reward, State newState) {
	// SGD on current scenario
	std::vector<Wire> newContolWires = newControlWiresForHistory(History(lastState, newState, lastAction, reward));

	// Calculate uncertainty and adjust exploration
	double uncertainty = getError(lastState, getRawOutput(newContolWires));
	adjustExploration(uncertainty);
	lastUncertainty = uncertainty;

	// History sample and resize nn
	histories.push_back(History(lastState, newState, lastAction, reward));
	std::vector<History> selectedHistories = selectHistories();

	/*std::cout << "----------RESIZING-----------\n";
	if(selectedHistories.size() > 3) {
		bool didChange = false;
		net::Pruner pruner;
		net::NeuralNet originalNet;
		int iter = 0;
		while(iter < 1) {
			iter++;
			originalNet = net::NeuralNet(network);

			// Randomize
			for(net::Layer &l : network->net) {
				for(net::Neuron &n : l.neurons) {
					n.randomizeWeights();
				}
			}

			double totalCurrentError = trainOnHistories(selectedHistories, 0.001, 5);

			if(network->numberOfHiddenNeurons() > 4) {
				pruner.pruneRandomnly(network);
				double totalPrunedError = trainOnHistories(selectedHistories, 0.001, 5);
				if(totalPrunedError*1.05 < totalCurrentError) {
					didChange = true;
					continue;
				}
			}

			*network = originalNet;
			network->net[0].neurons.push_back(net::Neuron(network->numberOfInputs()));
			for(net::Neuron &n : network->net[1].neurons) {
				n.weights.push_back(1);
				n.randomizeWeights();
			}
			double totalAddedError = trainOnHistories(selectedHistories, 0.001, 5);
			if(totalAddedError*1.05 < totalCurrentError) {
				didChange = true;
				continue;
			}

			*network = originalNet;
			break;
		}

		if(didChange == false) {
			*network = originalNet;
		}
		std::cout << "Num neurons: " << network->numberOfHiddenNeurons() << "\n";
	}
	std::cout << "-----------------\n";*/

	trainOnHistories(selectedHistories, 0.01, 100);
}

void FidoControlSystem::reset() {
	std::cout << "RESET\n";
	WireFitQLearn::reset();
	histories.clear();
	explorationLevel = initialExploration;
}

double FidoControlSystem::getError(std::vector<double> input, std::vector<double> correctOutput) {
	double totalError = 0;
	std::vector<double> output = network->getOutput(input);
	for(unsigned int a = 0; a < output.size(); a++) {
		totalError += pow(output[a] - correctOutput[a], 2);
	}

	return totalError / (double)output.size();
}

double FidoControlSystem::trainOnHistories(std::vector<FidoControlSystem::History> selectedHistories, double allowedError, unsigned int maxIterations) {

	double totalError = DBL_MAX;
	net::Adadelta tempTrainer = net::Adadelta(0.95, allowedError, 100);
	unsigned int iter = 0;
	do {
		std::vector< std::vector<double> > input, correctOutput;
		for(History history : selectedHistories) {
			std::vector<Wire> historyControlWires = getWires(history.initialState);
			double newRewardForLastAction = getQValue(history.reward, history.initialState, history.newState, history.action, historyControlWires);

			Wire correctHistoryWire = {history.action, newRewardForLastAction};
			std::vector<Wire> newContolWires = newControlWires(correctHistoryWire, historyControlWires);

			input.push_back(history.newState);
			correctOutput.push_back(getRawOutput(newContolWires));

			tempTrainer.train(network, {input.back()}, {correctOutput.back()});
		}

		totalError = 0;
		for(unsigned int a = 0; a < input.size(); a++) {
			std::vector<double> output = network->getOutput(input[a]);
			for(unsigned int b = 0; b < input[a].size(); b++) {
				totalError += pow(output[b] - correctOutput[a][b], 2);
			}
		}

		std::cout << "Error: " << totalError << "\n";
		iter++;
	} while (totalError > allowedError*selectedHistories.size() && iter < maxIterations);

	return totalError;
}

void FidoControlSystem::adjustExploration(double uncertainty) {
	explorationLevel = pow(uncertainty, 2) * 10000;
	if(explorationLevel < 0.00001) {
		explorationLevel = 0.00001;
	}
	if(explorationLevel > 1000) {
		explorationLevel = 1000;
	}
	std::cout << "Exploration level: " << explorationLevel << "\n";
}

std::vector<FidoControlSystem::History> FidoControlSystem::selectHistories() {
	std::vector<History> selectedHistories;
	std::vector<History> tempHistories(histories);
	while(selectedHistories.size() < samplesOfHistory && tempHistories.size() > 0) {
		History bestHistory = *(tempHistories.end()-1);
		double maxDifference = DBL_MIN;
		for(History prospectiveHistory : tempHistories) {
			double difference = 0;
			for(History selectedHistory : selectedHistories) {
				for(unsigned int stateIndex = 0; stateIndex < selectedHistory.initialState.size(); stateIndex++) {
					difference += pow(prospectiveHistory.initialState[stateIndex] - selectedHistory.initialState[stateIndex], 2);
				}
			}

			if(difference > maxDifference) {
				maxDifference = difference;
				bestHistory = prospectiveHistory;
			}
		}

		selectedHistories.push_back(bestHistory);
		tempHistories.erase(std::remove(tempHistories.begin(), tempHistories.end(), bestHistory), tempHistories.end());
	}

	return selectedHistories;
}

std::vector<Wire> FidoControlSystem::newControlWiresForHistory(History history) {
	std::vector<Wire> controlWires = getWires(history.initialState);
	double newRewardForLastAction = getQValue(history.reward, history.initialState, history.newState, history.action, controlWires);
	Wire correctWire = {history.action, newRewardForLastAction};
	return WireFitQLearn::newControlWires(correctWire, controlWires);
}
<commit_msg>DRIVE HOLO WORKS<commit_after>#include "../include/FidoControlSystem.h"

#include <cassert>
#include <float.h>
#include <algorithm>

#include "../include/NeuralNet.h"
#include "../include/Backpropagation.h"
#include "../include/Adadelta.h"
#include "../include/Pruner.h"
#include "../include/LSInterpolator.h"

using namespace rl;

FidoControlSystem::FidoControlSystem(int stateDimensions, Action minAction, Action maxAction, int baseOfDimensions) : WireFitQLearn(stateDimensions, minAction.size(), 1, 12, 6, minAction, maxAction, baseOfDimensions, new rl::LSInterpolator(), new net::Adadelta(0.95, 0.15, 10000), 1, 0)  {
	explorationLevel = initialExploration;
}

std::vector<double> FidoControlSystem::chooseBoltzmanActionDynamic(State state) {
	return WireFitQLearn::chooseBoltzmanAction(state, explorationLevel);
}

void FidoControlSystem::applyReinforcementToLastAction(double reward, State newState) {
	// SGD on current scenario
	std::vector<Wire> newContolWires = newControlWiresForHistory(History(lastState, newState, lastAction, reward));

	// Calculate uncertainty and adjust exploration
	double uncertainty = getError(lastState, getRawOutput(newContolWires));
	adjustExploration(uncertainty);
	lastUncertainty = uncertainty;

	// History sample and resize nn
	histories.push_back(History(lastState, newState, lastAction, reward));
	std::vector<History> selectedHistories = selectHistories();

	std::cout << "----------RESIZING-----------\n";
	if(selectedHistories.size() > 3) {
		bool didChange = false;
		net::Pruner pruner;
		net::NeuralNet originalNet;
		int iter = 0;
		while(iter < 1) {
			iter++;
			originalNet = net::NeuralNet(network);

			// Randomize
			for(net::Layer &l : network->net) {
				for(net::Neuron &n : l.neurons) {
					n.randomizeWeights();
				}
			}

			double totalCurrentError = trainOnHistories(selectedHistories, 0.001, 5);

			if(network->numberOfHiddenNeurons() > 4) {
				pruner.pruneRandomnly(network);
				double totalPrunedError = trainOnHistories(selectedHistories, 0.001, 5);
				if(totalPrunedError*1.05 < totalCurrentError) {
					didChange = true;
					continue;
				}
			}

			*network = originalNet;
			network->net[0].neurons.push_back(net::Neuron(network->numberOfInputs()));
			for(net::Neuron &n : network->net[1].neurons) {
				n.weights.push_back(1);
				n.randomizeWeights();
			}
			double totalAddedError = trainOnHistories(selectedHistories, 0.001, 5);
			if(totalAddedError*1.05 < totalCurrentError) {
				didChange = true;
				continue;
			}

			*network = originalNet;
			break;
		}

		if(didChange == false) {
			*network = originalNet;
		}
		std::cout << "Num neurons: " << network->numberOfHiddenNeurons() << "\n";
	}
	std::cout << "-----------------\n";

	trainOnHistories(selectedHistories, 0.01, 100);
}

void FidoControlSystem::reset() {
	std::cout << "RESET\n";
	WireFitQLearn::reset();
	histories.clear();
	explorationLevel = initialExploration;
}

double FidoControlSystem::getError(std::vector<double> input, std::vector<double> correctOutput) {
	double totalError = 0;
	std::vector<double> output = network->getOutput(input);
	for(unsigned int a = 0; a < output.size(); a++) {
		totalError += pow(output[a] - correctOutput[a], 2);
	}

	return totalError / (double)output.size();
}

double FidoControlSystem::trainOnHistories(std::vector<FidoControlSystem::History> selectedHistories, double allowedError, unsigned int maxIterations) {

	double totalError = DBL_MAX;
	net::Adadelta tempTrainer = net::Adadelta(0.95, allowedError, 100);
	unsigned int iter = 0;
	do {
		std::vector< std::vector<double> > input, correctOutput;
		for(History history : selectedHistories) {
			std::vector<Wire> historyControlWires = getWires(history.initialState);
			double newRewardForLastAction = getQValue(history.reward, history.initialState, history.newState, history.action, historyControlWires);

			Wire correctHistoryWire = {history.action, newRewardForLastAction};
			std::vector<Wire> newContolWires = newControlWires(correctHistoryWire, historyControlWires);

			input.push_back(history.newState);
			correctOutput.push_back(getRawOutput(newContolWires));

			tempTrainer.train(network, {input.back()}, {correctOutput.back()});
		}

		totalError = 0;
		for(unsigned int a = 0; a < input.size(); a++) {
			std::vector<double> output = network->getOutput(input[a]);
			for(unsigned int b = 0; b < input[a].size(); b++) {
				totalError += pow(output[b] - correctOutput[a][b], 2);
			}
		}

		std::cout << "Error: " << totalError << "\n";
		iter++;
	} while (totalError > allowedError*selectedHistories.size() && iter < maxIterations);

	return totalError;
}

void FidoControlSystem::adjustExploration(double uncertainty) {
	explorationLevel = pow(uncertainty, 2) * 10000;
	if(explorationLevel < 0.00001) {
		explorationLevel = 0.00001;
	}
	if(explorationLevel > 1000) {
		explorationLevel = 1000;
	}
	std::cout << "Exploration level: " << explorationLevel << "\n";
}

std::vector<FidoControlSystem::History> FidoControlSystem::selectHistories() {
	std::vector<History> selectedHistories;
	std::vector<History> tempHistories(histories);
	while(selectedHistories.size() < samplesOfHistory && tempHistories.size() > 0) {
		History bestHistory = *(tempHistories.end()-1);
		double maxDifference = DBL_MIN;
		for(History prospectiveHistory : tempHistories) {
			double difference = 0;
			for(History selectedHistory : selectedHistories) {
				for(unsigned int stateIndex = 0; stateIndex < selectedHistory.initialState.size(); stateIndex++) {
					difference += pow(prospectiveHistory.initialState[stateIndex] - selectedHistory.initialState[stateIndex], 2);
				}
			}

			if(difference > maxDifference) {
				maxDifference = difference;
				bestHistory = prospectiveHistory;
			}
		}

		selectedHistories.push_back(bestHistory);
		tempHistories.erase(std::remove(tempHistories.begin(), tempHistories.end(), bestHistory), tempHistories.end());
	}

	return selectedHistories;
}

std::vector<Wire> FidoControlSystem::newControlWiresForHistory(History history) {
	std::vector<Wire> controlWires = getWires(history.initialState);
	double newRewardForLastAction = getQValue(history.reward, history.initialState, history.newState, history.action, controlWires);
	Wire correctWire = {history.action, newRewardForLastAction};
	return WireFitQLearn::newControlWires(correctWire, controlWires);
}
<|endoftext|>


<commit_before>#include <stan/math/mix.hpp>
#include <gtest/gtest.h>
#include <limits>

template <typename T>
void expect_isnan() {
  using stan::math::isnan;
  using std::isnan;
  using std::numeric_limits;
  T inf = numeric_limits<double>::infinity();
  T nan = std::numeric_limits<double>::quiet_NaN();
  EXPECT_FALSE(isnan(inf));
  EXPECT_FALSE(isnan(-inf));
  EXPECT_TRUE(isnan(nan));
  EXPECT_FALSE(isinf(T(1)));
  EXPECT_FALSE(isinf(T(1.0)));
  EXPECT_FALSE(isinf(T(0)));
  EXPECT_FALSE(isinf(T(0.0)));
  EXPECT_FALSE(isinf(T(-1)));
  EXPECT_FALSE(isinf(T(-1.0)));
}

TEST(mixFun, isnan) {
  using stan::math::fvar;
  using stan::math::var;
  expect_isnan<double>();
  expect_isnan<var>();
  expect_isnan<fvar<double>>();
  expect_isnan<fvar<fvar<double>>>();
  expect_isnan<fvar<var>>();
  expect_isnan<fvar<fvar<var>>>();
}
<commit_msg>fix isnan tests to call right fun<commit_after>#include <stan/math/mix.hpp>
#include <gtest/gtest.h>
#include <limits>

template <typename T>
void expect_isnan() {
  using stan::math::isnan;
  using std::isnan;
  using std::numeric_limits;
  T inf = numeric_limits<double>::infinity();
  T nan = std::numeric_limits<double>::quiet_NaN();
  EXPECT_FALSE(isnan(inf));
  EXPECT_FALSE(isnan(-inf));
  EXPECT_TRUE(isnan(nan));
  EXPECT_FALSE(isnan(T(1)));
  EXPECT_FALSE(isnan(T(1.0)));
  EXPECT_FALSE(isnan(T(0)));
  EXPECT_FALSE(isnan(T(0.0)));
  EXPECT_FALSE(isnan(T(-1)));
  EXPECT_FALSE(isnan(T(-1.0)));
}

TEST(mixFun, isnan) {
  using stan::math::fvar;
  using stan::math::var;
  expect_isnan<double>();
  expect_isnan<var>();
  expect_isnan<fvar<double>>();
  expect_isnan<fvar<fvar<double>>>();
  expect_isnan<fvar<var>>();
  expect_isnan<fvar<fvar<var>>>();
}
<|endoftext|>


<commit_before>#ifndef LIA_PRETTY_PRINT_HPP
#define LIA_PRETTY_PRINT_HPP

#include "../detail/type_traits.hpp"
#include "../detail/iterator.hpp"
#include "../detail/indices.hpp"
#include <iosfwd>

namespace lia {
namespace pretty_print_detail {
template<class Elem, class Traits, class Tuple, size_t... Indices>
void print_tuple(std::basic_ostream<Elem, Traits>& os, const Tuple& t, indices<Indices...>) {
    using expander = int[];
    using std::get;
    (void)expander{0, (void(os << (!Indices ? "" : ", ") << get<Indices>(t)), 0)...};
}
} // pretty_print_detail
namespace operators {
template<class Elem, class Traits, typename... Args>
inline std::basic_ostream<Elem, Traits>& operator<<(std::basic_ostream<Elem, Traits>& os, const std::tuple<Args...>& tuple) {
    os << "(";
    pretty_print_detail::print_tuple(os, tuple, build_indices<sizeof...(Args)>());
    os << ")";
    return os;
}

template<class Elem, class Traits, typename T, typename U>
inline std::basic_ostream<Elem,Traits>& operator<<(std::basic_ostream<Elem,Traits>& os, const std::pair<T,U>& p) {
    os << '(' << p.first << ", " << p.second << ')';
    return os;
}

template<class Elem, class Traits, class Cont, EnableIf<has_begin_end<Unqualified<Cont>>>...>
inline std::basic_ostream<Elem, Traits>& operator<<(std::basic_ostream<Elem, Traits>& os, const Cont& cont) {
    auto first = std::begin(cont);
    auto last = std::end(cont);
    if(first == last) {
        os << "[]";
        return os;
    }
    else {
        os << '[' << *first++;
    }
    while(first != last) {
        os << ", " << *first++;
    }
    os << ']';
    return os;
}
} // operators
} // lia

#endif // LIA_PRETTY_PRINT_HPP<commit_msg>Fixed prettyprint includes<commit_after>#ifndef LIA_PRETTY_PRINT_HPP
#define LIA_PRETTY_PRINT_HPP

#include "detail/type_traits.hpp"
#include "detail/iterator.hpp"
#include "detail/indices.hpp"
#include <iosfwd>

namespace lia {
namespace pretty_print_detail {
template<class Elem, class Traits, class Tuple, size_t... Indices>
void print_tuple(std::basic_ostream<Elem, Traits>& os, const Tuple& t, indices<Indices...>) {
    using expander = int[];
    using std::get;
    (void)expander{0, (void(os << (!Indices ? "" : ", ") << get<Indices>(t)), 0)...};
}
} // pretty_print_detail
namespace operators {
template<class Elem, class Traits, typename... Args>
inline std::basic_ostream<Elem, Traits>& operator<<(std::basic_ostream<Elem, Traits>& os, const std::tuple<Args...>& tuple) {
    os << "(";
    pretty_print_detail::print_tuple(os, tuple, build_indices<sizeof...(Args)>());
    os << ")";
    return os;
}

template<class Elem, class Traits, typename T, typename U>
inline std::basic_ostream<Elem,Traits>& operator<<(std::basic_ostream<Elem,Traits>& os, const std::pair<T,U>& p) {
    os << '(' << p.first << ", " << p.second << ')';
    return os;
}

template<class Elem, class Traits, class Cont, EnableIf<has_begin_end<Unqualified<Cont>>>...>
inline std::basic_ostream<Elem, Traits>& operator<<(std::basic_ostream<Elem, Traits>& os, const Cont& cont) {
    auto first = std::begin(cont);
    auto last = std::end(cont);
    if(first == last) {
        os << "[]";
        return os;
    }
    else {
        os << '[' << *first++;
    }
    while(first != last) {
        os << ", " << *first++;
    }
    os << ']';
    return os;
}
} // operators
} // lia

#endif // LIA_PRETTY_PRINT_HPP<|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)
//=======================================================================

#define DLL_SVM_SUPPORT

#include "dll/conv_dbn.hpp"

template<typename DBN>
void test_dbn(){
    DBN dbn;

    dbn.display();

    std::vector<etl::dyn_vector<double>> images;
    std::vector<uint8_t> labels;

    etl::dyn_vector<double> result(100);

    dbn.pretrain(images, 10);
    dbn.svm_train(images, labels);
    dbn.svm_train(images.begin(), images.end(), labels.begin(), labels.end());
    dbn.svm_grid_search(images, labels);
    dbn.svm_grid_search(images.begin(), images.end(), labels.begin(), labels.end());
    dbn.svm_predict(images[1]);
}

template <typename RBM>
using pcd2_trainer_t = dll::persistent_cd_trainer<2, RBM>;

int main(){
    //Basic example

    //TODO Enable again once multi channel RBM are supported
    //typedef dll::conv_dbn_desc<
        //dll::dbn_layers<
        //dll::conv_rbm_desc<28, 12, 40, dll::momentum, dll::batch_size<50>>::rbm_t,
        //dll::conv_rbm_desc<12*12*40, 6, 40, dll::momentum, dll::batch_size<50>>::rbm_t>>::dbn_t dbn_1;

    ////Test them all

    //test_dbn<dbn_1>();

    return 0;
}<commit_msg>Reactivate test<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)
//=======================================================================

#define DLL_SVM_SUPPORT

#include "dll/conv_rbm.hpp"
#include "dll/conv_dbn.hpp"

template<typename DBN>
void test_dbn(){
    DBN dbn;

    dbn.display();

    std::vector<etl::dyn_vector<double>> images;
    std::vector<uint8_t> labels;

    etl::dyn_vector<double> result(100);

    dbn.pretrain(images, 10);
    dbn.svm_train(images, labels);
    dbn.svm_train(images.begin(), images.end(), labels.begin(), labels.end());
    dbn.svm_grid_search(images, labels);
    dbn.svm_grid_search(images.begin(), images.end(), labels.begin(), labels.end());
    dbn.svm_predict(images[1]);
}

int main(){
    //Basic example

    typedef dll::conv_dbn_desc<
        dll::dbn_layers<
        dll::conv_rbm_desc<28, 1, 12, 40, dll::momentum, dll::batch_size<50>>::rbm_t,
        dll::conv_rbm_desc<12, 40, 6, 40, dll::momentum, dll::batch_size<50>>::rbm_t>>::dbn_t dbn_1;

    //Test them all

    test_dbn<dbn_1>();

    return 0;
}<|endoftext|>


<commit_before>//=================================================================================================
//
//  MJP's DX11 Sample Framework
//  http://mynameismjp.wordpress.com/
//
//  All code licensed under the MIT license
//
//=================================================================================================

#include "PCH.h"

#include "..\\Utility.h"
#include "..\\Exceptions.h"
#include "Textures.h"
#include "DDSTextureLoader.h"
#include "WICTextureLoader.h"
#include "..\\FileIO.h"
#include "ShaderCompilation.h"
#include "GraphicsTypes.h"
#include "TinyEXR.h"

namespace SampleFramework11
{

    // Loads a texture, using either the DDS loader or the WIC loader
ID3D11ShaderResourceViewPtr LoadTexture(ID3D11Device* device, const wchar* filePath, bool forceSRGB)
{
    ID3D11DeviceContextPtr context;
    device->GetImmediateContext(&context);

    ID3D11ResourcePtr resource;
    ID3D11ShaderResourceViewPtr srv;

    const std::wstring extension = GetFileExtension(filePath);
    _bstr_t b(filePath);
    const char * buff = b;
    if(extension == L"DDS" || extension == L"dds")
    {
        DXCall(DirectX::CreateDDSTextureFromFileEx(device, filePath, 0, D3D11_USAGE_DEFAULT,
                                                   D3D11_BIND_SHADER_RESOURCE, 0, 0, forceSRGB,
                                                   &resource, &srv, nullptr));
        resource->SetPrivateData(WKPDID_D3DDebugObjectName, (UINT)strlen(buff), buff);

        return srv;
    }
    else
    {
        DXCall(DirectX:: CreateWICTextureFromFileEx(device, context, filePath, 0, D3D11_USAGE_DEFAULT,
                                                    D3D11_BIND_SHADER_RESOURCE, 0, 0, forceSRGB, &resource, &srv));
        resource->SetPrivateData(WKPDID_D3DDebugObjectName, (UINT)strlen(buff), buff);

        return srv;
    }
}

template<typename T>
static void GetTextureData(ID3D11Device* device, ID3D11ShaderResourceView* textureSRV,
                           DXGI_FORMAT outFormat, TextureData<T>& texData)
{
    static ComputeShaderPtr decodeTextureCS;
    static ComputeShaderPtr decodeTextureArrayCS;

    static const uint32 TGSize = 16;

    if(decodeTextureCS.Valid() == false)
    {
        CompileOptions opts;
        opts.Add("TGSize_", TGSize);
        const std::wstring shaderPath = SampleFrameworkDir() + L"Shaders\\DecodeTextureCS.hlsl";
        decodeTextureCS = CompileCSFromFile(device, shaderPath.c_str(), "DecodeTextureCS", "cs_5_0", opts);

        decodeTextureArrayCS = CompileCSFromFile(device, shaderPath.c_str(), "DecodeTextureArrayCS", "cs_5_0", opts);
    }

    ID3D11Texture2DPtr texture;
    textureSRV->GetResource(reinterpret_cast<ID3D11Resource**>(&texture));

    D3D11_TEXTURE2D_DESC texDesc;
    texture->GetDesc(&texDesc);

    D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
    textureSRV->GetDesc(&srvDesc);

    ID3D11ShaderResourceViewPtr sourceSRV = textureSRV;
    uint32 arraySize = texDesc.ArraySize;
    if(srvDesc.ViewDimension == D3D11_SRV_DIMENSION_TEXTURECUBE
       || srvDesc.ViewDimension == D3D11_SRV_DIMENSION_TEXTURECUBEARRAY)
    {
        srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DARRAY;
        srvDesc.Texture2DArray.ArraySize = arraySize;
        srvDesc.Texture2DArray.FirstArraySlice = 0;
        srvDesc.Texture2DArray.MostDetailedMip = 0;
        srvDesc.Texture2DArray.MipLevels = -1;
        DXCall(device->CreateShaderResourceView(texture, &srvDesc, &sourceSRV));
    }

    D3D11_TEXTURE2D_DESC decodeTextureDesc;
    decodeTextureDesc.Width = texDesc.Width;
    decodeTextureDesc.Height = texDesc.Height;
    decodeTextureDesc.ArraySize = arraySize;
    decodeTextureDesc.BindFlags = D3D11_BIND_UNORDERED_ACCESS;
    decodeTextureDesc.Format = outFormat;
    decodeTextureDesc.MipLevels = 1;
    decodeTextureDesc.MiscFlags = 0;
    decodeTextureDesc.SampleDesc.Count = 1;
    decodeTextureDesc.SampleDesc.Quality = 0;
    decodeTextureDesc.Usage = D3D11_USAGE_DEFAULT;
    decodeTextureDesc.CPUAccessFlags = 0;

    ID3D11Texture2DPtr decodeTexture;
    DXCall(device->CreateTexture2D(&decodeTextureDesc, nullptr, &decodeTexture));
    std::string decode_texture("decode_texture");
    decodeTexture->SetPrivateData(WKPDID_D3DDebugObjectName, (UINT)decode_texture.length(), decode_texture.c_str());

    ID3D11UnorderedAccessViewPtr decodeTextureUAV;
    DXCall(device->CreateUnorderedAccessView(decodeTexture, nullptr, &decodeTextureUAV));

    ID3D11DeviceContextPtr context;
    device->GetImmediateContext(&context);

    SetCSInputs(context, sourceSRV);
    SetCSOutputs(context, decodeTextureUAV);
    SetCSShader(context, arraySize > 1 ? decodeTextureArrayCS : decodeTextureCS);

    context->Dispatch(DispatchSize(TGSize, texDesc.Width), DispatchSize(TGSize, texDesc.Height), arraySize);

    ClearCSInputs(context);
    ClearCSOutputs(context);

    StagingTexture2D stagingTexture;
    stagingTexture.Initialize(device, texDesc.Width, texDesc.Height, outFormat, 1, 1, 0, arraySize);
    context->CopyResource(stagingTexture.Texture, decodeTexture);

    texData.Init(texDesc.Width, texDesc.Height, arraySize);

    for(uint32 slice = 0; slice < arraySize; ++slice)
    {
        uint32 pitch = 0;
        const uint8* srcData = reinterpret_cast<const uint8*>(stagingTexture.Map(context, slice, pitch));
        Assert_(pitch >= texDesc.Width * sizeof(T));

        const uint32 sliceOffset = texDesc.Width * texDesc.Height * slice;

        for(uint32 y = 0; y < texDesc.Height; ++y)
        {
            const T* rowData = reinterpret_cast<const T*>(srcData);

            for(uint32 x = 0; x < texDesc.Width; ++x)
                texData.Texels[y * texDesc.Width + x + sliceOffset] = rowData[x];

            srcData += pitch;
        }
    }
}

// Decode a texture into 32-bit floats and copies it to the CPU
void GetTextureData(ID3D11Device* device, ID3D11ShaderResourceView* textureSRV,
                    TextureData<Float4>& textureData)
{
    GetTextureData(device, textureSRV, DXGI_FORMAT_R32G32B32A32_FLOAT, textureData);
}

// Decode a texture into 16-bit floats and copies it to the CPU
void GetTextureData(ID3D11Device* device, ID3D11ShaderResourceView* textureSRV,
                    TextureData<Half4>& textureData)
{
    GetTextureData(device, textureSRV, DXGI_FORMAT_R16G16B16A16_FLOAT, textureData);
}

// Decode a texture into 32-bit floats and copies it to the CPU
void GetTextureData(ID3D11Device* device, ID3D11ShaderResourceView* textureSRV,
                    TextureData<UByte4N>& textureData)
{
    GetTextureData(device, textureSRV, DXGI_FORMAT_R8G8B8A8_UNORM, textureData);
}

template<typename T>
static ID3D11ShaderResourceViewPtr CreateSRVFromTextureData(ID3D11Device* device, const TextureData<T>& textureData)
{
    DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN;
    if(typeid(T) == typeid(UByte4N))
        format = DXGI_FORMAT_R8G8B8A8_UNORM;
    else if(typeid(T) == typeid(Half4))
        format = DXGI_FORMAT_R16G16B16A16_FLOAT;
    else if(typeid(T) == typeid(Float4))
        format = DXGI_FORMAT_R32G32B32A32_FLOAT;

    Assert_(format != DXGI_FORMAT_UNKNOWN);

    const uint64 elemSize = sizeof(T);
    Assert_(textureData.Texels.size() > 0);
    Assert_(textureData.Width * textureData.Height * textureData.NumSlices == textureData.Texels.size());

    std::vector<D3D11_SUBRESOURCE_DATA> subResources;
    subResources.resize(textureData.NumSlices);
    for(uint64 i = 0; i < textureData.NumSlices; ++i)
    {
        subResources[i].pSysMem = &textureData.Texels[textureData.Width * textureData.Height * i];
        subResources[i].SysMemPitch = elemSize * textureData.Width;
        subResources[i].SysMemSlicePitch = 0;
    }

    D3D11_TEXTURE2D_DESC texDesc;
    texDesc.Width = textureData.Width;
    texDesc.Height = textureData.Height;
    texDesc.MipLevels = 1;
    texDesc.ArraySize = textureData.NumSlices;
    texDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
    texDesc.SampleDesc.Count = 1;
    texDesc.SampleDesc.Quality = 0;
    texDesc.Usage = D3D11_USAGE_IMMUTABLE;
    texDesc.CPUAccessFlags = 0;
    texDesc.MiscFlags = 0;
    texDesc.Format = format;
    ID3D11Texture2DPtr texture;
    DXCall(device->CreateTexture2D(&texDesc, subResources.data(), &texture));

    ID3D11ShaderResourceViewPtr srv;
    DXCall(device->CreateShaderResourceView(texture, nullptr, &srv));

    return srv;
}

ID3D11ShaderResourceViewPtr CreateSRVFromTextureData(ID3D11Device* device, const TextureData<UByte4N>& textureData)
{
    return CreateSRVFromTextureData<UByte4N>(device, textureData);
}

ID3D11ShaderResourceViewPtr CreateSRVFromTextureData(ID3D11Device* device, const TextureData<Half4>& textureData)
{
    return CreateSRVFromTextureData<Half4>(device, textureData);
}

ID3D11ShaderResourceViewPtr CreateSRVFromTextureData(ID3D11Device* device, const TextureData<Float4>& textureData)
{
    return CreateSRVFromTextureData<Float4>(device, textureData);
}

void SaveTextureAsDDS(ID3D11ShaderResourceView* srv, const wchar* filePath)
{
    ID3D11ResourcePtr texture;
    srv->GetResource(&texture);

    SaveTextureAsDDS(texture, filePath);
}

void SaveTextureAsDDS(ID3D11Resource* texture, const wchar* filePath)
{
    ID3D11DevicePtr device;
    texture->GetDevice(&device);

    ID3D11DeviceContextPtr context;
    device->GetImmediateContext(&context);

    ScratchImage scratchImage;
    DXCall(CaptureTexture(device, context, texture, scratchImage));
    DXCall(SaveToDDSFile(scratchImage.GetImages(), scratchImage.GetImageCount(),
                         scratchImage.GetMetadata(), DDS_FLAGS_FORCE_DX10_EXT, filePath));
}

void SaveTextureAsEXR(ID3D11ShaderResourceView* srv, const wchar* filePath)
{
    ID3D11DevicePtr device;
    srv->GetDevice(&device);

    TextureData<Float4> textureData;
    GetTextureData(device, srv, textureData);

    SaveTextureAsEXR(textureData, filePath);
}

void SaveTextureAsEXR(const TextureData<Float4>& texture, const wchar* filePath)
{
    Assert_(texture.Texels.size() > 0);
    Assert_(texture.Width > 0 && texture.Height > 0);
    Assert_(texture.NumSlices == 1);

    const uint64 numTexels = texture.Texels.size();
    std::vector<float> channelDataR;
    std::vector<float> channelDataG;
    std::vector<float> channelDataB;
    channelDataR.resize(numTexels);
    channelDataG.resize(numTexels);
    channelDataB.resize(numTexels);
    for(uint64 i = 0; i < numTexels; ++i)
    {
        channelDataR[i] = texture.Texels[i].x;
        channelDataG[i] = texture.Texels[i].y;
        channelDataB[i] = texture.Texels[i].z;
    }

    float* imageChannels[3] = { channelDataB.data(), channelDataG.data(), channelDataR.data() };
    const char* channelNames[3] = { "B", "G", "R" };

    EXRImage exrImage;
    exrImage.num_channels = 3;
    exrImage.width = texture.Width;
    exrImage.height = texture.Height;
    exrImage.channel_names = channelNames;
    exrImage.images = imageChannels;

    std::string filePathAnsi = WStringToAnsi(filePath);

    const char* errorString = nullptr;
    int returnCode = SaveMultiChannelEXR(&exrImage, filePathAnsi.c_str(), &errorString);
    if(returnCode != 0)
    {
        AssertFail_("%s", errorString);
        throw Exception(AnsiToWString(errorString));
    }
}

// Utility function to map a XY + Side coordinate to a direction vector
Float3 MapXYSToDirection(uint64 x, uint64 y, uint64 s, uint64 width, uint64 height)
{
    float u = ((x + 0.5f) / float(width)) * 2.0f - 1.0f;
    float v = ((y + 0.5f) / float(height)) * 2.0f - 1.0f;
    v *= -1.0f;

    Float3 dir = 0.0f;

    // +x, -x, +y, -y, +z, -z
    switch(s) {
    case 0:
        dir = Float3::Normalize(Float3(1.0f, v, -u));
        break;
    case 1:
        dir = Float3::Normalize(Float3(-1.0f, v, u));
        break;
    case 2:
        dir = Float3::Normalize(Float3(u, 1.0f, -v));
        break;
    case 3:
        dir = Float3::Normalize(Float3(u, -1.0f, v));
        break;
    case 4:
        dir = Float3::Normalize(Float3(u, v, 1.0f));
        break;
    case 5:
        dir = Float3::Normalize(Float3(-u, v, -1.0f));
        break;
    }

    return dir;
}

}<commit_msg>Update Textures.cpp<commit_after>//=================================================================================================
//
//  MJP's DX11 Sample Framework
//  http://mynameismjp.wordpress.com/
//
//  All code licensed under the MIT license
//
//=================================================================================================

#include "PCH.h"

#include "..\\Utility.h"
#include "..\\Exceptions.h"
#include "Textures.h"
#include "DDSTextureLoader.h"
#include "WICTextureLoader.h"
#include "..\\FileIO.h"
#include "ShaderCompilation.h"
#include "GraphicsTypes.h"
#include "TinyEXR.h"

namespace SampleFramework11
{

    // Loads a texture, using either the DDS loader or the WIC loader
ID3D11ShaderResourceViewPtr LoadTexture(ID3D11Device* device, const wchar* filePath, bool forceSRGB)
{
    ID3D11DeviceContextPtr context;
    device->GetImmediateContext(&context);

    ID3D11ResourcePtr resource;
    ID3D11ShaderResourceViewPtr srv;

    const std::wstring extension = GetFileExtension(filePath);
    _bstr_t b(filePath);
    const char * buff = b;
    if(extension == L"DDS" || extension == L"dds")
    {
        DXCall(DirectX::CreateDDSTextureFromFileEx(device, filePath, 0, D3D11_USAGE_DEFAULT,
                                                   D3D11_BIND_SHADER_RESOURCE, 0, 0, forceSRGB,
                                                   &resource, &srv, nullptr));
        resource->SetPrivateData(WKPDID_D3DDebugObjectName, 0, NULL); //Prevents error SETPRIVATEDATA_CHANGINGPARAMS
        resource->SetPrivateData(WKPDID_D3DDebugObjectName, (UINT)strlen(buff), buff);

        return srv;
    }
    else
    {
        DXCall(DirectX:: CreateWICTextureFromFileEx(device, context, filePath, 0, D3D11_USAGE_DEFAULT,
                                                    D3D11_BIND_SHADER_RESOURCE, 0, 0, forceSRGB, &resource, &srv));
        resource->SetPrivateData(WKPDID_D3DDebugObjectName, 0, NULL); //Prevents error SETPRIVATEDATA_CHANGINGPARAMS
        resource->SetPrivateData(WKPDID_D3DDebugObjectName, (UINT)strlen(buff), buff);

        return srv;
    }
}

template<typename T>
static void GetTextureData(ID3D11Device* device, ID3D11ShaderResourceView* textureSRV,
                           DXGI_FORMAT outFormat, TextureData<T>& texData)
{
    static ComputeShaderPtr decodeTextureCS;
    static ComputeShaderPtr decodeTextureArrayCS;

    static const uint32 TGSize = 16;

    if(decodeTextureCS.Valid() == false)
    {
        CompileOptions opts;
        opts.Add("TGSize_", TGSize);
        const std::wstring shaderPath = SampleFrameworkDir() + L"Shaders\\DecodeTextureCS.hlsl";
        decodeTextureCS = CompileCSFromFile(device, shaderPath.c_str(), "DecodeTextureCS", "cs_5_0", opts);

        decodeTextureArrayCS = CompileCSFromFile(device, shaderPath.c_str(), "DecodeTextureArrayCS", "cs_5_0", opts);
    }

    ID3D11Texture2DPtr texture;
    textureSRV->GetResource(reinterpret_cast<ID3D11Resource**>(&texture));

    D3D11_TEXTURE2D_DESC texDesc;
    texture->GetDesc(&texDesc);

    D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
    textureSRV->GetDesc(&srvDesc);

    ID3D11ShaderResourceViewPtr sourceSRV = textureSRV;
    uint32 arraySize = texDesc.ArraySize;
    if(srvDesc.ViewDimension == D3D11_SRV_DIMENSION_TEXTURECUBE
       || srvDesc.ViewDimension == D3D11_SRV_DIMENSION_TEXTURECUBEARRAY)
    {
        srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DARRAY;
        srvDesc.Texture2DArray.ArraySize = arraySize;
        srvDesc.Texture2DArray.FirstArraySlice = 0;
        srvDesc.Texture2DArray.MostDetailedMip = 0;
        srvDesc.Texture2DArray.MipLevels = -1;
        DXCall(device->CreateShaderResourceView(texture, &srvDesc, &sourceSRV));
    }

    D3D11_TEXTURE2D_DESC decodeTextureDesc;
    decodeTextureDesc.Width = texDesc.Width;
    decodeTextureDesc.Height = texDesc.Height;
    decodeTextureDesc.ArraySize = arraySize;
    decodeTextureDesc.BindFlags = D3D11_BIND_UNORDERED_ACCESS;
    decodeTextureDesc.Format = outFormat;
    decodeTextureDesc.MipLevels = 1;
    decodeTextureDesc.MiscFlags = 0;
    decodeTextureDesc.SampleDesc.Count = 1;
    decodeTextureDesc.SampleDesc.Quality = 0;
    decodeTextureDesc.Usage = D3D11_USAGE_DEFAULT;
    decodeTextureDesc.CPUAccessFlags = 0;

    ID3D11Texture2DPtr decodeTexture;
    DXCall(device->CreateTexture2D(&decodeTextureDesc, nullptr, &decodeTexture));
    std::string decode_texture("decode_texture");
    decodeTexture->SetPrivateData(WKPDID_D3DDebugObjectName, (UINT)decode_texture.length(), decode_texture.c_str());

    ID3D11UnorderedAccessViewPtr decodeTextureUAV;
    DXCall(device->CreateUnorderedAccessView(decodeTexture, nullptr, &decodeTextureUAV));

    ID3D11DeviceContextPtr context;
    device->GetImmediateContext(&context);

    SetCSInputs(context, sourceSRV);
    SetCSOutputs(context, decodeTextureUAV);
    SetCSShader(context, arraySize > 1 ? decodeTextureArrayCS : decodeTextureCS);

    context->Dispatch(DispatchSize(TGSize, texDesc.Width), DispatchSize(TGSize, texDesc.Height), arraySize);

    ClearCSInputs(context);
    ClearCSOutputs(context);

    StagingTexture2D stagingTexture;
    stagingTexture.Initialize(device, texDesc.Width, texDesc.Height, outFormat, 1, 1, 0, arraySize);
    context->CopyResource(stagingTexture.Texture, decodeTexture);

    texData.Init(texDesc.Width, texDesc.Height, arraySize);

    for(uint32 slice = 0; slice < arraySize; ++slice)
    {
        uint32 pitch = 0;
        const uint8* srcData = reinterpret_cast<const uint8*>(stagingTexture.Map(context, slice, pitch));
        Assert_(pitch >= texDesc.Width * sizeof(T));

        const uint32 sliceOffset = texDesc.Width * texDesc.Height * slice;

        for(uint32 y = 0; y < texDesc.Height; ++y)
        {
            const T* rowData = reinterpret_cast<const T*>(srcData);

            for(uint32 x = 0; x < texDesc.Width; ++x)
                texData.Texels[y * texDesc.Width + x + sliceOffset] = rowData[x];

            srcData += pitch;
        }
    }
}

// Decode a texture into 32-bit floats and copies it to the CPU
void GetTextureData(ID3D11Device* device, ID3D11ShaderResourceView* textureSRV,
                    TextureData<Float4>& textureData)
{
    GetTextureData(device, textureSRV, DXGI_FORMAT_R32G32B32A32_FLOAT, textureData);
}

// Decode a texture into 16-bit floats and copies it to the CPU
void GetTextureData(ID3D11Device* device, ID3D11ShaderResourceView* textureSRV,
                    TextureData<Half4>& textureData)
{
    GetTextureData(device, textureSRV, DXGI_FORMAT_R16G16B16A16_FLOAT, textureData);
}

// Decode a texture into 32-bit floats and copies it to the CPU
void GetTextureData(ID3D11Device* device, ID3D11ShaderResourceView* textureSRV,
                    TextureData<UByte4N>& textureData)
{
    GetTextureData(device, textureSRV, DXGI_FORMAT_R8G8B8A8_UNORM, textureData);
}

template<typename T>
static ID3D11ShaderResourceViewPtr CreateSRVFromTextureData(ID3D11Device* device, const TextureData<T>& textureData)
{
    DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN;
    if(typeid(T) == typeid(UByte4N))
        format = DXGI_FORMAT_R8G8B8A8_UNORM;
    else if(typeid(T) == typeid(Half4))
        format = DXGI_FORMAT_R16G16B16A16_FLOAT;
    else if(typeid(T) == typeid(Float4))
        format = DXGI_FORMAT_R32G32B32A32_FLOAT;

    Assert_(format != DXGI_FORMAT_UNKNOWN);

    const uint64 elemSize = sizeof(T);
    Assert_(textureData.Texels.size() > 0);
    Assert_(textureData.Width * textureData.Height * textureData.NumSlices == textureData.Texels.size());

    std::vector<D3D11_SUBRESOURCE_DATA> subResources;
    subResources.resize(textureData.NumSlices);
    for(uint64 i = 0; i < textureData.NumSlices; ++i)
    {
        subResources[i].pSysMem = &textureData.Texels[textureData.Width * textureData.Height * i];
        subResources[i].SysMemPitch = elemSize * textureData.Width;
        subResources[i].SysMemSlicePitch = 0;
    }

    D3D11_TEXTURE2D_DESC texDesc;
    texDesc.Width = textureData.Width;
    texDesc.Height = textureData.Height;
    texDesc.MipLevels = 1;
    texDesc.ArraySize = textureData.NumSlices;
    texDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
    texDesc.SampleDesc.Count = 1;
    texDesc.SampleDesc.Quality = 0;
    texDesc.Usage = D3D11_USAGE_IMMUTABLE;
    texDesc.CPUAccessFlags = 0;
    texDesc.MiscFlags = 0;
    texDesc.Format = format;
    ID3D11Texture2DPtr texture;
    DXCall(device->CreateTexture2D(&texDesc, subResources.data(), &texture));

    ID3D11ShaderResourceViewPtr srv;
    DXCall(device->CreateShaderResourceView(texture, nullptr, &srv));

    return srv;
}

ID3D11ShaderResourceViewPtr CreateSRVFromTextureData(ID3D11Device* device, const TextureData<UByte4N>& textureData)
{
    return CreateSRVFromTextureData<UByte4N>(device, textureData);
}

ID3D11ShaderResourceViewPtr CreateSRVFromTextureData(ID3D11Device* device, const TextureData<Half4>& textureData)
{
    return CreateSRVFromTextureData<Half4>(device, textureData);
}

ID3D11ShaderResourceViewPtr CreateSRVFromTextureData(ID3D11Device* device, const TextureData<Float4>& textureData)
{
    return CreateSRVFromTextureData<Float4>(device, textureData);
}

void SaveTextureAsDDS(ID3D11ShaderResourceView* srv, const wchar* filePath)
{
    ID3D11ResourcePtr texture;
    srv->GetResource(&texture);

    SaveTextureAsDDS(texture, filePath);
}

void SaveTextureAsDDS(ID3D11Resource* texture, const wchar* filePath)
{
    ID3D11DevicePtr device;
    texture->GetDevice(&device);

    ID3D11DeviceContextPtr context;
    device->GetImmediateContext(&context);

    ScratchImage scratchImage;
    DXCall(CaptureTexture(device, context, texture, scratchImage));
    DXCall(SaveToDDSFile(scratchImage.GetImages(), scratchImage.GetImageCount(),
                         scratchImage.GetMetadata(), DDS_FLAGS_FORCE_DX10_EXT, filePath));
}

void SaveTextureAsEXR(ID3D11ShaderResourceView* srv, const wchar* filePath)
{
    ID3D11DevicePtr device;
    srv->GetDevice(&device);

    TextureData<Float4> textureData;
    GetTextureData(device, srv, textureData);

    SaveTextureAsEXR(textureData, filePath);
}

void SaveTextureAsEXR(const TextureData<Float4>& texture, const wchar* filePath)
{
    Assert_(texture.Texels.size() > 0);
    Assert_(texture.Width > 0 && texture.Height > 0);
    Assert_(texture.NumSlices == 1);

    const uint64 numTexels = texture.Texels.size();
    std::vector<float> channelDataR;
    std::vector<float> channelDataG;
    std::vector<float> channelDataB;
    channelDataR.resize(numTexels);
    channelDataG.resize(numTexels);
    channelDataB.resize(numTexels);
    for(uint64 i = 0; i < numTexels; ++i)
    {
        channelDataR[i] = texture.Texels[i].x;
        channelDataG[i] = texture.Texels[i].y;
        channelDataB[i] = texture.Texels[i].z;
    }

    float* imageChannels[3] = { channelDataB.data(), channelDataG.data(), channelDataR.data() };
    const char* channelNames[3] = { "B", "G", "R" };

    EXRImage exrImage;
    exrImage.num_channels = 3;
    exrImage.width = texture.Width;
    exrImage.height = texture.Height;
    exrImage.channel_names = channelNames;
    exrImage.images = imageChannels;

    std::string filePathAnsi = WStringToAnsi(filePath);

    const char* errorString = nullptr;
    int returnCode = SaveMultiChannelEXR(&exrImage, filePathAnsi.c_str(), &errorString);
    if(returnCode != 0)
    {
        AssertFail_("%s", errorString);
        throw Exception(AnsiToWString(errorString));
    }
}

// Utility function to map a XY + Side coordinate to a direction vector
Float3 MapXYSToDirection(uint64 x, uint64 y, uint64 s, uint64 width, uint64 height)
{
    float u = ((x + 0.5f) / float(width)) * 2.0f - 1.0f;
    float v = ((y + 0.5f) / float(height)) * 2.0f - 1.0f;
    v *= -1.0f;

    Float3 dir = 0.0f;

    // +x, -x, +y, -y, +z, -z
    switch(s) {
    case 0:
        dir = Float3::Normalize(Float3(1.0f, v, -u));
        break;
    case 1:
        dir = Float3::Normalize(Float3(-1.0f, v, u));
        break;
    case 2:
        dir = Float3::Normalize(Float3(u, 1.0f, -v));
        break;
    case 3:
        dir = Float3::Normalize(Float3(u, -1.0f, v));
        break;
    case 4:
        dir = Float3::Normalize(Float3(u, v, 1.0f));
        break;
    case 5:
        dir = Float3::Normalize(Float3(-u, v, -1.0f));
        break;
    }

    return dir;
}

}
<|endoftext|>


<commit_before>/*

Copyright (c) 2003, Arvid Norberg
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 author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include <stdlib.h>
#include "libtorrent/session.hpp"
#include "libtorrent/alert_types.hpp"

void print_alert(libtorrent::alert const* a)
{
	using namespace libtorrent;

	if (alert_cast<portmap_error_alert>(a))
	{
		printf("%s","\x1b[32m");
	}
	else if (alert_cast<portmap_alert>(a))
	{
		printf("%s","\x1b[33m");
	}

	printf("[%s] %s\n", time_now_string(), a->message().c_str());
	printf("%s", "\x1b[0m");
}

int main(int argc, char* argv[])
{
	using namespace libtorrent;

	if (argc != 1)
	{
		fputs("usage: ./upnp_test\n", stderr);
		return 1;
	}

	session s;
	s.set_alert_mask(alert::port_mapping_notification);

	for (;;)
	{
		alert const* a = s.wait_for_alert(seconds(5));
		if (a == 0)
		{
			s.stop_upnp();
			break;
		}
		std::auto_ptr<alert> holder = s.pop_alert();
		print_alert(holder.get());
	}

	printf("\x1b[1m\n\n===================== done mapping. Now deleting mappings ========================\n\n\n\x1b[0m");

	for (;;)
	{
		alert const* a = s.wait_for_alert(seconds(5));
		if (a == 0) break;
		std::auto_ptr<alert> holder = s.pop_alert();
		print_alert(holder.get());
	}

	return 0;
}

<commit_msg>stop natpmp in test<commit_after>/*

Copyright (c) 2003, Arvid Norberg
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 author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include <stdlib.h>
#include "libtorrent/session.hpp"
#include "libtorrent/alert_types.hpp"

void print_alert(libtorrent::alert const* a)
{
	using namespace libtorrent;

	if (alert_cast<portmap_error_alert>(a))
	{
		printf("%s","\x1b[32m");
	}
	else if (alert_cast<portmap_alert>(a))
	{
		printf("%s","\x1b[33m");
	}

	printf("[%s] %s\n", time_now_string(), a->message().c_str());
	printf("%s", "\x1b[0m");
}

int main(int argc, char* argv[])
{
	using namespace libtorrent;

	if (argc != 1)
	{
		fputs("usage: ./upnp_test\n", stderr);
		return 1;
	}

	session s;
	s.set_alert_mask(alert::port_mapping_notification);

	for (;;)
	{
		alert const* a = s.wait_for_alert(seconds(5));
		if (a == 0)
		{
			s.stop_upnp();
			s.stop_natpmp();
			break;
		}
		std::auto_ptr<alert> holder = s.pop_alert();
		print_alert(holder.get());
	}

	printf("\x1b[1m\n\n===================== done mapping. Now deleting mappings ========================\n\n\n\x1b[0m");

	for (;;)
	{
		alert const* a = s.wait_for_alert(seconds(5));
		if (a == 0) break;
		std::auto_ptr<alert> holder = s.pop_alert();
		print_alert(holder.get());
	}

	return 0;
}

<|endoftext|>