<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/renderer/media/android/media_info_loader.h"

#include "base/bits.h"
#include "base/callback_helpers.h"
#include "base/metrics/histogram.h"
#include "third_party/WebKit/public/platform/WebURLError.h"
#include "third_party/WebKit/public/platform/WebURLLoader.h"
#include "third_party/WebKit/public/platform/WebURLResponse.h"
#include "third_party/WebKit/public/web/WebFrame.h"

using WebKit::WebFrame;
using WebKit::WebURLError;
using WebKit::WebURLLoader;
using WebKit::WebURLLoaderOptions;
using WebKit::WebURLRequest;
using WebKit::WebURLResponse;

namespace content {

static const int kHttpOK = 200;

MediaInfoLoader::MediaInfoLoader(
    const GURL& url,
    WebKit::WebMediaPlayer::CORSMode cors_mode,
    const ReadyCB& ready_cb)
    : loader_failed_(false),
      url_(url),
      cors_mode_(cors_mode),
      single_origin_(true),
      ready_cb_(ready_cb) {}

MediaInfoLoader::~MediaInfoLoader() {}

void MediaInfoLoader::Start(WebKit::WebFrame* frame) {
  // Make sure we have not started.
  DCHECK(!ready_cb_.is_null());
  CHECK(frame);

  start_time_ = base::TimeTicks::Now();

  // Prepare the request.
  WebURLRequest request(url_);
  request.setTargetType(WebURLRequest::TargetIsMedia);
  frame->setReferrerForRequest(request, WebKit::WebURL());

  scoped_ptr<WebURLLoader> loader;
  if (test_loader_) {
    loader = test_loader_.Pass();
  } else {
    WebURLLoaderOptions options;
    if (cors_mode_ == WebKit::WebMediaPlayer::CORSModeUnspecified) {
      options.allowCredentials = true;
      options.crossOriginRequestPolicy =
          WebURLLoaderOptions::CrossOriginRequestPolicyAllow;
    } else {
      options.exposeAllResponseHeaders = true;
      options.crossOriginRequestPolicy =
          WebURLLoaderOptions::CrossOriginRequestPolicyUseAccessControl;
      if (cors_mode_ == WebKit::WebMediaPlayer::CORSModeUseCredentials)
        options.allowCredentials = true;
    }
    loader.reset(frame->createAssociatedURLLoader(options));
  }

  // Start the resource loading.
  loader->loadAsynchronously(request, this);
  active_loader_.reset(new ActiveLoader(loader.Pass()));
}

/////////////////////////////////////////////////////////////////////////////
// WebKit::WebURLLoaderClient implementation.
void MediaInfoLoader::willSendRequest(
    WebURLLoader* loader,
    WebURLRequest& newRequest,
    const WebURLResponse& redirectResponse) {
  // The load may have been stopped and |ready_cb| is destroyed.
  // In this case we shouldn't do anything.
  if (ready_cb_.is_null()) {
    // Set the url in the request to an invalid value (empty url).
    newRequest.setURL(WebKit::WebURL());
    return;
  }

  // Only allow |single_origin_| if we haven't seen a different origin yet.
  if (single_origin_)
    single_origin_ = url_.GetOrigin() == GURL(newRequest.url()).GetOrigin();

  url_ = newRequest.url();
}

void MediaInfoLoader::didSendData(
    WebURLLoader* loader,
    unsigned long long bytes_sent,
    unsigned long long total_bytes_to_be_sent) {
  NOTIMPLEMENTED();
}

void MediaInfoLoader::didReceiveResponse(
    WebURLLoader* loader,
    const WebURLResponse& response) {
  DVLOG(1) << "didReceiveResponse: HTTP/"
           << (response.httpVersion() == WebURLResponse::HTTP_0_9 ? "0.9" :
               response.httpVersion() == WebURLResponse::HTTP_1_0 ? "1.0" :
               response.httpVersion() == WebURLResponse::HTTP_1_1 ? "1.1" :
               "Unknown")
           << " " << response.httpStatusCode();
  DCHECK(active_loader_.get());
  if (response.httpStatusCode() == kHttpOK) {
    DidBecomeReady(kOk);
    return;
  }
  loader_failed_ = true;
  DidBecomeReady(kFailed);
}

void MediaInfoLoader::didReceiveData(
    WebURLLoader* loader,
    const char* data,
    int data_length,
    int encoded_data_length) {
  // Ignored.
}

void MediaInfoLoader::didDownloadData(
    WebKit::WebURLLoader* loader,
    int dataLength) {
  NOTIMPLEMENTED();
}

void MediaInfoLoader::didReceiveCachedMetadata(
    WebURLLoader* loader,
    const char* data,
    int data_length) {
  NOTIMPLEMENTED();
}

void MediaInfoLoader::didFinishLoading(
    WebURLLoader* loader,
    double finishTime) {
  DCHECK(active_loader_.get());
  DidBecomeReady(kOk);
}

void MediaInfoLoader::didFail(
    WebURLLoader* loader,
    const WebURLError& error) {
  DVLOG(1) << "didFail: reason=" << error.reason
           << ", isCancellation=" << error.isCancellation
           << ", domain=" << error.domain.utf8().data()
           << ", localizedDescription="
           << error.localizedDescription.utf8().data();
  DCHECK(active_loader_.get());
  loader_failed_ = true;
  DidBecomeReady(kFailed);
}

bool MediaInfoLoader::HasSingleOrigin() const {
  DCHECK(ready_cb_.is_null())
      << "Must become ready before calling HasSingleOrigin()";
  return single_origin_;
}

bool MediaInfoLoader::DidPassCORSAccessCheck() const {
  DCHECK(ready_cb_.is_null())
      << "Must become ready before calling DidPassCORSAccessCheck()";
  return !loader_failed_ &&
      cors_mode_ != WebKit::WebMediaPlayer::CORSModeUnspecified;
}

/////////////////////////////////////////////////////////////////////////////
// Helper methods.

void MediaInfoLoader::DidBecomeReady(Status status) {
  UMA_HISTOGRAM_TIMES("Media.InfoLoadDelay",
                      base::TimeTicks::Now() - start_time_);
  active_loader_.reset();
  if (!ready_cb_.is_null())
    base::ResetAndReturn(&ready_cb_).Run(status);
}

}  // namespace content
<commit_msg>[Android] Fix the issue of ContentShell can't play video with file scheme.<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/renderer/media/android/media_info_loader.h"

#include "base/bits.h"
#include "base/callback_helpers.h"
#include "base/metrics/histogram.h"
#include "third_party/WebKit/public/platform/WebURLError.h"
#include "third_party/WebKit/public/platform/WebURLLoader.h"
#include "third_party/WebKit/public/platform/WebURLResponse.h"
#include "third_party/WebKit/public/web/WebFrame.h"

using WebKit::WebFrame;
using WebKit::WebURLError;
using WebKit::WebURLLoader;
using WebKit::WebURLLoaderOptions;
using WebKit::WebURLRequest;
using WebKit::WebURLResponse;

namespace content {

static const int kHttpOK = 200;

MediaInfoLoader::MediaInfoLoader(
    const GURL& url,
    WebKit::WebMediaPlayer::CORSMode cors_mode,
    const ReadyCB& ready_cb)
    : loader_failed_(false),
      url_(url),
      cors_mode_(cors_mode),
      single_origin_(true),
      ready_cb_(ready_cb) {}

MediaInfoLoader::~MediaInfoLoader() {}

void MediaInfoLoader::Start(WebKit::WebFrame* frame) {
  // Make sure we have not started.
  DCHECK(!ready_cb_.is_null());
  CHECK(frame);

  start_time_ = base::TimeTicks::Now();

  // Prepare the request.
  WebURLRequest request(url_);
  request.setTargetType(WebURLRequest::TargetIsMedia);
  frame->setReferrerForRequest(request, WebKit::WebURL());

  scoped_ptr<WebURLLoader> loader;
  if (test_loader_) {
    loader = test_loader_.Pass();
  } else {
    WebURLLoaderOptions options;
    if (cors_mode_ == WebKit::WebMediaPlayer::CORSModeUnspecified) {
      options.allowCredentials = true;
      options.crossOriginRequestPolicy =
          WebURLLoaderOptions::CrossOriginRequestPolicyAllow;
    } else {
      options.exposeAllResponseHeaders = true;
      options.crossOriginRequestPolicy =
          WebURLLoaderOptions::CrossOriginRequestPolicyUseAccessControl;
      if (cors_mode_ == WebKit::WebMediaPlayer::CORSModeUseCredentials)
        options.allowCredentials = true;
    }
    loader.reset(frame->createAssociatedURLLoader(options));
  }

  // Start the resource loading.
  loader->loadAsynchronously(request, this);
  active_loader_.reset(new ActiveLoader(loader.Pass()));
}

/////////////////////////////////////////////////////////////////////////////
// WebKit::WebURLLoaderClient implementation.
void MediaInfoLoader::willSendRequest(
    WebURLLoader* loader,
    WebURLRequest& newRequest,
    const WebURLResponse& redirectResponse) {
  // The load may have been stopped and |ready_cb| is destroyed.
  // In this case we shouldn't do anything.
  if (ready_cb_.is_null()) {
    // Set the url in the request to an invalid value (empty url).
    newRequest.setURL(WebKit::WebURL());
    return;
  }

  // Only allow |single_origin_| if we haven't seen a different origin yet.
  if (single_origin_)
    single_origin_ = url_.GetOrigin() == GURL(newRequest.url()).GetOrigin();

  url_ = newRequest.url();
}

void MediaInfoLoader::didSendData(
    WebURLLoader* loader,
    unsigned long long bytes_sent,
    unsigned long long total_bytes_to_be_sent) {
  NOTIMPLEMENTED();
}

void MediaInfoLoader::didReceiveResponse(
    WebURLLoader* loader,
    const WebURLResponse& response) {
  DVLOG(1) << "didReceiveResponse: HTTP/"
           << (response.httpVersion() == WebURLResponse::HTTP_0_9 ? "0.9" :
               response.httpVersion() == WebURLResponse::HTTP_1_0 ? "1.0" :
               response.httpVersion() == WebURLResponse::HTTP_1_1 ? "1.1" :
               "Unknown")
           << " " << response.httpStatusCode();
  DCHECK(active_loader_.get());
  if (response.httpStatusCode() == kHttpOK || url_.SchemeIsFile()) {
    DidBecomeReady(kOk);
    return;
  }
  loader_failed_ = true;
  DidBecomeReady(kFailed);
}

void MediaInfoLoader::didReceiveData(
    WebURLLoader* loader,
    const char* data,
    int data_length,
    int encoded_data_length) {
  // Ignored.
}

void MediaInfoLoader::didDownloadData(
    WebKit::WebURLLoader* loader,
    int dataLength) {
  NOTIMPLEMENTED();
}

void MediaInfoLoader::didReceiveCachedMetadata(
    WebURLLoader* loader,
    const char* data,
    int data_length) {
  NOTIMPLEMENTED();
}

void MediaInfoLoader::didFinishLoading(
    WebURLLoader* loader,
    double finishTime) {
  DCHECK(active_loader_.get());
  DidBecomeReady(kOk);
}

void MediaInfoLoader::didFail(
    WebURLLoader* loader,
    const WebURLError& error) {
  DVLOG(1) << "didFail: reason=" << error.reason
           << ", isCancellation=" << error.isCancellation
           << ", domain=" << error.domain.utf8().data()
           << ", localizedDescription="
           << error.localizedDescription.utf8().data();
  DCHECK(active_loader_.get());
  loader_failed_ = true;
  DidBecomeReady(kFailed);
}

bool MediaInfoLoader::HasSingleOrigin() const {
  DCHECK(ready_cb_.is_null())
      << "Must become ready before calling HasSingleOrigin()";
  return single_origin_;
}

bool MediaInfoLoader::DidPassCORSAccessCheck() const {
  DCHECK(ready_cb_.is_null())
      << "Must become ready before calling DidPassCORSAccessCheck()";
  return !loader_failed_ &&
      cors_mode_ != WebKit::WebMediaPlayer::CORSModeUnspecified;
}

/////////////////////////////////////////////////////////////////////////////
// Helper methods.

void MediaInfoLoader::DidBecomeReady(Status status) {
  UMA_HISTOGRAM_TIMES("Media.InfoLoadDelay",
                      base::TimeTicks::Now() - start_time_);
  active_loader_.reset();
  if (!ready_cb_.is_null())
    base::ResetAndReturn(&ready_cb_).Run(status);
}

}  // namespace content
<|endoftext|>


<commit_before>#ifndef WIN32

//===--- TerminalConfigUnix.cpp - termios storage -------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// TerminalReader and TerminalDisplay need to reset the terminal configuration
// upon destruction, to leave the terminal as before. To avoid a possible
// misunderstanding of what "before" means, centralize their storage of the
// previous termios and have them share it.
//
//  Axel Naumann <axel@cern.ch>, 2011-05-12
//===----------------------------------------------------------------------===//

#include "textinput/TerminalConfigUnix.h"

#include <termios.h>
#include <unistd.h>
#include <stdio.h>
#include <cstring>

using namespace textinput;
using std::memcpy;

void
TerminalConfigUnix__handleAbortSignal(int signum) {
  // Clean up before we are killed.
  TerminalConfigUnix::Get().HandleAbortSignal(signum);

}

TerminalConfigUnix&
TerminalConfigUnix::Get() {
  static TerminalConfigUnix s;
  return s;
}

TerminalConfigUnix::TerminalConfigUnix():
  fIsAttached(false), fFD(fileno(stdin)), fOldTIOS(), fConfTIOS() {
#ifdef TCSANOW
  fOldTIOS = new termios;
  fConfTIOS = new termios;
  tcgetattr(fFD, fOldTIOS);
  *fConfTIOS = *fOldTIOS;
#endif
  fPrevAbortHandler = signal(SIGABRT, TerminalConfigUnix__handleAbortSignal);
}

TerminalConfigUnix::~TerminalConfigUnix() {
  Detach();
  delete fOldTIOS;
  delete fConfTIOS;
}

void
TerminalConfigUnix::HandleAbortSignal(int signum) {
  Detach();
  if (fPrevAbortHandler) fPrevAbortHandler(signum);
}

void
TerminalConfigUnix::Attach() {
  if (fIsAttached) return;
#ifdef TCSANOW
  tcsetattr(fFD, TCSANOW, fConfTIOS);
#endif
  fIsAttached = true;
}

void
TerminalConfigUnix::Detach() {
  // Reset the terminal configuration.
  if (!fIsAttached) return;
#ifdef TCSANOW
  tcsetattr(fFD, TCSANOW, fOldTIOS);
#endif
  fIsAttached = false;
}

#endif // ndef WIN32
<commit_msg>Solaris puts signal only into std::.<commit_after>#ifndef WIN32

//===--- TerminalConfigUnix.cpp - termios storage -------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// TerminalReader and TerminalDisplay need to reset the terminal configuration
// upon destruction, to leave the terminal as before. To avoid a possible
// misunderstanding of what "before" means, centralize their storage of the
// previous termios and have them share it.
//
//  Axel Naumann <axel@cern.ch>, 2011-05-12
//===----------------------------------------------------------------------===//

#include "textinput/TerminalConfigUnix.h"

#include <termios.h>
#include <unistd.h>
#include <stdio.h>
#include <cstring>

using namespace textinput;
using std::memcpy;
using std::signal;

void
TerminalConfigUnix__handleAbortSignal(int signum) {
  // Clean up before we are killed.
  TerminalConfigUnix::Get().HandleAbortSignal(signum);

}

TerminalConfigUnix&
TerminalConfigUnix::Get() {
  static TerminalConfigUnix s;
  return s;
}

TerminalConfigUnix::TerminalConfigUnix():
  fIsAttached(false), fFD(fileno(stdin)), fOldTIOS(), fConfTIOS() {
#ifdef TCSANOW
  fOldTIOS = new termios;
  fConfTIOS = new termios;
  tcgetattr(fFD, fOldTIOS);
  *fConfTIOS = *fOldTIOS;
#endif
  fPrevAbortHandler = signal(SIGABRT, TerminalConfigUnix__handleAbortSignal);
}

TerminalConfigUnix::~TerminalConfigUnix() {
  Detach();
  delete fOldTIOS;
  delete fConfTIOS;
}

void
TerminalConfigUnix::HandleAbortSignal(int signum) {
  Detach();
  if (fPrevAbortHandler) fPrevAbortHandler(signum);
}

void
TerminalConfigUnix::Attach() {
  if (fIsAttached) return;
#ifdef TCSANOW
  tcsetattr(fFD, TCSANOW, fConfTIOS);
#endif
  fIsAttached = true;
}

void
TerminalConfigUnix::Detach() {
  // Reset the terminal configuration.
  if (!fIsAttached) return;
#ifdef TCSANOW
  tcsetattr(fFD, TCSANOW, fOldTIOS);
#endif
  fIsAttached = false;
}

#endif // ndef WIN32
<|endoftext|>


<commit_before>#include <stdio.h>
#include <iostream>
#include "Eigen/Dense"
#include "gtest/gtest.h"
#include "include/cpu_operations.h"
#include "include/matrix.h"

template<class T>
class MatrixSubtractTest : public ::testing::Test {
 public:
  Nice::Matrix<T> m1;
  Nice::Matrix<T> m2;
  Nice::Matrix<T> result;
  Nice::Matrix<T> testMatrix;

  void MatrixSubtract() {
    result = Nice::CpuOperations<T>::Subtract(m1, m2);
  }
};

typedef ::testing::Types<int, double, float> MyTypes;
TYPED_TEST_CASE(MatrixSubtractTest, MyTypes);

TYPED_TEST(MatrixSubtractTest, MatrixSubtractFunctionality) {
  this->m1.resize(2,2);
  this->m2.resize(2,2);
 // this->result.resize(2,2);
  this->testMatrix.resize(2,2);
  this->m1 << 2, 3,
              4, 5;
  this->m2 << 1, 2,
              3, 2;
  this->MatrixSubtract();
  this->testMatrix << 1, 1,
                      1, 3;
  ASSERT_TRUE(this->result.isApprox(this->testMatrix));
}

TYPED_TEST(MatrixSubtractTest, DifferentSizeMatrix) {
  this->m1.resize(2,2);
  this->m2.resize(3,2);
  this->m1.setZero();
  this->m2.setZero();
  ASSERT_DEATH(this->MatrixSubtract(), ".*");
}

TYPED_TEST(MatrixSubtractTest, EmptyMatrix) {
  ASSERT_DEATH(this->MatrixSubtract(), ".*");
}
<commit_msg>Code style update<commit_after>// The MIT License (MIT)
//
// Copyright (c) 2016 Northeastern University
//
// 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.

#include <stdio.h>
#include <iostream>
#include "Eigen/Dense"
#include "gtest/gtest.h"
#include "include/cpu_operations.h"
#include "include/matrix.h"

template<class T>
class MatrixSubtractTest : public ::testing::Test {
 public:
  Nice::Matrix<T> m1;
  Nice::Matrix<T> m2;
  Nice::Matrix<T> result;
  Nice::Matrix<T> testMatrix;

  void MatrixSubtract() {
    result = Nice::CpuOperations<T>::Subtract(m1, m2);
  }
};

typedef ::testing::Types<int, double, float> MyTypes;
TYPED_TEST_CASE(MatrixSubtractTest, MyTypes);

TYPED_TEST(MatrixSubtractTest, MatrixSubtractFunctionality) {
  this->m1.resize(2, 2);
  this->m2.resize(2, 2);
  this->testMatrix.resize(2, 2);
  this->m1 << 2, 3,
              4, 5;
  this->m2 << 1, 2,
              3, 2;
  this->MatrixSubtract();
  this->testMatrix << 1, 1,
                      1, 3;
  ASSERT_TRUE(this->result.isApprox(this->testMatrix));
}

TYPED_TEST(MatrixSubtractTest, DifferentSizeMatrix) {
  this->m1.resize(2, 2);
  this->m2.resize(3, 2);
  this->m1.setZero();
  this->m2.setZero();
  ASSERT_DEATH(this->MatrixSubtract(), ".*");
}

TYPED_TEST(MatrixSubtractTest, EmptyMatrix) {
  ASSERT_DEATH(this->MatrixSubtract(), ".*");
}
<|endoftext|>


<commit_before>#include "../../../include/stupid/internal/macros.hpp"

Q_LOGGING_CATEGORY(cutehmi_stupid_0_lib_loggingCategory, "cutehmi.stupid.0.lib")

//(c)MP: Copyright © 2017, Michal Policht. All rights reserved.
//(c)MP: This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
<commit_msg>Fix logging category name.<commit_after>#include "../../../include/stupid/internal/macros.hpp"

Q_LOGGING_CATEGORY(cutehmi_stupid_1_lib_loggingCategory, "cutehmi_stupid_1_lib")

//(c)MP: Copyright © 2017, Michal Policht. All rights reserved.
//(c)MP: This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
<|endoftext|>


<commit_before>//
//  yas_audio_rendering_graph.cpp
//

#include "yas_audio_rendering_graph.h"

#include <audio/yas_audio_graph_connection.h>
#include <audio/yas_audio_graph_node.h>
#include <cpp_utils/yas_stl_utils.h>

using namespace yas;

namespace yas::audio {

std::vector<std::unique_ptr<rendering_node>> make_rendering_nodes(renderable_graph_node_ptr const &node) {
    std::vector<std::unique_ptr<rendering_node>> sub_nodes;
    rendering_connection_map connections;

    for (auto const &pair : node->input_connections()) {
        uint32_t const dst_bus_idx = pair.first;
        graph_connection_ptr const connection = pair.second.lock();
        renderable_graph_node_ptr const src_node = connection->source_node();

        std::vector<std::unique_ptr<rendering_node>> src_rendering_nodes = make_rendering_nodes(src_node);

        connections.emplace(dst_bus_idx, rendering_connection{connection->source_bus(), src_rendering_nodes.at(0).get(),
                                                              connection->format()});

        yas::move_back_insert(sub_nodes, std::move(src_rendering_nodes));
    }

    std::vector<std::unique_ptr<rendering_node>> result;
    result.emplace_back(std::make_unique<rendering_node>(node->render_handler(), std::move(connections)));

    if (!sub_nodes.empty()) {
        yas::move_back_insert(result, std::move(sub_nodes));
    }

    return result;
}
}  // namespace yas::audio

audio::rendering_graph::rendering_graph(renderable_graph_node_ptr const &end_node)
    : nodes(make_rendering_nodes(end_node)) {
}
<commit_msg>use renderable_graph_connection_ptr<commit_after>//
//  yas_audio_rendering_graph.cpp
//

#include "yas_audio_rendering_graph.h"

#include <audio/yas_audio_graph_connection.h>
#include <audio/yas_audio_graph_node.h>
#include <cpp_utils/yas_stl_utils.h>

using namespace yas;

namespace yas::audio {

std::vector<std::unique_ptr<rendering_node>> make_rendering_nodes(renderable_graph_node_ptr const &node) {
    std::vector<std::unique_ptr<rendering_node>> sub_nodes;
    rendering_connection_map connections;

    for (auto const &pair : node->input_connections()) {
        uint32_t const dst_bus_idx = pair.first;
        renderable_graph_connection_ptr const connection = pair.second.lock();
        renderable_graph_node_ptr const src_node = connection->source_node();

        std::vector<std::unique_ptr<rendering_node>> src_rendering_nodes = make_rendering_nodes(src_node);

        connections.emplace(dst_bus_idx, rendering_connection{connection->source_bus(), src_rendering_nodes.at(0).get(),
                                                              connection->format()});

        yas::move_back_insert(sub_nodes, std::move(src_rendering_nodes));
    }

    std::vector<std::unique_ptr<rendering_node>> result;
    result.emplace_back(std::make_unique<rendering_node>(node->render_handler(), std::move(connections)));

    if (!sub_nodes.empty()) {
        yas::move_back_insert(result, std::move(sub_nodes));
    }

    return result;
}
}  // namespace yas::audio

audio::rendering_graph::rendering_graph(renderable_graph_node_ptr const &end_node)
    : nodes(make_rendering_nodes(end_node)) {
}
<|endoftext|>


<commit_before>//! [class-defn]
#include <memory>

#include <QApplication>
#include <QGuiApplication>

#include "QtWidgets/qwidget.h"

#include "Qt3D/qglview.h"
#include "Qt3D/qglscenenode.h"
#include "Qt3D/qglbuilder.h"
#include "Qt3D/qglteapot.h"

class TeapotView : public QGLView
{
    Q_OBJECT
public:
    TeapotView(QWindow *parent = 0)
        : QGLView(parent),
        teapot(nullptr)
    {}
    ~TeapotView();

protected:
    void initializeGL(QGLPainter *painter);
    void paintGL(QGLPainter *painter);

private:
    std::unique_ptr<QGLSceneNode> teapot;
};
//! [class-defn]

//! [initialize]
void TeapotView::initializeGL(QGLPainter *painter)
{
    painter->setStandardEffect(QGL::LitMaterial);
//! [build-geometry]
    QGLBuilder builder;
    builder << QGLTeapot();
    auto scene = builder.finalizedSceneNode();
    teapot.reset(scene);
}
//! [initialize]

//! [destructor]
TeapotView::~TeapotView()
{
}
//! [destructor]

//! [paint]
void TeapotView::paintGL(QGLPainter *painter)
{
    teapot->draw(painter);
}
//! [paint]

int mainQ3D(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    TeapotView view;

    view.setTitle("Pure Q3D!");
    view.resize(800, 600);
    view.show();

    return app.exec();
}

int mainQ3DWidget(int argc, char *argv[])
{
    QApplication app(argc, argv);
    TeapotView view;

    // ownership is still at view! so don't delete the 'teapot' pointer!
    QWidget* teapot(QWidget::createWindowContainer(&view));
    teapot->setWindowTitle("Q3D as a QWidget!");
    teapot->resize(800, 600);
    teapot->show();

    return app.exec();
}

//! [main]
int main(int argc, char *argv[]) {
    //return mainQ3DWidget(argc, argv);
    return mainQ3D(argc, argv);
}
//! [main]<commit_msg>included missing include of the corresponding moc file (i don't really understand the technique Qt uses)<commit_after>//! [class-defn]
#include <memory>

#include <QApplication>
#include <QGuiApplication>

#include "QtWidgets/qwidget.h"

#include "Qt3D/qglview.h"
#include "Qt3D/qglscenenode.h"
#include "Qt3D/qglbuilder.h"
#include "Qt3D/qglteapot.h"

class TeapotView : public QGLView
{
    Q_OBJECT
public:
    TeapotView(QWindow *parent = 0)
        : QGLView(parent),
        teapot(nullptr)
    {}
    ~TeapotView();

protected:
    void initializeGL(QGLPainter *painter);
    void paintGL(QGLPainter *painter);

private:
    std::unique_ptr<QGLSceneNode> teapot;
};
//! [class-defn]

//! [initialize]
void TeapotView::initializeGL(QGLPainter *painter)
{
    painter->setStandardEffect(QGL::LitMaterial);
//! [build-geometry]
    QGLBuilder builder;
    builder << QGLTeapot();
    auto scene = builder.finalizedSceneNode();
    teapot.reset(scene);
}
//! [initialize]

//! [destructor]
TeapotView::~TeapotView()
{
}
//! [destructor]

//! [paint]
void TeapotView::paintGL(QGLPainter *painter)
{
    teapot->draw(painter);
}
//! [paint]

int mainQ3D(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    TeapotView view;

    view.setTitle("Pure Q3D!");
    view.resize(800, 600);
    view.show();

    return app.exec();
}

int mainQ3DWidget(int argc, char *argv[])
{
    QApplication app(argc, argv);
    TeapotView view;

    // ownership is still at view! so don't delete the 'teapot' pointer!
    QWidget* teapot(QWidget::createWindowContainer(&view));
    teapot->setWindowTitle("Q3D as a QWidget!");
    teapot->resize(800, 600);
    teapot->show();

    return app.exec();
}

//! [main]
int main(int argc, char *argv[]) {
    //return mainQ3DWidget(argc, argv);
    return mainQ3D(argc, argv);
}
//! [main]

#include "dummy.moc"<|endoftext|>


<commit_before>#include <QtGui>

#include "editorviewmviface.h"

#include "editorview.h"
#include "editorviewscene.h"

#include "realreporoles.h"

#include "../umllib/uml_element.h"
#include "../umllib/uml_guiobjectfactory.h"

EditorViewMViface::EditorViewMViface(EditorView *view, EditorViewScene *scene)
	: QAbstractItemView(0)
{
	this->view = view;
	this->scene = scene;

	//    view->mv_iface = this;
	scene->mv_iface = this;
	scene->view = view;
}

QRect EditorViewMViface::visualRect(const QModelIndex &) const
{
	return QRect();
}

void EditorViewMViface::scrollTo(const QModelIndex &, ScrollHint)
{
}

QModelIndex EditorViewMViface::indexAt(const QPoint &) const
{
	return QModelIndex();
}

QModelIndex EditorViewMViface::moveCursor(QAbstractItemView::CursorAction,
		Qt::KeyboardModifiers)
{
	return QModelIndex();
}

int EditorViewMViface::horizontalOffset() const
{
	return 0;
}

int EditorViewMViface::verticalOffset() const
{
	return 0;
}

bool EditorViewMViface::isIndexHidden(const QModelIndex &) const
{
	return false;
}

void EditorViewMViface::setSelection(const QRect&, QItemSelectionModel::SelectionFlags )
{
}

QRegion EditorViewMViface::visualRegionForSelection(const QItemSelection &) const
{
	return QRegion();
}
/*
void EditorViewMViface::raiseClick ( const QGraphicsItem * item )
{
	const UML::Element *e = qgraphicsitem_cast<const UML::Element *>(item);
	if (e)
		emit clicked(e->index());
}
*/

UML::Element* EditorViewMViface::getItem(int uuid)
{
	return items[uuid];
}

void EditorViewMViface::reset()
{
	items.clear();
	scene->clearScene();

	// so that our diagram be nicer
	scene->removeItem(scene->addRect(QRect(-1000,-1000,2000,2000)));

	if ( model() )
		rowsInserted(rootIndex(), 0, model()->rowCount(rootIndex()) - 1 );
}

void EditorViewMViface::setRootIndex(const QModelIndex &index)
{
	QAbstractItemView::setRootIndex(index);
	reset();
}

void EditorViewMViface::rowsInserted ( const QModelIndex & parent, int start, int end )
{
	qDebug() << "========== rowsInserted";

//	if ( parent != rootIndex() )
//		return;
	if ( parent == QModelIndex() )
		return;

//	qDebug() << "rowsInserted: adding items" << parent;
	for (int row = start; row <= end; ++row) {
		QPersistentModelIndex current = model()->index(row, 0, parent);
		int uuid = model()->index(row, 0, parent).data(Unreal::IdRole).toInt();
		int type = model()->index(row, 0, parent).data(Unreal::TypeRole).toInt();

		int parent_uuid;
		if ( parent != rootIndex() )
				parent_uuid = parent.data(Unreal::IdRole).toInt();
		else
				parent_uuid = -1;

		qDebug() << uuid << type;

		if ( ! uuid )
			continue;

		if ( UML::Element *e = UML::GUIObjectFactory(type) ) {
			scene->addItem(e);
			e->setIndex(current);
			e->setPos(current.data(Unreal::PositionRole).toPointF());

			if ( parent_uuid != -1 )
				e->setParentItem(items[parent_uuid]);

			items[uuid] = e;
		}

		if ( model()->hasChildren(current) ) {
			rowsInserted( current, 0, model()->rowCount( current ) );
		}
	}

//	qDebug() << "rowsInserted: updating items";
	for (int row = start; row <= end; ++row) {
		int uuid = model()->index(row, 0, parent).data(Unreal::IdRole).toInt();
		if (items.contains(uuid))
			items[uuid]->updateData();
	}

	QAbstractItemView::rowsInserted(parent, start, end);
}

void EditorViewMViface::rowsAboutToBeRemoved ( const QModelIndex & parent, int start, int end )
{
	for (int row = start; row <= end; ++row) {
		int uuid = model()->index(row, 0, parent).data(Unreal::IdRole).toInt();

		scene->removeItem(items[uuid]);
		delete items[uuid];
		items.remove(uuid);
	}

	QAbstractItemView::rowsAboutToBeRemoved(parent, start, end);
}

void EditorViewMViface::dataChanged(const QModelIndex &topLeft,
		const QModelIndex &bottomRight)
{
	for (int row = topLeft.row(); row <= bottomRight.row(); ++row) {
		int uuid = topLeft.sibling(row, 0).data(Unreal::IdRole).toInt();

		if ( items.contains(uuid) )
			items[uuid]->updateData();
		else
			rowsInserted(topLeft.parent(),row,row);

	}
}

<commit_msg>Hujnja kakajato. (for english speakers: some weird shit)<commit_after>#include <QtGui>

#include "editorviewmviface.h"

#include "editorview.h"
#include "editorviewscene.h"

#include "realreporoles.h"

#include "../umllib/uml_element.h"
#include "../umllib/uml_guiobjectfactory.h"

EditorViewMViface::EditorViewMViface(EditorView *view, EditorViewScene *scene)
	: QAbstractItemView(0)
{
	this->view = view;
	this->scene = scene;

	//    view->mv_iface = this;
	scene->mv_iface = this;
	scene->view = view;
}

QRect EditorViewMViface::visualRect(const QModelIndex &) const
{
	return QRect();
}

void EditorViewMViface::scrollTo(const QModelIndex &, ScrollHint)
{
}

QModelIndex EditorViewMViface::indexAt(const QPoint &) const
{
	return QModelIndex();
}

QModelIndex EditorViewMViface::moveCursor(QAbstractItemView::CursorAction,
		Qt::KeyboardModifiers)
{
	return QModelIndex();
}

int EditorViewMViface::horizontalOffset() const
{
	return 0;
}

int EditorViewMViface::verticalOffset() const
{
	return 0;
}

bool EditorViewMViface::isIndexHidden(const QModelIndex &) const
{
	return false;
}

void EditorViewMViface::setSelection(const QRect&, QItemSelectionModel::SelectionFlags )
{
}

QRegion EditorViewMViface::visualRegionForSelection(const QItemSelection &) const
{
	return QRegion();
}
/*
void EditorViewMViface::raiseClick ( const QGraphicsItem * item )
{
	const UML::Element *e = qgraphicsitem_cast<const UML::Element *>(item);
	if (e)
		emit clicked(e->index());
}
*/

UML::Element* EditorViewMViface::getItem(int uuid)
{
	return items[uuid];
}

void EditorViewMViface::reset()
{
	items.clear();
	scene->clearScene();

	// so that our diagram be nicer
	scene->removeItem(scene->addRect(QRect(-1000,-1000,2000,2000)));

	if ( model() )
		rowsInserted(rootIndex(), 0, model()->rowCount(rootIndex()) - 1 );
}

void EditorViewMViface::setRootIndex(const QModelIndex &index)
{
	QAbstractItemView::setRootIndex(index);
	reset();
}

void EditorViewMViface::rowsInserted ( const QModelIndex & parent, int start, int end )
{
	qDebug() << "========== rowsInserted" << parent << start << end;

//	if ( parent != rootIndex() )
//		return;
	if ( parent == QModelIndex() )
		return;

//	qDebug() << "rowsInserted: adding items" << parent;
	for (int row = start; row <= end; ++row) {
		QPersistentModelIndex current = model()->index(row, 0, parent);
		int uuid = model()->index(row, 0, parent).data(Unreal::IdRole).toInt();
		int type = model()->index(row, 0, parent).data(Unreal::TypeRole).toInt();

		int parent_uuid;
		if ( parent != rootIndex() )
				parent_uuid = parent.data(Unreal::IdRole).toInt();
		else
				parent_uuid = -1;

		qDebug() << uuid << type;

		if ( ! uuid )
			continue;

		if ( UML::Element *e = UML::GUIObjectFactory(type) ) {
			scene->addItem(e);
			e->setIndex(current);
			e->setPos(current.data(Unreal::PositionRole).toPointF());

			if ( parent_uuid != -1 )
				e->setParentItem(items[parent_uuid]);

			items[uuid] = e;
		}

		if ( model()->hasChildren(current) ) {
			rowsInserted( current, 0, model()->rowCount( current ) - 1 );
		}
	}

	qDebug() << "rowsInserted: updating items";
	for (int row = start; row <= end; ++row) {
		int uuid = model()->index(row, 0, parent).data(Unreal::IdRole).toInt();
		if (items.contains(uuid))
			items[uuid]->updateData();
	}

	QAbstractItemView::rowsInserted(parent, start, end);
}

void EditorViewMViface::rowsAboutToBeRemoved ( const QModelIndex & parent, int start, int end )
{
	for (int row = start; row <= end; ++row) {
		int uuid = model()->index(row, 0, parent).data(Unreal::IdRole).toInt();

		scene->removeItem(items[uuid]);
		delete items[uuid];
		items.remove(uuid);
	}

	QAbstractItemView::rowsAboutToBeRemoved(parent, start, end);
}

void EditorViewMViface::dataChanged(const QModelIndex &topLeft,
		const QModelIndex &bottomRight)
{
	for (int row = topLeft.row(); row <= bottomRight.row(); ++row) {
		int uuid = topLeft.sibling(row, 0).data(Unreal::IdRole).toInt();

		if ( items.contains(uuid) )
			items[uuid]->updateData();
		else
			rowsInserted(topLeft.parent(),row,row);

	}
}

<|endoftext|>


<commit_before>#include <owlqn.h>

void OWLQN::optimize()
{
    // compute dir
    // compute grad
    while (_cur_iter < _max_iter)
    {
        _cur_iter ++;
        grad();
        dir();
        linearSearch();
        shift();
    }
}

void OWLQN::grad()
{
    model->grad(_w, *_data, _grad);
}

void OWLQN::dir()
{
    for (int i=0; i<_N; ++i)
    {
        _dir[i] = _grad[i];
    }
    // l1 so virtual grad
    if (_l1>0)
    {
        for (int i=0; i<_N; ++i)
        {
            if (_w[i] > MinDoubleValue)
            {
                _dir[i] = -1.0*(_grad[i] + _l1)
            }
            else if (_w[i] < -1.0*MinDoubleValue)
            {
                _dir[i] = -1.0*(_grad[i] - _l1)
            }
            else
            {
                double l_grad = _grad[i]-_l1;
                double r_grad = _grad[i]+_l1;
                if (r_grad < 0.0)
                {
                    _dir[i] = -1.0*r_grad;
                }
                else if (l_grad > 0.0)
                {
                    _dir[i] = -1.0*l_grad;
                }
                else
                {
                    _dir[i] = 0.0;
                }
            }
        }
        // check dir direction, same direction with -grad
        for (int i=0; i<_N; ++i)
        {
            if (_dir[i]*_grad[i] > 0.0)
            {
                _dir[i] = 0.0;
            }
        }
    }
    else
    {
        for (int i=0; i<_N; ++i)
        {
            _dir[i] = -1.0*_grad[i];
        }
    }
    // two loop lbfgs
    // Hk+1 = G-1
    // Hk+1 * yk = sk
    // Hk+1 = (I-sy'/s'y)*Hk*(I-ys'/s'y) + ss'/s'y
    // dir = -Hk+1*grad
    // one loop, compute q[i] =
    int i = _end;
    while(i != _start)
    {
        i = (i-1)%_M;
        _sy[i] = dot(_S[i], _Y[i]);
        _alpha[i] = dot(_S[i], _dir) / _sy[i];
        for (size_t k=0; k<_dir.size(); ++k)
        {
            _dir[k] -= _alpha[i]*_Y[i][k]
        }
    }
    // H0 = I*(s'y/y'y)
    i = (_end-1)%M;
    double yy = _sy[i]/dot(_Y[i], _Y[i]);
    for (size_t k=0; k<_dir.size(); ++k)
    {
        _dir[k] *= yy;
    }
    // second loop
    i = _start;
    while (i != _end)
    {
        _beta = dot(_Y[i], _dir) / _sy[i];
        for (size_t k=0; k<_dir.size(); ++k)
        {
            _dir[k] -= _S[i][k]*(_beta + _alpha[i]);
        }
        i = (i+1)%M;
    }
}

void OWLQN::linearSearch()
{
    // check is _dir down dir
    double res = 0.0;
}

void OWLQN::shift()
{
    for (size_t k=0; k<_w.size(); ++i)
    {
        _S[_end][k] = _next_w[k] - _w[k];
        _Y[_end][k] = _next_grad[k] - _grad[k];
    }
    _end = (_end+1) % M;
    if (_cur_iter > M)
    {
        _start = (_start+1) % M;
    }
}

double OWLQN::dot(vector<double> x, vector<double> y)
{
    if (x.size() != y.size())
    {
        return 0.0;
    }
    double value = 0.0;
    for (size_t i=0; i<x.size(); ++i)
    {
        value += x[i]*y[i];
    }
    return value;
}<commit_msg>modify some<commit_after>#include <owlqn.h>

void OWLQN::optimize()
{
    // compute dir
    // compute grad
    while (_cur_iter < _max_iter)
    {
        _cur_iter ++;
        grad();
        dir();
        linearSearch();
        shift();
    }
}

void OWLQN::grad()
{
    model->grad(_w, *_data, _grad);
}

void OWLQN::dir()
{
    for (int i=0; i<_N; ++i)
    {
        _dir[i] = _grad[i];
    }
    // l1 so virtual grad
    if (_l1>0)
    {
        for (int i=0; i<_N; ++i)
        {
            if (_w[i] > MinDoubleValue)
            {
                _dir[i] = -1.0*(_grad[i] + _l1)
            }
            else if (_w[i] < -1.0*MinDoubleValue)
            {
                _dir[i] = -1.0*(_grad[i] - _l1)
            }
            else
            {
                double l_grad = _grad[i]-_l1;
                double r_grad = _grad[i]+_l1;
                if (r_grad < 0.0)
                {
                    _dir[i] = -1.0*r_grad;
                }
                else if (l_grad > 0.0)
                {
                    _dir[i] = -1.0*l_grad;
                }
                else
                {
                    _dir[i] = 0.0;
                }
            }
        }
    }
    else
    {
        for (int i=0; i<_N; ++i)
        {
            _dir[i] = -1.0*_grad[i];
        }
    }
    // two loop lbfgs
    // Hk+1 = G-1
    // Hk+1 * yk = sk
    // Hk+1 = (I-sy'/s'y)*Hk*(I-ys'/s'y) + ss'/s'y
    // dir = -Hk+1*grad
    // one loop, compute q[i] =
    int i = _end;
    while(i != _start)
    {
        i = (i-1)%_M;
        _sy[i] = dot(_S[i], _Y[i]);
        _alpha[i] = dot(_S[i], _dir) / _sy[i];
        for (size_t k=0; k<_dir.size(); ++k)
        {
            _dir[k] -= _alpha[i]*_Y[i][k]
        }
    }
    // H0 = I*(s'y/y'y)
    i = (_end-1)%M;
    double yy = _sy[i]/dot(_Y[i], _Y[i]);
    for (size_t k=0; k<_dir.size(); ++k)
    {
        _dir[k] *= yy;
    }
    // second loop
    i = _start;
    while (i != _end)
    {
        _beta = dot(_Y[i], _dir) / _sy[i];
        for (size_t k=0; k<_dir.size(); ++k)
        {
            _dir[k] -= _S[i][k]*(_beta + _alpha[i]);
        }
        i = (i+1)%M;
    }
    // fix dir sign
    // check dir direction, same direction with l1 grad
    for (int i=0; i<_N; ++i)
    {
        if (_dir[i]*_grad[i] > 0.0)
        {
            _dir[i] = 0.0;
        }
    }
}

void OWLQN::linearSearch()
{
    // check is _dir down dir, so Hk+1 should be positive
    // l1grad * _dir should be less than 0
    double res = 0.0;
}

void OWLQN::shift()
{
    for (size_t k=0; k<_w.size(); ++i)
    {
        _S[_end][k] = _next_w[k] - _w[k];
        _Y[_end][k] = _next_grad[k] - _grad[k];
    }
    _end = (_end+1) % M;
    if (_cur_iter > M)
    {
        _start = (_start+1) % M;
    }
}

double OWLQN::dot(vector<double> x, vector<double> y)
{
    if (x.size() != y.size())
    {
        return 0.0;
    }
    double value = 0.0;
    for (size_t i=0; i<x.size(); ++i)
    {
        value += x[i]*y[i];
    }
    return value;
}<|endoftext|>


<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "build/build_config.h"
#include "cc/layers/solid_color_layer.h"
#include "cc/test/layer_tree_pixel_test.h"
#include "cc/test/pixel_comparator.h"

#if !defined(OS_ANDROID)

namespace cc {
namespace {

class LayerTreeHostFiltersPixelTest : public LayerTreePixelTest {};

TEST_F(LayerTreeHostFiltersPixelTest, BackgroundFilterBlur) {
  scoped_refptr<SolidColorLayer> background = CreateSolidColorLayer(
      gfx::Rect(200, 200), SK_ColorWHITE);

  // The green box is entirely behind a layer with background blur, so it
  // should appear blurred on its edges.
  scoped_refptr<SolidColorLayer> green = CreateSolidColorLayer(
      gfx::Rect(50, 50, 100, 100), kCSSGreen);
  scoped_refptr<SolidColorLayer> blur = CreateSolidColorLayer(
      gfx::Rect(30, 30, 140, 140), SK_ColorTRANSPARENT);
  background->AddChild(green);
  background->AddChild(blur);

  FilterOperations filters;
  filters.Append(FilterOperation::CreateBlurFilter(2.f));
  blur->SetBackgroundFilters(filters);

#if defined(OS_WIN)
  // Windows has 436 pixels off by 1: crbug.com/259915
  float percentage_pixels_large_error = 1.09f;  // 436px / (200*200)
  float percentage_pixels_small_error = 0.0f;
  float average_error_allowed_in_bad_pixels = 1.f;
  int large_error_allowed = 1;
  int small_error_allowed = 0;
  pixel_comparator_.reset(new FuzzyPixelComparator(
      true,  // discard_alpha
      percentage_pixels_large_error,
      percentage_pixels_small_error,
      average_error_allowed_in_bad_pixels,
      large_error_allowed,
      small_error_allowed));
#endif

  RunPixelTest(GL_WITH_BITMAP,
               background,
               base::FilePath(FILE_PATH_LITERAL("background_filter_blur.png")));
}

TEST_F(LayerTreeHostFiltersPixelTest, BackgroundFilterBlurOutsets) {
  scoped_refptr<SolidColorLayer> background = CreateSolidColorLayer(
      gfx::Rect(200, 200), SK_ColorWHITE);

  // The green border is outside the layer with background blur, but the
  // background blur should use pixels from outside its layer borders, up to the
  // radius of the blur effect. So the border should be blurred underneath the
  // top layer causing the green to bleed under the transparent layer, but not
  // in the 1px region between the transparent layer and the green border.
  scoped_refptr<SolidColorLayer> green_border = CreateSolidColorLayerWithBorder(
      gfx::Rect(1, 1, 198, 198), SK_ColorWHITE, 10, kCSSGreen);
  scoped_refptr<SolidColorLayer> blur = CreateSolidColorLayer(
      gfx::Rect(12, 12, 176, 176), SK_ColorTRANSPARENT);
  background->AddChild(green_border);
  background->AddChild(blur);

  FilterOperations filters;
  filters.Append(FilterOperation::CreateBlurFilter(5.f));
  blur->SetBackgroundFilters(filters);

#if defined(OS_WIN)
  // Windows has 2596 pixels off by at most 2: crbug.com/259922
  float percentage_pixels_large_error = 6.49f;  // 2596px / (200*200)
  float percentage_pixels_small_error = 0.0f;
  float average_error_allowed_in_bad_pixels = 1.f;
  int large_error_allowed = 2;
  int small_error_allowed = 0;
  pixel_comparator_.reset(new FuzzyPixelComparator(
      true,  // discard_alpha
      percentage_pixels_large_error,
      percentage_pixels_small_error,
      average_error_allowed_in_bad_pixels,
      large_error_allowed,
      small_error_allowed));
#endif

  RunPixelTest(GL_WITH_BITMAP,
               background,
               base::FilePath(FILE_PATH_LITERAL(
                   "background_filter_blur_outsets.png")));
}

TEST_F(LayerTreeHostFiltersPixelTest, BackgroundFilterBlurOffAxis) {
  scoped_refptr<SolidColorLayer> background = CreateSolidColorLayer(
      gfx::Rect(200, 200), SK_ColorWHITE);

  // This verifies that the perspective of the clear layer (with black border)
  // does not influence the blending of the green box behind it. Also verifies
  // that the blur is correctly clipped inside the transformed clear layer.
  scoped_refptr<SolidColorLayer> green = CreateSolidColorLayer(
      gfx::Rect(50, 50, 100, 100), kCSSGreen);
  scoped_refptr<SolidColorLayer> blur = CreateSolidColorLayerWithBorder(
      gfx::Rect(30, 30, 120, 120), SK_ColorTRANSPARENT, 1, SK_ColorBLACK);
  background->AddChild(green);
  background->AddChild(blur);

  background->SetPreserves3d(true);
  gfx::Transform background_transform;
  background_transform.ApplyPerspectiveDepth(200.0);
  background->SetTransform(background_transform);

  blur->SetPreserves3d(true);
  gfx::Transform blur_transform;
  blur_transform.Translate(55.0, 65.0);
  blur_transform.RotateAboutXAxis(85.0);
  blur_transform.RotateAboutYAxis(180.0);
  blur_transform.RotateAboutZAxis(20.0);
  blur_transform.Translate(-60.0, -60.0);
  blur->SetTransform(blur_transform);

  FilterOperations filters;
  filters.Append(FilterOperation::CreateBlurFilter(2.f));
  blur->SetBackgroundFilters(filters);

#if defined(OS_WIN)
  // Windows has 151 pixels off by at most 2: crbug.com/225027
  float percentage_pixels_large_error = 0.3775f;  // 151px / (200*200)
  float percentage_pixels_small_error = 0.0f;
  float average_error_allowed_in_bad_pixels = 1.f;
  int large_error_allowed = 2;
  int small_error_allowed = 0;
  pixel_comparator_.reset(new FuzzyPixelComparator(
      true,  // discard_alpha
      percentage_pixels_large_error,
      percentage_pixels_small_error,
      average_error_allowed_in_bad_pixels,
      large_error_allowed,
      small_error_allowed));
#endif

  RunPixelTest(GL_WITH_BITMAP,
               background,
               base::FilePath(FILE_PATH_LITERAL(
                   "background_filter_blur_off_axis.png")));
}

}  // namespace
}  // namespace cc

#endif  // OS_ANDROID
<commit_msg>Revert 220159 "cc: Re-enable LayerTreeHostFiltersPixelTest.Backg..."<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "build/build_config.h"
#include "cc/layers/solid_color_layer.h"
#include "cc/test/layer_tree_pixel_test.h"
#include "cc/test/pixel_comparator.h"

#if !defined(OS_ANDROID)

namespace cc {
namespace {

class LayerTreeHostFiltersPixelTest : public LayerTreePixelTest {};

TEST_F(LayerTreeHostFiltersPixelTest, BackgroundFilterBlur) {
  scoped_refptr<SolidColorLayer> background = CreateSolidColorLayer(
      gfx::Rect(200, 200), SK_ColorWHITE);

  // The green box is entirely behind a layer with background blur, so it
  // should appear blurred on its edges.
  scoped_refptr<SolidColorLayer> green = CreateSolidColorLayer(
      gfx::Rect(50, 50, 100, 100), kCSSGreen);
  scoped_refptr<SolidColorLayer> blur = CreateSolidColorLayer(
      gfx::Rect(30, 30, 140, 140), SK_ColorTRANSPARENT);
  background->AddChild(green);
  background->AddChild(blur);

  FilterOperations filters;
  filters.Append(FilterOperation::CreateBlurFilter(2.f));
  blur->SetBackgroundFilters(filters);

#if defined(OS_WIN)
  // Windows has 436 pixels off by 1: crbug.com/259915
  float percentage_pixels_large_error = 1.09f;  // 436px / (200*200)
  float percentage_pixels_small_error = 0.0f;
  float average_error_allowed_in_bad_pixels = 1.f;
  int large_error_allowed = 1;
  int small_error_allowed = 0;
  pixel_comparator_.reset(new FuzzyPixelComparator(
      true,  // discard_alpha
      percentage_pixels_large_error,
      percentage_pixels_small_error,
      average_error_allowed_in_bad_pixels,
      large_error_allowed,
      small_error_allowed));
#endif

  RunPixelTest(GL_WITH_BITMAP,
               background,
               base::FilePath(FILE_PATH_LITERAL("background_filter_blur.png")));
}

TEST_F(LayerTreeHostFiltersPixelTest, DISABLED_BackgroundFilterBlurOutsets) {
  scoped_refptr<SolidColorLayer> background = CreateSolidColorLayer(
      gfx::Rect(200, 200), SK_ColorWHITE);

  // The green border is outside the layer with background blur, but the
  // background blur should use pixels from outside its layer borders, up to the
  // radius of the blur effect. So the border should be blurred underneath the
  // top layer causing the green to bleed under the transparent layer, but not
  // in the 1px region between the transparent layer and the green border.
  scoped_refptr<SolidColorLayer> green_border = CreateSolidColorLayerWithBorder(
      gfx::Rect(1, 1, 198, 198), SK_ColorWHITE, 10, kCSSGreen);
  scoped_refptr<SolidColorLayer> blur = CreateSolidColorLayer(
      gfx::Rect(12, 12, 176, 176), SK_ColorTRANSPARENT);
  background->AddChild(green_border);
  background->AddChild(blur);

  FilterOperations filters;
  filters.Append(FilterOperation::CreateBlurFilter(5.f));
  blur->SetBackgroundFilters(filters);

#if defined(OS_WIN)
  // Windows has 2250 pixels off by at most 2: crbug.com/259922
  float percentage_pixels_large_error = 5.625f;  // 2250px / (200*200)
  float percentage_pixels_small_error = 0.0f;
  float average_error_allowed_in_bad_pixels = 1.f;
  int large_error_allowed = 2;
  int small_error_allowed = 0;
  pixel_comparator_.reset(new FuzzyPixelComparator(
      true,  // discard_alpha
      percentage_pixels_large_error,
      percentage_pixels_small_error,
      average_error_allowed_in_bad_pixels,
      large_error_allowed,
      small_error_allowed));
#endif

  RunPixelTest(GL_WITH_BITMAP,
               background,
               base::FilePath(FILE_PATH_LITERAL(
                   "background_filter_blur_outsets.png")));
}

TEST_F(LayerTreeHostFiltersPixelTest, BackgroundFilterBlurOffAxis) {
  scoped_refptr<SolidColorLayer> background = CreateSolidColorLayer(
      gfx::Rect(200, 200), SK_ColorWHITE);

  // This verifies that the perspective of the clear layer (with black border)
  // does not influence the blending of the green box behind it. Also verifies
  // that the blur is correctly clipped inside the transformed clear layer.
  scoped_refptr<SolidColorLayer> green = CreateSolidColorLayer(
      gfx::Rect(50, 50, 100, 100), kCSSGreen);
  scoped_refptr<SolidColorLayer> blur = CreateSolidColorLayerWithBorder(
      gfx::Rect(30, 30, 120, 120), SK_ColorTRANSPARENT, 1, SK_ColorBLACK);
  background->AddChild(green);
  background->AddChild(blur);

  background->SetPreserves3d(true);
  gfx::Transform background_transform;
  background_transform.ApplyPerspectiveDepth(200.0);
  background->SetTransform(background_transform);

  blur->SetPreserves3d(true);
  gfx::Transform blur_transform;
  blur_transform.Translate(55.0, 65.0);
  blur_transform.RotateAboutXAxis(85.0);
  blur_transform.RotateAboutYAxis(180.0);
  blur_transform.RotateAboutZAxis(20.0);
  blur_transform.Translate(-60.0, -60.0);
  blur->SetTransform(blur_transform);

  FilterOperations filters;
  filters.Append(FilterOperation::CreateBlurFilter(2.f));
  blur->SetBackgroundFilters(filters);

#if defined(OS_WIN)
  // Windows has 151 pixels off by at most 2: crbug.com/225027
  float percentage_pixels_large_error = 0.3775f;  // 151px / (200*200)
  float percentage_pixels_small_error = 0.0f;
  float average_error_allowed_in_bad_pixels = 1.f;
  int large_error_allowed = 2;
  int small_error_allowed = 0;
  pixel_comparator_.reset(new FuzzyPixelComparator(
      true,  // discard_alpha
      percentage_pixels_large_error,
      percentage_pixels_small_error,
      average_error_allowed_in_bad_pixels,
      large_error_allowed,
      small_error_allowed));
#endif

  RunPixelTest(GL_WITH_BITMAP,
               background,
               base::FilePath(FILE_PATH_LITERAL(
                   "background_filter_blur_off_axis.png")));
}

}  // namespace
}  // namespace cc

#endif  // OS_ANDROID
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/accessibility_util.h"

#include "base/callback.h"
#include "base/logging.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_accessibility_api.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/file_reader.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/common/extensions/extension_messages.h"
#include "chrome/common/extensions/extension_resource.h"
#include "chrome/common/pref_names.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/browser/webui/web_ui.h"
#include "grit/browser_resources.h"
#include "ui/base/resource/resource_bundle.h"

namespace chromeos {
namespace accessibility {

// Helper class that directly loads an extension's content scripts into
// all of the frames corresponding to a given RenderViewHost.
class ContentScriptLoader {
 public:
  // Initialize the ContentScriptLoader with the ID of the extension
  // and the RenderViewHost where the scripts should be loaded.
  ContentScriptLoader(const std::string& extension_id,
                      RenderViewHost* render_view_host)
      : extension_id_(extension_id),
        render_view_host_(render_view_host) {}

  // Call this once with the ExtensionResource corresponding to each
  // content script to be loaded.
  void AppendScript(ExtensionResource resource) {
    resources_.push(resource);
  }

  // Fianlly, call this method once to fetch all of the resources and
  // load them. This method will delete this object when done.
  void Run() {
    if (resources_.empty()) {
      delete this;
      return;
    }

    ExtensionResource resource = resources_.front();
    resources_.pop();
    scoped_refptr<FileReader> reader(new FileReader(resource, NewCallback(
        this, &ContentScriptLoader::OnFileLoaded)));
    reader->Start();
  }

 private:
  void OnFileLoaded(bool success, const std::string& data) {
    if (success) {
      ExtensionMsg_ExecuteCode_Params params;
      params.request_id = 0;
      params.extension_id = extension_id_;
      params.is_javascript = true;
      params.code = data;
      params.all_frames = true;
      params.in_main_world = false;
      render_view_host_->Send(new ExtensionMsg_ExecuteCode(
          render_view_host_->routing_id(), params));
    }
    Run();
  }

  std::string extension_id_;
  RenderViewHost* render_view_host_;
  std::queue<ExtensionResource> resources_;
};

void EnableAccessibility(bool enabled, WebUI* login_web_ui) {
  bool accessibility_enabled = g_browser_process &&
      g_browser_process->local_state()->GetBoolean(
          prefs::kAccessibilityEnabled);
  if (accessibility_enabled == enabled) {
    LOG(INFO) << "Accessibility is already " <<
        (enabled ? "enabled" : "diabled") << ".  Going to do nothing.";
    return;
  }

  g_browser_process->local_state()->SetBoolean(
      prefs::kAccessibilityEnabled, enabled);
  g_browser_process->local_state()->ScheduleSavePersistentPrefs();
  ExtensionAccessibilityEventRouter::GetInstance()->
      SetAccessibilityEnabled(enabled);

  // Load/Unload ChromeVox
  Profile* profile = ProfileManager::GetDefaultProfile();
  ExtensionService* extension_service =
      profile->GetExtensionService();
  std::string manifest = ResourceBundle::GetSharedInstance().
      GetRawDataResource(IDR_CHROMEVOX_MANIFEST).as_string();
  FilePath path = FilePath(extension_misc::kAccessExtensionPath)
      .AppendASCII(extension_misc::kChromeVoxDirectoryName);
  ExtensionService::ComponentExtensionInfo info(manifest, path);
  if (enabled) { // Load ChromeVox
    extension_service->register_component_extension(info);
    const Extension* extension =
        extension_service->LoadComponentExtension(info);

    if (login_web_ui) {
      RenderViewHost* render_view_host =
          login_web_ui->tab_contents()->render_view_host();
      ContentScriptLoader* loader = new ContentScriptLoader(
          extension->id(), render_view_host);

      for (size_t i = 0; i < extension->content_scripts().size(); i++) {
        const UserScript& script = extension->content_scripts()[i];
        for (size_t j = 0; j < script.js_scripts().size(); ++j) {
          const UserScript::File &file = script.js_scripts()[j];
          ExtensionResource resource = extension->GetResource(
              file.relative_path());
          loader->AppendScript(resource);
        }
      }
      loader->Run();  // It cleans itself up when done.
    }

    LOG(INFO) << "ChromeVox was Loaded.";
  } else { // Unload ChromeVox
    extension_service->UnloadComponentExtension(info);
    extension_service->UnregisterComponentExtension(info);
    LOG(INFO) << "ChromeVox was Unloaded.";
  }
}

void ToggleAccessibility(WebUI* login_web_ui) {
  bool accessibility_enabled = g_browser_process &&
      g_browser_process->local_state()->GetBoolean(
          prefs::kAccessibilityEnabled);
  accessibility_enabled = !accessibility_enabled;
  EnableAccessibility(accessibility_enabled, login_web_ui);
};

}  // namespace accessibility
}  // namespace chromeos
<commit_msg>Write the accessibility pref immediately when it changes, rather than scheduling it to be written later. This prevents a bug where the user changes the setting and then immediately shuts down before it can be written. I filed http://crosbug.com/19491 to possibly fix the underlying bug instead (Local State not written before shutdown).<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/accessibility_util.h"

#include "base/callback.h"
#include "base/logging.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_accessibility_api.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/file_reader.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/common/extensions/extension_messages.h"
#include "chrome/common/extensions/extension_resource.h"
#include "chrome/common/pref_names.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/browser/webui/web_ui.h"
#include "grit/browser_resources.h"
#include "ui/base/resource/resource_bundle.h"

namespace chromeos {
namespace accessibility {

// Helper class that directly loads an extension's content scripts into
// all of the frames corresponding to a given RenderViewHost.
class ContentScriptLoader {
 public:
  // Initialize the ContentScriptLoader with the ID of the extension
  // and the RenderViewHost where the scripts should be loaded.
  ContentScriptLoader(const std::string& extension_id,
                      RenderViewHost* render_view_host)
      : extension_id_(extension_id),
        render_view_host_(render_view_host) {}

  // Call this once with the ExtensionResource corresponding to each
  // content script to be loaded.
  void AppendScript(ExtensionResource resource) {
    resources_.push(resource);
  }

  // Fianlly, call this method once to fetch all of the resources and
  // load them. This method will delete this object when done.
  void Run() {
    if (resources_.empty()) {
      delete this;
      return;
    }

    ExtensionResource resource = resources_.front();
    resources_.pop();
    scoped_refptr<FileReader> reader(new FileReader(resource, NewCallback(
        this, &ContentScriptLoader::OnFileLoaded)));
    reader->Start();
  }

 private:
  void OnFileLoaded(bool success, const std::string& data) {
    if (success) {
      ExtensionMsg_ExecuteCode_Params params;
      params.request_id = 0;
      params.extension_id = extension_id_;
      params.is_javascript = true;
      params.code = data;
      params.all_frames = true;
      params.in_main_world = false;
      render_view_host_->Send(new ExtensionMsg_ExecuteCode(
          render_view_host_->routing_id(), params));
    }
    Run();
  }

  std::string extension_id_;
  RenderViewHost* render_view_host_;
  std::queue<ExtensionResource> resources_;
};

void EnableAccessibility(bool enabled, WebUI* login_web_ui) {
  bool accessibility_enabled = g_browser_process &&
      g_browser_process->local_state()->GetBoolean(
          prefs::kAccessibilityEnabled);
  if (accessibility_enabled == enabled) {
    LOG(INFO) << "Accessibility is already " <<
        (enabled ? "enabled" : "diabled") << ".  Going to do nothing.";
    return;
  }

  g_browser_process->local_state()->SetBoolean(
      prefs::kAccessibilityEnabled, enabled);
  // Explicitly call SavePersistentPrefs instead of ScheduleSavePersistentPrefs
  // so that this change gets written immediately, in case the user shuts
  // down right now.  TODO(dmazzoni) switch this back to
  // ScheduleSavePersistentPrefs once http://crosbug.com/19491 is fixed.
  g_browser_process->local_state()->SavePersistentPrefs();
  ExtensionAccessibilityEventRouter::GetInstance()->
      SetAccessibilityEnabled(enabled);

  // Load/Unload ChromeVox
  Profile* profile = ProfileManager::GetDefaultProfile();
  ExtensionService* extension_service =
      profile->GetExtensionService();
  std::string manifest = ResourceBundle::GetSharedInstance().
      GetRawDataResource(IDR_CHROMEVOX_MANIFEST).as_string();
  FilePath path = FilePath(extension_misc::kAccessExtensionPath)
      .AppendASCII(extension_misc::kChromeVoxDirectoryName);
  ExtensionService::ComponentExtensionInfo info(manifest, path);
  if (enabled) { // Load ChromeVox
    extension_service->register_component_extension(info);
    const Extension* extension =
        extension_service->LoadComponentExtension(info);

    if (login_web_ui) {
      RenderViewHost* render_view_host =
          login_web_ui->tab_contents()->render_view_host();
      ContentScriptLoader* loader = new ContentScriptLoader(
          extension->id(), render_view_host);

      for (size_t i = 0; i < extension->content_scripts().size(); i++) {
        const UserScript& script = extension->content_scripts()[i];
        for (size_t j = 0; j < script.js_scripts().size(); ++j) {
          const UserScript::File &file = script.js_scripts()[j];
          ExtensionResource resource = extension->GetResource(
              file.relative_path());
          loader->AppendScript(resource);
        }
      }
      loader->Run();  // It cleans itself up when done.
    }

    LOG(INFO) << "ChromeVox was Loaded.";
  } else { // Unload ChromeVox
    extension_service->UnloadComponentExtension(info);
    extension_service->UnregisterComponentExtension(info);
    LOG(INFO) << "ChromeVox was Unloaded.";
  }
}

void ToggleAccessibility(WebUI* login_web_ui) {
  bool accessibility_enabled = g_browser_process &&
      g_browser_process->local_state()->GetBoolean(
          prefs::kAccessibilityEnabled);
  accessibility_enabled = !accessibility_enabled;
  EnableAccessibility(accessibility_enabled, login_web_ui);
};

}  // namespace accessibility
}  // namespace chromeos
<|endoftext|>


<commit_before>#ifndef __SCENECHANGER_HPP__
#define __SCENECHANGER_HPP__

#include "utils.hpp"

class SceneChanger {
public:
    SceneChanger();/*
    SceneChanger(sf::Vector2f pos, std::string nextScene, sf::Vector2f nextScenePos);
    ~SceneChanger();

    std::string getNextSceneName();
    directions getChangeDirection();
    directions getOutsideDirection();
    sf::FloatRect getRect(sf::Vector2f offset);

    void setDirection(directions dir);
    void setBounds(sf::FloatRect rect);

    directions _dir;
    sf::Vector2f _pos;
    sf::FloatRect _bound;
    std::string _nextScene;
    sf::Vector2f _nextScenePos;
*/
};

#endif
<commit_msg>Delete SceneChanger.hpp<commit_after><|endoftext|>


<commit_before>/*
Copyright (c) 2014, Dilyan Rusev
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 {organization} nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

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

#include "stdafx.h"
#include "Board.h"
#include <cassert>
#ifdef min
#undef min
#endif
#ifdef max
#undef max
#endif
#include <algorithm>
#include "Log.h"

using std::begin;
using std::end;

Board::Board()
		: WIDTH(10)
		, HEIGHT(20)
		, MAX_TETRIMONO_WIDTH(4)
		, MAX_TETRIMONO_HEIGHT(4)
		, m_currentX(0)
		, m_currentY(0)
		, m_currentStartX(0)
		, m_currentEndX(0)
		, m_currentStartY(0)
		, m_currentEndY(0)
		, m_currentType(Tetrimono_Empty)
		, m_nextType(Tetrimono_Empty)
		, m_elapsedSinceLastFall(0)
		, m_timeBetweenFall(500)
		, m_isGameOver(false)
		, m_isFirstFallAfterSpawn(true)
		, m_randomDistributor(Tetrimono_I, Tetrimono_Z) {
	Empty(m_matrix);
	m_nextType = static_cast<Tetrimonos>(m_randomDistributor(m_randomGenerator));
	GetMatrixFor(m_nextType, m_next);
	SpawnNext();
}

Board::~Board() {
}

void Board::Update(float ms) {
	if (m_isGameOver) {
		return;
	}

	m_elapsedSinceLastFall += ms;
	//Log("elaped = %f; ms = %f\n", m_elapsedSinceLastFall, ms);
	if (m_elapsedSinceLastFall >= m_timeBetweenFall) {
		m_elapsedSinceLastFall = 0;
		MergeResult fallResult = MoveCurrent(0, 1);
		if (fallResult == MergeResult_Conflict) {
			if (!m_isFirstFallAfterSpawn) {
				SpawnNext();
				m_isFirstFallAfterSpawn = true;
			}
			else {
				m_isGameOver = true;
			}
		} else {
			m_isFirstFallAfterSpawn = false;
		}
	}
}

void Board::FallDown() {
	if (m_isGameOver) {
		return;
	}

	MergeResult fallResult;
	do {
		fallResult = MoveCurrent(0, 1);
	} while (fallResult != MergeResult_Conflict);
	SpawnNext();
	m_isFirstFallAfterSpawn = true;
}

void Board::Empty(ArrayTetrimonos4x4& matrix) const {
	for (int y = 0; y < MAX_TETRIMONO_HEIGHT; y++) {
		for (int x = 0; x < MAX_TETRIMONO_WIDTH; x++) {
			matrix[y][x] = Tetrimono_Empty;
		}
	}
}

void Board::Empty(ArrayTetrimonos10x20& matrix) const {
	for (int y = 0; y < HEIGHT; y++) {
		for (int x = 0; x < WIDTH; x++) {
			matrix[y][x] = Tetrimono_Empty;
		}
	}
}

void Board::RemoveCurrentFromMatrix(ArrayTetrimonos10x20& matrix) const {
	int boardX, boardY;
	for (int y = m_currentStartY; y <= m_currentEndY; y++) {
		for (int x = m_currentStartX; x <= m_currentEndX; x++) {
			boardX = m_currentX + x;
			boardY = m_currentY + y;
			if (boardX >= 0 && boardY >= 0 && boardX < WIDTH && boardY < HEIGHT && m_current[y][x] != Tetrimono_Empty) {
				matrix[boardY][boardX] = Tetrimono_Empty;
			}
		}
	}
}

void Board::GetMatrixFor(Tetrimonos type, ArrayTetrimonos4x4& matrix) const {
	int ignore1 = 0, ignore2 = 0, ignore3 = 0, ignore4 = 0;
	GetMatrixFor(type, matrix, ignore1, ignore2, ignore3, ignore4);
}

void Board::GetMatrixFor(Tetrimonos type, ArrayTetrimonos4x4& matrix, int& startX, int& endX, int& startY, int& endY) const {
	Empty(matrix);

	switch (type) {
	case Tetrimono_I:
		matrix[0][1] = type;
		matrix[1][1] = type;
		matrix[2][1] = type;
		matrix[3][1] = type;
		startX = 1; endX = 1;
		startY = 0; endY = 3;
		break;
	case Tetrimono_J:
		matrix[0][2] = type;
		matrix[1][2] = type;
		matrix[2][2] = type;
		matrix[2][1] = type;
		startX = 1; endX = 2;
		startY = 0; endY = 2;
		break;
	case Tetrimono_L:
		matrix[0][1] = type;
		matrix[1][1] = type;
		matrix[2][1] = type;
		matrix[2][2] = type;
		startX = 1; endX = 2;
		startY = 0; endY = 2;
		break;
	case Tetrimono_O:
		matrix[0][1] = type;
		matrix[0][2] = type;
		matrix[1][1] = type;
		matrix[1][2] = type;
		startX = 1; endX = 2;
		startY = 0; endY = 1;
		break;
	case Tetrimono_S:
		matrix[0][2] = type;
		matrix[1][0] = type;
		matrix[0][1] = type;
		matrix[1][1] = type;
		startX = 0; endX = 2;
		startY = 0; endY = 1;
		break;
	case Tetrimono_T:
		matrix[0][0] = type;
		matrix[0][1] = type;
		matrix[0][2] = type;
		matrix[1][1] = type;
		startX = 0; endX = 2;
		startY = 0; endY = 1;
		break;
	case Tetrimono_Z:
		matrix[0][0] = type;
		matrix[0][1] = type;
		matrix[1][1] = type;
		matrix[1][2] = type;
		startX = 0; endX = 2;
		startY = 0; endY = 1;
		break;
	default:
		assert(false);
		break;
	}
}

void Board::Spawn(Tetrimonos type) {
	GetMatrixFor(type, m_current, m_currentStartX, m_currentEndX, m_currentStartY, m_currentEndY);

	m_currentType = type;
	m_currentX = (WIDTH - (m_currentEndX - m_currentStartX + 1)) / 2;
	m_currentY = -(m_currentEndY - m_currentStartY + 1);
}

MergeResult Board::SpawnNext() {
	Spawn(m_nextType);

	ArrayTetrimonos10x20 merged;
	std::copy(begin(m_matrix), end(m_matrix), begin(merged));
	MergeResult mergeResult = MergeCurrent(merged);
	std::copy(begin(merged), end(merged), begin(m_matrix));

	m_nextType = static_cast<Tetrimonos>(m_randomDistributor(m_randomGenerator));
	GetMatrixFor(m_nextType, m_next);

	return mergeResult;
}

MergeResult Board::MergeCurrent(ArrayTetrimonos10x20& result) const {
	MergeResult mergeResult = MergeResult_OK;

	int boardX, boardY;

	for (int y = m_currentStartY; y <= m_currentEndY; y++) {
		for (int x = m_currentStartX; x <= m_currentEndX; x++) {
			boardX = m_currentX + x;
			boardY = m_currentY + y;
			if (boardX < 0 || boardX >= WIDTH || boardY >= HEIGHT) {
				mergeResult = MergeResult_Conflict;
				continue;
			} else if (boardY < 0) {
				// going out from the top is not conflict by design
				continue;
			}

			const Tetrimonos& source = m_current[y][x];
			Tetrimonos& target = result[boardY][boardX];

			if (target == Tetrimono_Empty) {
				target = source;
			} else if (source != Tetrimono_Empty ) {
				mergeResult = MergeResult_Conflict;
			}
		}
	}
	return mergeResult;
}

MergeResult Board::MoveCurrent(int deltaX, int deltaY) {
	ArrayTetrimonos10x20 mergedMatrix;
	std::copy(begin(m_matrix), end(m_matrix), begin(mergedMatrix));
	RemoveCurrentFromMatrix(mergedMatrix);

	m_currentX += deltaX;
	m_currentY += deltaY;
	MergeResult res = MergeCurrent(mergedMatrix);
	if (res == MergeResult_OK) {
		std::copy(begin(mergedMatrix), end(mergedMatrix), begin(m_matrix));
	} else {
		m_currentX -= deltaX;
		m_currentY -= deltaY;
	}

	return res;
}

MergeResult Board::Rotate(RotateDirection direction) {
	ArrayTetrimonos10x20 mergedMatrix;
	std::copy(begin(m_matrix), end(m_matrix), begin(mergedMatrix));
	RemoveCurrentFromMatrix(mergedMatrix);

	int startX, endX, startY, endY;
	startX = m_currentStartX;
	endX = m_currentEndX;
	startY = m_currentStartY;
	endY = m_currentEndY;
	ArrayTetrimonos4x4 original;
	std::copy(begin(m_current), end(m_current), begin(original));

	RotateCurrentMatrix(direction);

	MergeResult res = MergeCurrent(mergedMatrix);
	if (res == MergeResult_OK) {
		std::copy(begin(mergedMatrix), end(mergedMatrix), begin(m_matrix));
	} else {
		m_currentStartX = startX;
		m_currentEndX = endX;
		m_currentStartY = startY;
		m_currentEndY = endY;
		std::copy(begin(original), end(original), begin(m_current));
	}

	return res;
}

void Board::FindBoundsFor(const ArrayTetrimonos4x4& figure, int& startX, int& startY, int& endX, int& endY) const {
	startX = MAX_TETRIMONO_WIDTH - 1;
	endX = 0;
	startY = MAX_TETRIMONO_HEIGHT - 1;
	endY = 0;

	for (int y = 0; y < MAX_TETRIMONO_HEIGHT; y++) {
		for (int x = 0; x < MAX_TETRIMONO_WIDTH; x++) {
			if (figure[y][x] != Tetrimono_Empty) {
				startX = std::min(startX, x);
				endX = std::max(endX, x);
				startY = std::min(startY, y);
				endY = std::max(endY, y);
			}
		}
	}
}

void Board::RotateCurrentMatrix(RotateDirection direction) {
	ArrayTetrimonos4x4 source;
	std::copy(begin(m_current), end(m_current), begin(source));

	if (direction == RotateDirection_Clockwize) {
		for (int y = 0; y < MAX_TETRIMONO_HEIGHT; y++) {
			for (int x = 0; x < MAX_TETRIMONO_WIDTH; x++) {
				m_current[y][x] = source[x][MAX_TETRIMONO_HEIGHT - y - 1];
			}
		}
	} else {
		for (int y = 0; y < MAX_TETRIMONO_HEIGHT; y++) {
			for (int x = 0; x < MAX_TETRIMONO_WIDTH; x++) {
				m_current[y][x] = source[MAX_TETRIMONO_WIDTH - x - 1][y];
			}
		}
	}

	FindBoundsFor(m_current, m_currentStartX, m_currentStartY, m_currentEndX, m_currentEndX);
}<commit_msg>fix rotation bug<commit_after>/*
Copyright (c) 2014, Dilyan Rusev
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 {organization} nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

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

#include "stdafx.h"
#include "Board.h"
#include <cassert>
#ifdef min
#undef min
#endif
#ifdef max
#undef max
#endif
#include <algorithm>
#include "Log.h"

using std::begin;
using std::end;

Board::Board()
		: WIDTH(10)
		, HEIGHT(20)
		, MAX_TETRIMONO_WIDTH(4)
		, MAX_TETRIMONO_HEIGHT(4)
		, m_currentX(0)
		, m_currentY(0)
		, m_currentStartX(0)
		, m_currentEndX(0)
		, m_currentStartY(0)
		, m_currentEndY(0)
		, m_currentType(Tetrimono_Empty)
		, m_nextType(Tetrimono_Empty)
		, m_elapsedSinceLastFall(0)
		, m_timeBetweenFall(500)
		, m_isGameOver(false)
		, m_isFirstFallAfterSpawn(true)
		, m_randomDistributor(Tetrimono_I, Tetrimono_Z) {
	Empty(m_matrix);
	m_nextType = static_cast<Tetrimonos>(m_randomDistributor(m_randomGenerator));
	GetMatrixFor(m_nextType, m_next);
	SpawnNext();
}

Board::~Board() {
}

void Board::Update(float ms) {
	if (m_isGameOver) {
		return;
	}

	m_elapsedSinceLastFall += ms;
	//Log("elaped = %f; ms = %f\n", m_elapsedSinceLastFall, ms);
	if (m_elapsedSinceLastFall >= m_timeBetweenFall) {
		m_elapsedSinceLastFall = 0;
		MergeResult fallResult = MoveCurrent(0, 1);
		if (fallResult == MergeResult_Conflict) {
			if (!m_isFirstFallAfterSpawn) {
				SpawnNext();
				m_isFirstFallAfterSpawn = true;
			}
			else {
				m_isGameOver = true;
			}
		} else {
			m_isFirstFallAfterSpawn = false;
		}
	}
}

void Board::FallDown() {
	if (m_isGameOver) {
		return;
	}

	MergeResult fallResult;
	do {
		fallResult = MoveCurrent(0, 1);
	} while (fallResult != MergeResult_Conflict);
	SpawnNext();
	m_isFirstFallAfterSpawn = true;
}

void Board::Empty(ArrayTetrimonos4x4& matrix) const {
	for (int y = 0; y < MAX_TETRIMONO_HEIGHT; y++) {
		for (int x = 0; x < MAX_TETRIMONO_WIDTH; x++) {
			matrix[y][x] = Tetrimono_Empty;
		}
	}
}

void Board::Empty(ArrayTetrimonos10x20& matrix) const {
	for (int y = 0; y < HEIGHT; y++) {
		for (int x = 0; x < WIDTH; x++) {
			matrix[y][x] = Tetrimono_Empty;
		}
	}
}

void Board::RemoveCurrentFromMatrix(ArrayTetrimonos10x20& matrix) const {
	int boardX, boardY;
	for (int y = m_currentStartY; y <= m_currentEndY; y++) {
		for (int x = m_currentStartX; x <= m_currentEndX; x++) {
			boardX = m_currentX + x;
			boardY = m_currentY + y;
			if (boardX >= 0 && boardY >= 0 && boardX < WIDTH && boardY < HEIGHT && m_current[y][x] != Tetrimono_Empty) {
				matrix[boardY][boardX] = Tetrimono_Empty;
			}
		}
	}
}

void Board::GetMatrixFor(Tetrimonos type, ArrayTetrimonos4x4& matrix) const {
	int ignore1 = 0, ignore2 = 0, ignore3 = 0, ignore4 = 0;
	GetMatrixFor(type, matrix, ignore1, ignore2, ignore3, ignore4);
}

void Board::GetMatrixFor(Tetrimonos type, ArrayTetrimonos4x4& matrix, int& startX, int& endX, int& startY, int& endY) const {
	Empty(matrix);

	switch (type) {
	case Tetrimono_I:
		matrix[0][1] = type;
		matrix[1][1] = type;
		matrix[2][1] = type;
		matrix[3][1] = type;
		startX = 1; endX = 1;
		startY = 0; endY = 3;
		break;
	case Tetrimono_J:
		matrix[0][2] = type;
		matrix[1][2] = type;
		matrix[2][2] = type;
		matrix[2][1] = type;
		startX = 1; endX = 2;
		startY = 0; endY = 2;
		break;
	case Tetrimono_L:
		matrix[0][1] = type;
		matrix[1][1] = type;
		matrix[2][1] = type;
		matrix[2][2] = type;
		startX = 1; endX = 2;
		startY = 0; endY = 2;
		break;
	case Tetrimono_O:
		matrix[0][1] = type;
		matrix[0][2] = type;
		matrix[1][1] = type;
		matrix[1][2] = type;
		startX = 1; endX = 2;
		startY = 0; endY = 1;
		break;
	case Tetrimono_S:
		matrix[0][2] = type;
		matrix[1][0] = type;
		matrix[0][1] = type;
		matrix[1][1] = type;
		startX = 0; endX = 2;
		startY = 0; endY = 1;
		break;
	case Tetrimono_T:
		matrix[0][0] = type;
		matrix[0][1] = type;
		matrix[0][2] = type;
		matrix[1][1] = type;
		startX = 0; endX = 2;
		startY = 0; endY = 1;
		break;
	case Tetrimono_Z:
		matrix[0][0] = type;
		matrix[0][1] = type;
		matrix[1][1] = type;
		matrix[1][2] = type;
		startX = 0; endX = 2;
		startY = 0; endY = 1;
		break;
	default:
		assert(false);
		break;
	}
}

void Board::Spawn(Tetrimonos type) {
	GetMatrixFor(type, m_current, m_currentStartX, m_currentEndX, m_currentStartY, m_currentEndY);

	m_currentType = type;
	m_currentX = (WIDTH - (m_currentEndX - m_currentStartX + 1)) / 2;
	m_currentY = -(m_currentEndY - m_currentStartY + 1);
}

MergeResult Board::SpawnNext() {
	Spawn(m_nextType);

	ArrayTetrimonos10x20 merged;
	std::copy(begin(m_matrix), end(m_matrix), begin(merged));
	MergeResult mergeResult = MergeCurrent(merged);
	std::copy(begin(merged), end(merged), begin(m_matrix));

	m_nextType = static_cast<Tetrimonos>(m_randomDistributor(m_randomGenerator));
	GetMatrixFor(m_nextType, m_next);

	return mergeResult;
}

MergeResult Board::MergeCurrent(ArrayTetrimonos10x20& result) const {
	MergeResult mergeResult = MergeResult_OK;

	int boardX, boardY;

	for (int y = m_currentStartY; y <= m_currentEndY; y++) {
		for (int x = m_currentStartX; x <= m_currentEndX; x++) {
			boardX = m_currentX + x;
			boardY = m_currentY + y;
			if (boardX < 0 || boardX >= WIDTH || boardY >= HEIGHT) {
				mergeResult = MergeResult_Conflict;
				continue;
			} else if (boardY < 0) {
				// going out from the top is not conflict by design
				continue;
			}

			const Tetrimonos& source = m_current[y][x];
			Tetrimonos& target = result[boardY][boardX];

			if (target == Tetrimono_Empty) {
				target = source;
			} else if (source != Tetrimono_Empty ) {
				mergeResult = MergeResult_Conflict;
			}
		}
	}
	return mergeResult;
}

MergeResult Board::MoveCurrent(int deltaX, int deltaY) {
	ArrayTetrimonos10x20 mergedMatrix;
	std::copy(begin(m_matrix), end(m_matrix), begin(mergedMatrix));
	RemoveCurrentFromMatrix(mergedMatrix);

	m_currentX += deltaX;
	m_currentY += deltaY;
	MergeResult res = MergeCurrent(mergedMatrix);
	if (res == MergeResult_OK) {
		std::copy(begin(mergedMatrix), end(mergedMatrix), begin(m_matrix));
	} else {
		m_currentX -= deltaX;
		m_currentY -= deltaY;
	}

	return res;
}

MergeResult Board::Rotate(RotateDirection direction) {
	ArrayTetrimonos10x20 mergedMatrix;
	std::copy(begin(m_matrix), end(m_matrix), begin(mergedMatrix));
	RemoveCurrentFromMatrix(mergedMatrix);

	int startX, endX, startY, endY;
	startX = m_currentStartX;
	endX = m_currentEndX;
	startY = m_currentStartY;
	endY = m_currentEndY;
	ArrayTetrimonos4x4 original;
	std::copy(begin(m_current), end(m_current), begin(original));

	RotateCurrentMatrix(direction);

	MergeResult res = MergeCurrent(mergedMatrix);
	if (res == MergeResult_OK) {
		std::copy(begin(mergedMatrix), end(mergedMatrix), begin(m_matrix));
	} else {
		m_currentStartX = startX;
		m_currentEndX = endX;
		m_currentStartY = startY;
		m_currentEndY = endY;
		std::copy(begin(original), end(original), begin(m_current));
	}

	return res;
}

void Board::FindBoundsFor(const ArrayTetrimonos4x4& figure, int& startX, int& startY, int& endX, int& endY) const {
	startX = MAX_TETRIMONO_WIDTH - 1;
	endX = 0;
	startY = MAX_TETRIMONO_HEIGHT - 1;
	endY = 0;

	for (int y = 0; y < MAX_TETRIMONO_HEIGHT; y++) {
		for (int x = 0; x < MAX_TETRIMONO_WIDTH; x++) {
			if (figure[y][x] != Tetrimono_Empty) {
				startX = std::min(startX, x);
				endX = std::max(endX, x);
				startY = std::min(startY, y);
				endY = std::max(endY, y);
			}
		}
	}
}

void Board::RotateCurrentMatrix(RotateDirection direction) {
	ArrayTetrimonos4x4 source;
	std::copy(begin(m_current), end(m_current), begin(source));

	if (direction == RotateDirection_Clockwize) {
		for (int y = 0; y < MAX_TETRIMONO_HEIGHT; y++) {
			for (int x = 0; x < MAX_TETRIMONO_WIDTH; x++) {
				m_current[y][x] = source[x][MAX_TETRIMONO_HEIGHT - y - 1];
			}
		}
	} else {
		for (int y = 0; y < MAX_TETRIMONO_HEIGHT; y++) {
			for (int x = 0; x < MAX_TETRIMONO_WIDTH; x++) {
				m_current[y][x] = source[MAX_TETRIMONO_WIDTH - x - 1][y];
			}
		}
	}

	FindBoundsFor(m_current, m_currentStartX, m_currentStartY, m_currentEndX, m_currentEndY);
}<|endoftext|>


<commit_before>/* -*-  mode: c++; c-default-style: "google"; indent-tabs-mode: nil -*- */

/*
  The elevation evaluator gets the surface elevation, slope, and updates pres + elev.

  Authors: Ethan Coon (ecoon@lanl.gov)
*/

#include "fractional_conductance_evaluator.hh"

namespace Amanzi {
namespace Flow {
namespace FlowRelations {

FractionalConductanceEvaluator::FractionalConductanceEvaluator(Teuchos::ParameterList& plist) :
    SecondaryVariableFieldEvaluator(plist) {

  Key domain = Keys::getDomain(my_key_);

  vpd_key_ = Keys::readKey(plist_, domain, "volumetric ponded depth", "volumetric_ponded_depth");
  dependencies_.insert(vpd_key_);

  pdd_key_ = Keys::readKey(plist_, domain, "ponded depth minus depression depth", "ponded_depth_minus_depression_depth");
  dependencies_.insert(pdd_key_);

  delta_max_key_ = Keys::readKey(plist_, domain, "microtopographic relief", "microtopographic_relief");
  dependencies_.insert(delta_max_key_);

  delta_ex_key_ = plist_.get<std::string>("excluded volume key", Keys::getKey(domain,"excluded_volume"));
  dependencies_.insert(delta_ex_key_);

  depr_depth_key_ = plist_.get<std::string>("depression depth key", Keys::getKey(domain,"depression_depth"));
  dependencies_.insert(depr_depth_key_);
}

FractionalConductanceEvaluator::FractionalConductanceEvaluator(const FractionalConductanceEvaluator& other) :
    SecondaryVariableFieldEvaluator(other),
    pdd_key_(other.pdd_key_),
    vpd_key_(other.vpd_key_),
    delta_ex_key_(other.delta_ex_key_),
    delta_max_key_(other.delta_max_key_),
    depr_depth_key_(other.depr_depth_key_)
{};

Teuchos::RCP<FieldEvaluator>
FractionalConductanceEvaluator::Clone() const {
  return Teuchos::rcp(new FractionalConductanceEvaluator(*this));
}

void FractionalConductanceEvaluator::EvaluateField_(const Teuchos::Ptr<State>& S,
        const Teuchos::Ptr<CompositeVector>& result) {

  Epetra_MultiVector& res = *result->ViewComponent("cell",false);

  const Epetra_MultiVector& vpd = *S->GetFieldData(vpd_key_)->ViewComponent("cell",false);
  const Epetra_MultiVector& delta_max_v = *S->GetFieldData(delta_max_key_)->ViewComponent("cell", false);
  const Epetra_MultiVector& delta_ex_v = *S->GetFieldData(delta_ex_key_)->ViewComponent("cell", false);
  const Epetra_MultiVector& depr_depth_v = *S->GetFieldData(depr_depth_key_)->ViewComponent("cell", false);
  const Epetra_MultiVector& pdd_v = *S->GetFieldData(pdd_key_)->ViewComponent("cell",false);

  int ncells = res.MyLength();
  assert(depr_depth_v[0][0] > 0.);

  for (int c=0; c!=ncells; ++c) {
    double depr_depth = depr_depth_v[0][c];
    double delta_max = delta_max_v[0][c];
    double delta_ex = delta_ex_v[0][c];
    double fixed_depth = std::pow(depr_depth,2)*(2*delta_max - 3*delta_ex)/std::pow(delta_max,2) + std::pow(depr_depth,3)*(2*delta_ex - delta_max)/std::pow(delta_max,3);

    if (pdd_v[0][c] <= 0.0)
      res[0][c] = 0;
    else{
      res[0][c] = (vpd[0][c] - fixed_depth) / (pdd_v[0][c]);
    }
  }
}

// This is hopefully never called?
void FractionalConductanceEvaluator::EvaluateFieldPartialDerivative_(const Teuchos::Ptr<State>& S,
        Key wrt_key, const Teuchos::Ptr<CompositeVector>& result) {
  //  std::cout<<"Fractional Conductance Evaluator Partial Derivative -- NEVER CALLED??: \n"; abort();
  std::cout<<"Fractional: "<<my_key_<<" "<<wrt_key<<"\n";

  Epetra_MultiVector& res = *result->ViewComponent("cell",false);

  const Epetra_MultiVector& vpd = *S->GetFieldData(vpd_key_)->ViewComponent("cell",false);
  const Epetra_MultiVector& delta_max_v = *S->GetFieldData(delta_max_key_)->ViewComponent("cell", false);
  const Epetra_MultiVector& delta_ex_v = *S->GetFieldData(delta_ex_key_)->ViewComponent("cell", false);
  const Epetra_MultiVector& depr_depth_v = *S->GetFieldData(depr_depth_key_)->ViewComponent("cell", false);
  const Epetra_MultiVector& pdd_v = *S->GetFieldData(pdd_key_)->ViewComponent("cell",false);

  int ncells = res.MyLength();
  //  assert(depr_depth_v[0][0] > 0.);

  if (wrt_key == pdd_key_) {
    for (int c=0; c!=ncells; ++c) {
      double depr_depth = depr_depth_v[0][c];
      double delta_max = delta_max_v[0][c];
      double delta_ex = delta_ex_v[0][c];
      double fixed_depth = std::pow(depr_depth,2)*(2*delta_max - 3*delta_ex)/std::pow(delta_max,2) + std::pow(depr_depth,3)*(2*delta_ex - delta_max)/std::pow(delta_max,3);

      if (pdd_v[0][c] <= 0.0)
        res[0][c] = 0;
      else{
        res[0][c] = - (vpd[0][c] - fixed_depth) / std::pow(pdd_v[0][c],2.);
      }
    }

  }
  else if (wrt_key == vpd_key_) {
    for (int c=0; c!=ncells; ++c) {
      double depr_depth = depr_depth_v[0][c];
      double delta_max = delta_max_v[0][c];
      double delta_ex = delta_ex_v[0][c];
      double fixed_depth = std::pow(depr_depth,2)*(2*delta_max - 3*delta_ex)/std::pow(delta_max,2) + std::pow(depr_depth,3)*(2*delta_ex - delta_max)/std::pow(delta_max,3);

      if (pdd_v[0][c] <= 0.0)
        res[0][c] = 0;
      else{
        res[0][c] =  1.0 / pdd_v[0][c];
      }
    }

  }
  else {
    Errors::Message msg("VolumetricHeightSubgridEvaluator: Not Implemented: no derivatives implemented other than ponded depth.");
    Exceptions::amanzi_throw(msg);
  }

}

} //namespace
} //namespace
} //namespace
<commit_msg>removed couts.<commit_after>/* -*-  mode: c++; c-default-style: "google"; indent-tabs-mode: nil -*- */

/*
  The elevation evaluator gets the surface elevation, slope, and updates pres + elev.

  Authors: Ethan Coon (ecoon@lanl.gov)
*/

#include "fractional_conductance_evaluator.hh"

namespace Amanzi {
namespace Flow {
namespace FlowRelations {

FractionalConductanceEvaluator::FractionalConductanceEvaluator(Teuchos::ParameterList& plist) :
    SecondaryVariableFieldEvaluator(plist) {

  Key domain = Keys::getDomain(my_key_);

  vpd_key_ = Keys::readKey(plist_, domain, "volumetric ponded depth", "volumetric_ponded_depth");
  dependencies_.insert(vpd_key_);

  pdd_key_ = Keys::readKey(plist_, domain, "ponded depth minus depression depth", "ponded_depth_minus_depression_depth");
  dependencies_.insert(pdd_key_);

  delta_max_key_ = Keys::readKey(plist_, domain, "microtopographic relief", "microtopographic_relief");
  dependencies_.insert(delta_max_key_);

  delta_ex_key_ = plist_.get<std::string>("excluded volume key", Keys::getKey(domain,"excluded_volume"));
  dependencies_.insert(delta_ex_key_);

  depr_depth_key_ = plist_.get<std::string>("depression depth key", Keys::getKey(domain,"depression_depth"));
  dependencies_.insert(depr_depth_key_);
}

FractionalConductanceEvaluator::FractionalConductanceEvaluator(const FractionalConductanceEvaluator& other) :
    SecondaryVariableFieldEvaluator(other),
    pdd_key_(other.pdd_key_),
    vpd_key_(other.vpd_key_),
    delta_ex_key_(other.delta_ex_key_),
    delta_max_key_(other.delta_max_key_),
    depr_depth_key_(other.depr_depth_key_)
{};

Teuchos::RCP<FieldEvaluator>
FractionalConductanceEvaluator::Clone() const {
  return Teuchos::rcp(new FractionalConductanceEvaluator(*this));
}

void FractionalConductanceEvaluator::EvaluateField_(const Teuchos::Ptr<State>& S,
        const Teuchos::Ptr<CompositeVector>& result) {

  Epetra_MultiVector& res = *result->ViewComponent("cell",false);

  const Epetra_MultiVector& vpd = *S->GetFieldData(vpd_key_)->ViewComponent("cell",false);
  const Epetra_MultiVector& delta_max_v = *S->GetFieldData(delta_max_key_)->ViewComponent("cell", false);
  const Epetra_MultiVector& delta_ex_v = *S->GetFieldData(delta_ex_key_)->ViewComponent("cell", false);
  const Epetra_MultiVector& depr_depth_v = *S->GetFieldData(depr_depth_key_)->ViewComponent("cell", false);
  const Epetra_MultiVector& pdd_v = *S->GetFieldData(pdd_key_)->ViewComponent("cell",false);

  int ncells = res.MyLength();
  assert(depr_depth_v[0][0] > 0.);

  for (int c=0; c!=ncells; ++c) {
    double depr_depth = depr_depth_v[0][c];
    double delta_max = delta_max_v[0][c];
    double delta_ex = delta_ex_v[0][c];
    double fixed_depth = std::pow(depr_depth,2)*(2*delta_max - 3*delta_ex)/std::pow(delta_max,2) + std::pow(depr_depth,3)*(2*delta_ex - delta_max)/std::pow(delta_max,3);

    if (pdd_v[0][c] <= 0.0)
      res[0][c] = 0;
    else{
      res[0][c] = (vpd[0][c] - fixed_depth) / (pdd_v[0][c]);
    }
  }
}

// This is hopefully never called?
void FractionalConductanceEvaluator::EvaluateFieldPartialDerivative_(const Teuchos::Ptr<State>& S,
        Key wrt_key, const Teuchos::Ptr<CompositeVector>& result) {

  Epetra_MultiVector& res = *result->ViewComponent("cell",false);

  const Epetra_MultiVector& vpd = *S->GetFieldData(vpd_key_)->ViewComponent("cell",false);
  const Epetra_MultiVector& delta_max_v = *S->GetFieldData(delta_max_key_)->ViewComponent("cell", false);
  const Epetra_MultiVector& delta_ex_v = *S->GetFieldData(delta_ex_key_)->ViewComponent("cell", false);
  const Epetra_MultiVector& depr_depth_v = *S->GetFieldData(depr_depth_key_)->ViewComponent("cell", false);
  const Epetra_MultiVector& pdd_v = *S->GetFieldData(pdd_key_)->ViewComponent("cell",false);

  int ncells = res.MyLength();
  //  assert(depr_depth_v[0][0] > 0.);

  if (wrt_key == pdd_key_) {
    for (int c=0; c!=ncells; ++c) {
      double depr_depth = depr_depth_v[0][c];
      double delta_max = delta_max_v[0][c];
      double delta_ex = delta_ex_v[0][c];
      double fixed_depth = std::pow(depr_depth,2)*(2*delta_max - 3*delta_ex)/std::pow(delta_max,2) + std::pow(depr_depth,3)*(2*delta_ex - delta_max)/std::pow(delta_max,3);

      if (pdd_v[0][c] <= 0.0)
        res[0][c] = 0;
      else{
        res[0][c] = - (vpd[0][c] - fixed_depth) / std::pow(pdd_v[0][c],2.);
      }
    }

  }
  else if (wrt_key == vpd_key_) {
    for (int c=0; c!=ncells; ++c) {
      double depr_depth = depr_depth_v[0][c];
      double delta_max = delta_max_v[0][c];
      double delta_ex = delta_ex_v[0][c];
      double fixed_depth = std::pow(depr_depth,2)*(2*delta_max - 3*delta_ex)/std::pow(delta_max,2) + std::pow(depr_depth,3)*(2*delta_ex - delta_max)/std::pow(delta_max,3);

      if (pdd_v[0][c] <= 0.0)
        res[0][c] = 0;
      else{
        res[0][c] =  1.0 / pdd_v[0][c];
      }
    }

  }
  else {
    Errors::Message msg("VolumetricHeightSubgridEvaluator: Not Implemented: no derivatives implemented other than ponded depth.");
    Exceptions::amanzi_throw(msg);
  }

}

} //namespace
} //namespace
} //namespace
<|endoftext|>