<commit_before>#pragma once

#include "iokit_utility.hpp"
#include "json_utility.hpp"
#include "types.hpp"
#include <optional>
#include <pqrs/osx/iokit_hid_device.hpp>
#include <pqrs/osx/iokit_types.hpp>

namespace krbn {
class device_properties final {
public:
  device_properties(void) {
  }

  device_properties(device_id device_id,
                    IOHIDDeviceRef device) {
    device_id_ = device_id;

    pqrs::osx::iokit_hid_device hid_device(device);

    if (auto value = hid_device.find_vendor_id()) {
      vendor_id_ = make_vendor_id(*value);
    }
    if (auto value = hid_device.find_product_id()) {
      product_id_ = make_product_id(*value);
    }
    if (auto value = hid_device.find_location_id()) {
      location_id_ = make_location_id(*value);
    }
    manufacturer_ = hid_device.find_manufacturer();
    product_ = hid_device.find_product();
    serial_number_ = hid_device.find_serial_number();
    transport_ = hid_device.find_transport();
    is_keyboard_ = iokit_utility::is_keyboard(device);
    is_pointing_device_ = iokit_utility::is_pointing_device(device);

    if (product_ && is_keyboard_ && is_pointing_device_) {
      if ((*product_).find("Apple Internal ") != std::string::npos) {
        if (*is_keyboard_ == true && *is_pointing_device_ == false) {
          is_built_in_keyboard_ = true;
        }
        if (*is_keyboard_ == false && *is_pointing_device_ == true) {
          is_built_in_pointing_device_ = true;
        }
      }
    }

    is_karabiner_virtual_hid_device_ = iokit_utility::is_karabiner_virtual_hid_device(device);

    device_identifiers_ = std::make_shared<device_identifiers>(
        vendor_id_.value_or(vendor_id(0)),
        product_id_.value_or(product_id(0)),
        is_keyboard_.value_or(false),
        is_pointing_device_.value_or(false));
  }

  nlohmann::json to_json(void) const {
    nlohmann::json json;

    json["device_id"] = type_safe::get(device_id_);

    if (vendor_id_) {
      json["vendor_id"] = type_safe::get(*vendor_id_);
    }
    if (product_id_) {
      json["product_id"] = type_safe::get(*product_id_);
    }
    if (location_id_) {
      json["location_id"] = type_safe::get(*location_id_);
    }
    if (manufacturer_) {
      json["manufacturer"] = *manufacturer_;
    }
    if (product_) {
      json["product"] = *product_;
    }
    if (serial_number_) {
      json["serial_number"] = *serial_number_;
    }
    if (transport_) {
      json["transport"] = *transport_;
    }
    if (is_keyboard_) {
      json["is_keyboard"] = *is_keyboard_;
    }
    if (is_pointing_device_) {
      json["is_pointing_device"] = *is_pointing_device_;
    }
    if (is_built_in_keyboard_) {
      json["is_built_in_keyboard"] = *is_built_in_keyboard_;
    }
    if (is_built_in_pointing_device_) {
      json["is_built_in_pointing_device"] = *is_built_in_pointing_device_;
    }
    if (is_karabiner_virtual_hid_device_) {
      json["is_karabiner_virtual_hid_device"] = *is_karabiner_virtual_hid_device_;
    }

    return json;
  }

  std::optional<vendor_id> get_vendor_id(void) const {
    return vendor_id_;
  }

  device_properties& set(vendor_id value) {
    vendor_id_ = value;
    return *this;
  }

  std::optional<product_id> get_product_id(void) const {
    return product_id_;
  }

  device_properties& set(product_id value) {
    product_id_ = value;
    return *this;
  }

  std::optional<location_id> get_location_id(void) const {
    return location_id_;
  }

  device_properties& set(location_id value) {
    location_id_ = value;
    return *this;
  }

  std::optional<std::string> get_manufacturer(void) const {
    return manufacturer_;
  }

  device_properties& set_manufacturer(const std::string& value) {
    manufacturer_ = value;
    return *this;
  }

  std::optional<std::string> get_product(void) const {
    return product_;
  }

  device_properties& set_product(const std::string& value) {
    product_ = value;
    return *this;
  }

  std::optional<std::string> get_serial_number(void) const {
    return serial_number_;
  }

  device_properties& set_serial_number(const std::string& value) {
    serial_number_ = value;
    return *this;
  }

  std::optional<std::string> get_transport(void) const {
    return transport_;
  }

  device_properties& set_transport(const std::string& value) {
    transport_ = value;
    return *this;
  }

  std::optional<device_id> get_device_id(void) const {
    return device_id_;
  }

  device_properties& set(device_id value) {
    device_id_ = value;
    return *this;
  }

  std::optional<bool> get_is_keyboard(void) const {
    return is_keyboard_;
  }

  device_properties& set_is_keyboard(bool value) {
    is_keyboard_ = value;
    return *this;
  }

  std::optional<bool> get_is_pointing_device(void) const {
    return is_pointing_device_;
  }

  device_properties& set_is_pointing_device(bool value) {
    is_pointing_device_ = value;
    return *this;
  }

  std::optional<bool> get_is_karabiner_virtual_hid_device(void) const {
    return is_karabiner_virtual_hid_device_;
  }

  std::shared_ptr<device_identifiers> get_device_identifiers(void) const {
    return device_identifiers_;
  }

  bool compare(const device_properties& other) {
    // product
    {
      auto p1 = product_.value_or("");
      auto p2 = other.product_.value_or("");
      if (p1 != p2) {
        return p1 < p2;
      }
    }

    // manufacturer
    {
      auto m1 = manufacturer_.value_or("");
      auto m2 = other.manufacturer_.value_or("");
      if (m1 != m2) {
        return m1 < m2;
      }
    }

    // is_keyboard
    {
      auto k1 = is_keyboard_.value_or(false);
      auto k2 = other.is_keyboard_.value_or(false);
      if (k1 != k2) {
        return k1;
      }
    }

    // is_pointing_device
    {
      auto p1 = is_pointing_device_.value_or(false);
      auto p2 = other.is_pointing_device_.value_or(false);
      if (p1 != p2) {
        return p1;
      }
    }

    // device_id
    {
      auto r1 = device_id_;
      auto r2 = other.device_id_;
      if (r1 != r2) {
        return r1 < r2;
      }
    }

    return false;
  }

  bool operator==(const device_properties& other) const {
    return device_id_ == other.device_id_ &&
           vendor_id_ == other.vendor_id_ &&
           product_id_ == other.product_id_ &&
           location_id_ == other.location_id_ &&
           manufacturer_ == other.manufacturer_ &&
           product_ == other.product_ &&
           serial_number_ == other.serial_number_ &&
           transport_ == other.transport_ &&
           is_keyboard_ == other.is_keyboard_ &&
           is_pointing_device_ == other.is_pointing_device_;
  }

private:
  device_id device_id_;
  std::optional<vendor_id> vendor_id_;
  std::optional<product_id> product_id_;
  std::optional<location_id> location_id_;
  std::optional<std::string> manufacturer_;
  std::optional<std::string> product_;
  std::optional<std::string> serial_number_;
  std::optional<std::string> transport_;
  std::optional<bool> is_keyboard_;
  std::optional<bool> is_pointing_device_;
  std::optional<bool> is_built_in_keyboard_;
  std::optional<bool> is_built_in_pointing_device_;
  std::optional<bool> is_karabiner_virtual_hid_device_;
  std::shared_ptr<device_identifiers> device_identifiers_;
};

inline void to_json(nlohmann::json& json, const device_properties& device_properties) {
  json = device_properties.to_json();
}

inline size_t hash_value(const device_properties& value) {
  // We can treat device_id_ as the unique value of device_properties.
  if (auto id = value.get_device_id()) {
    return std::hash<device_id>{}(*id);
  }
  return 0;
}
} // namespace krbn
<commit_msg>add get_is_built_in_keyboard,get_is_built_in_pointing_device<commit_after>#pragma once

#include "iokit_utility.hpp"
#include "json_utility.hpp"
#include "types.hpp"
#include <optional>
#include <pqrs/osx/iokit_hid_device.hpp>
#include <pqrs/osx/iokit_types.hpp>

namespace krbn {
class device_properties final {
public:
  device_properties(void) {
  }

  device_properties(device_id device_id,
                    IOHIDDeviceRef device) {
    device_id_ = device_id;

    pqrs::osx::iokit_hid_device hid_device(device);

    if (auto value = hid_device.find_vendor_id()) {
      vendor_id_ = make_vendor_id(*value);
    }
    if (auto value = hid_device.find_product_id()) {
      product_id_ = make_product_id(*value);
    }
    if (auto value = hid_device.find_location_id()) {
      location_id_ = make_location_id(*value);
    }
    manufacturer_ = hid_device.find_manufacturer();
    product_ = hid_device.find_product();
    serial_number_ = hid_device.find_serial_number();
    transport_ = hid_device.find_transport();
    is_keyboard_ = iokit_utility::is_keyboard(device);
    is_pointing_device_ = iokit_utility::is_pointing_device(device);

    if (product_ && is_keyboard_ && is_pointing_device_) {
      if ((*product_).find("Apple Internal ") != std::string::npos) {
        if (*is_keyboard_ == true && *is_pointing_device_ == false) {
          is_built_in_keyboard_ = true;
        }
        if (*is_keyboard_ == false && *is_pointing_device_ == true) {
          is_built_in_pointing_device_ = true;
        }
      }
    }

    is_karabiner_virtual_hid_device_ = iokit_utility::is_karabiner_virtual_hid_device(device);

    device_identifiers_ = std::make_shared<device_identifiers>(
        vendor_id_.value_or(vendor_id(0)),
        product_id_.value_or(product_id(0)),
        is_keyboard_.value_or(false),
        is_pointing_device_.value_or(false));
  }

  nlohmann::json to_json(void) const {
    nlohmann::json json;

    json["device_id"] = type_safe::get(device_id_);

    if (vendor_id_) {
      json["vendor_id"] = type_safe::get(*vendor_id_);
    }
    if (product_id_) {
      json["product_id"] = type_safe::get(*product_id_);
    }
    if (location_id_) {
      json["location_id"] = type_safe::get(*location_id_);
    }
    if (manufacturer_) {
      json["manufacturer"] = *manufacturer_;
    }
    if (product_) {
      json["product"] = *product_;
    }
    if (serial_number_) {
      json["serial_number"] = *serial_number_;
    }
    if (transport_) {
      json["transport"] = *transport_;
    }
    if (is_keyboard_) {
      json["is_keyboard"] = *is_keyboard_;
    }
    if (is_pointing_device_) {
      json["is_pointing_device"] = *is_pointing_device_;
    }
    if (is_built_in_keyboard_) {
      json["is_built_in_keyboard"] = *is_built_in_keyboard_;
    }
    if (is_built_in_pointing_device_) {
      json["is_built_in_pointing_device"] = *is_built_in_pointing_device_;
    }
    if (is_karabiner_virtual_hid_device_) {
      json["is_karabiner_virtual_hid_device"] = *is_karabiner_virtual_hid_device_;
    }

    return json;
  }

  std::optional<vendor_id> get_vendor_id(void) const {
    return vendor_id_;
  }

  device_properties& set(vendor_id value) {
    vendor_id_ = value;
    return *this;
  }

  std::optional<product_id> get_product_id(void) const {
    return product_id_;
  }

  device_properties& set(product_id value) {
    product_id_ = value;
    return *this;
  }

  std::optional<location_id> get_location_id(void) const {
    return location_id_;
  }

  device_properties& set(location_id value) {
    location_id_ = value;
    return *this;
  }

  std::optional<std::string> get_manufacturer(void) const {
    return manufacturer_;
  }

  device_properties& set_manufacturer(const std::string& value) {
    manufacturer_ = value;
    return *this;
  }

  std::optional<std::string> get_product(void) const {
    return product_;
  }

  device_properties& set_product(const std::string& value) {
    product_ = value;
    return *this;
  }

  std::optional<std::string> get_serial_number(void) const {
    return serial_number_;
  }

  device_properties& set_serial_number(const std::string& value) {
    serial_number_ = value;
    return *this;
  }

  std::optional<std::string> get_transport(void) const {
    return transport_;
  }

  device_properties& set_transport(const std::string& value) {
    transport_ = value;
    return *this;
  }

  std::optional<device_id> get_device_id(void) const {
    return device_id_;
  }

  device_properties& set(device_id value) {
    device_id_ = value;
    return *this;
  }

  std::optional<bool> get_is_keyboard(void) const {
    return is_keyboard_;
  }

  device_properties& set_is_keyboard(bool value) {
    is_keyboard_ = value;
    return *this;
  }

  std::optional<bool> get_is_pointing_device(void) const {
    return is_pointing_device_;
  }

  device_properties& set_is_pointing_device(bool value) {
    is_pointing_device_ = value;
    return *this;
  }

  std::optional<bool> get_is_built_in_keyboard(void) const {
    return is_built_in_keyboard_;
  }

  std::optional<bool> get_is_built_in_pointing_device(void) const {
    return is_built_in_pointing_device_;
  }

  std::optional<bool> get_is_karabiner_virtual_hid_device(void) const {
    return is_karabiner_virtual_hid_device_;
  }

  std::shared_ptr<device_identifiers> get_device_identifiers(void) const {
    return device_identifiers_;
  }

  bool compare(const device_properties& other) {
    // product
    {
      auto p1 = product_.value_or("");
      auto p2 = other.product_.value_or("");
      if (p1 != p2) {
        return p1 < p2;
      }
    }

    // manufacturer
    {
      auto m1 = manufacturer_.value_or("");
      auto m2 = other.manufacturer_.value_or("");
      if (m1 != m2) {
        return m1 < m2;
      }
    }

    // is_keyboard
    {
      auto k1 = is_keyboard_.value_or(false);
      auto k2 = other.is_keyboard_.value_or(false);
      if (k1 != k2) {
        return k1;
      }
    }

    // is_pointing_device
    {
      auto p1 = is_pointing_device_.value_or(false);
      auto p2 = other.is_pointing_device_.value_or(false);
      if (p1 != p2) {
        return p1;
      }
    }

    // device_id
    {
      auto r1 = device_id_;
      auto r2 = other.device_id_;
      if (r1 != r2) {
        return r1 < r2;
      }
    }

    return false;
  }

  bool operator==(const device_properties& other) const {
    return device_id_ == other.device_id_ &&
           vendor_id_ == other.vendor_id_ &&
           product_id_ == other.product_id_ &&
           location_id_ == other.location_id_ &&
           manufacturer_ == other.manufacturer_ &&
           product_ == other.product_ &&
           serial_number_ == other.serial_number_ &&
           transport_ == other.transport_ &&
           is_keyboard_ == other.is_keyboard_ &&
           is_pointing_device_ == other.is_pointing_device_;
  }

private:
  device_id device_id_;
  std::optional<vendor_id> vendor_id_;
  std::optional<product_id> product_id_;
  std::optional<location_id> location_id_;
  std::optional<std::string> manufacturer_;
  std::optional<std::string> product_;
  std::optional<std::string> serial_number_;
  std::optional<std::string> transport_;
  std::optional<bool> is_keyboard_;
  std::optional<bool> is_pointing_device_;
  std::optional<bool> is_built_in_keyboard_;
  std::optional<bool> is_built_in_pointing_device_;
  std::optional<bool> is_karabiner_virtual_hid_device_;
  std::shared_ptr<device_identifiers> device_identifiers_;
};

inline void to_json(nlohmann::json& json, const device_properties& device_properties) {
  json = device_properties.to_json();
}

inline size_t hash_value(const device_properties& value) {
  // We can treat device_id_ as the unique value of device_properties.
  if (auto id = value.get_device_id()) {
    return std::hash<device_id>{}(*id);
  }
  return 0;
}
} // namespace krbn
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "Connection.h"
#include "../libutils/Buffer.h"

CConnection::CConnection(void)
{
	m_Timeout = 0;
	m_AutoDelete = false;
	m_Connected = false;
}

CConnection::~CConnection(void)
{
	CLog::Default()->Printf(0, "~CConnection(%p)", this);
}

void CConnection::SetTimeout(int Timeout)
{
	m_Timeout = Timeout;
}

void CConnection::Reconnect()
{
	Disconnect();
	Connect(m_ConnectString);
}

void CConnection::SendBuffer(CBuffer &buffer)
{
	Send(buffer.getBuffer(), buffer.getSize());
}

<commit_msg>less logging<commit_after>#include "stdafx.h"
#include "Connection.h"
#include "../libutils/Buffer.h"

CConnection::CConnection(void)
{
	m_Timeout = 0;
	m_AutoDelete = false;
	m_Connected = false;
	CLog::Default()->Printf(5, "CConnection(%p)", this);
}

CConnection::~CConnection(void)
{
	CLog::Default()->Printf(5, "~CConnection(%p)", this);
}

void CConnection::SetTimeout(int Timeout)
{
	m_Timeout = Timeout;
}

void CConnection::Reconnect()
{
	Disconnect();
	Connect(m_ConnectString);
}

void CConnection::SendBuffer(CBuffer &buffer)
{
	Send(buffer.getBuffer(), buffer.getSize());
}

<|endoftext|>


<commit_before>/*
 * Outputs weighted random number between 1 and 10^6, inclusive.
 * To generate different values, call "nwgen.exe weight".
 *
 * If parameter "weight"
 * is equals to 0 than used uniformly distributed random.
 *
 * If parameter "weight" > 0 then you can think about it as code like this:
 *
 * result = rnd.next(1, 1000000);
 * for (int i = 0; i < weight; i++)
 *     result = max(result, rnd.next(1, 1000000);
 *
 *
 * If parameter "weight" < 0 then you can think about it as code like this:
 *
 * result = rnd.next(1, 1000000);
 * for (int i = 0; i < -weight; i++)
 *     result = min(result, rnd.next(1, 1000000);
 *
 *
 * It is typical behaviour of "wnext" methods to use this strategy to
 * generate off-center random distribution.
 */

#include "testlib.h"
#include <iostream>

using namespace std;

int main(int argc, char* argv[])
{
    registerGen(argc, argv, 1);

    cout << rnd.wnext(1, 1000000, atoi(argv[1])) << endl;

    return 0;
}
<commit_msg>Update iwgen.cpp<commit_after>/*
 * Outputs weighted random number between 1 and 10^6, inclusive.
 * To generate different values, call "nwgen.exe weight".
 *
 * If parameter "weight"
 * is equals to 0 than used uniformly distributed random.
 *
 * If parameter "weight" > 0 then you can think about it as code like this:
 *
 * result = rnd.next(1, 1000000);
 * for (int i = 0; i < weight; i++)
 *     result = max(result, rnd.next(1, 1000000));
 *
 *
 * If parameter "weight" < 0 then you can think about it as code like this:
 *
 * result = rnd.next(1, 1000000);
 * for (int i = 0; i < -weight; i++)
 *     result = min(result, rnd.next(1, 1000000));
 *
 *
 * It is typical behaviour of "wnext" methods to use this strategy to
 * generate off-center random distribution.
 */

#include "testlib.h"
#include <iostream>

using namespace std;

int main(int argc, char* argv[])
{
    registerGen(argc, argv, 1);

    cout << rnd.wnext(1, 1000000, atoi(argv[1])) << endl;

    return 0;
}
<|endoftext|>


<commit_before>/*
  +----------------------------------------------------------------------+
  | PHP Version 7                                                        |
  +----------------------------------------------------------------------+
  | Copyright (c) 1997-2018 The PHP Group                                |
  +----------------------------------------------------------------------+
  | This source file is subject to version 3.01 of the PHP license,      |
  | that is bundled with this package in the file LICENSE, and is        |
  | available through the world-wide-web at the following url:           |
  | http://www.php.net/license/3_01.txt                                  |
  | If you did not receive a copy of the PHP license and are unable to   |
  | obtain it through the world-wide-web, please send a note to          |
  | license@php.net so we can mail you a copy immediately.               |
  +----------------------------------------------------------------------+
  | Author: Robert Eisele (https://www.xarg.org/)                        |
  +----------------------------------------------------------------------+
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

extern "C" {
#include "php.h"
}
#include "ext/standard/info.h"
#include "php_facedetect.h"

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/objdetect/objdetect.hpp>

using namespace cv;

/* True global resources - no need for thread safety here */
static int le_facedetect;

CascadeClassifier cascade;

static void php_facedetect(INTERNAL_FUNCTION_PARAMETERS, int return_type) {

#ifdef ZEND_ENGINE_3
    zval array;
#else
    zval *array;
#endif
    zval *pArray;

    char *file = NULL, *casc = NULL;
    long flen, clen;

    Mat img;
    Mat gray;
    std::vector<Rect> faces;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s", &file, &flen, &casc, &clen) == FAILURE) {
        RETURN_NULL();
    }

    if (access(file, R_OK) == -1) {
        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Image file is missing or could not be read.\n");
        RETURN_FALSE;
    }

    if (casc && access(casc, R_OK) == -1) {
        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Haar-cascade file is missing or could not be read.\n");
        RETURN_FALSE;
    }

    if (casc && !cascade.load(casc)) {
        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Haar-cascade file could not be loaded.\n");
        RETURN_FALSE;
    }

    if (!casc && cascade.empty()) {
        php_error_docref(NULL TSRMLS_CC, E_WARNING, "No Haar-cascade file loaded.\n");
        RETURN_FALSE;
    }

    img = imread(file);

    if (!img.data) {
        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Image could not be loaded.\n");
        RETURN_FALSE;
    }

    cvtColor(img, gray, COLOR_BGR2GRAY);
    equalizeHist(gray, gray);

    cascade.detectMultiScale(gray, faces, 1.1, 2, 0 | CASCADE_SCALE_IMAGE, Size(30, 30));

    if (return_type) {

        array_init(return_value);

        for (size_t i = 0; i < faces.size(); i++) {
#ifdef ZEND_ENGINE_3
            ZVAL_NEW_ARR(&array);
            pArray = &array;
#else
            MAKE_STD_ZVAL(array);
            pArray = array;
#endif
            array_init(pArray);

            add_assoc_long(pArray, "x", faces[i].x);
            add_assoc_long(pArray, "y", faces[i].y);
            add_assoc_long(pArray, "w", faces[i].width);
            add_assoc_long(pArray, "h", faces[i].height);

            add_next_index_zval(return_value, pArray);
        }

    } else {
        RETVAL_LONG(faces.size());
    }
}

PHP_INI_MH(on_cascade_change) {

    if (ZSTR_LEN(new_value) > 0 && cascade.load(ZSTR_VAL(new_value)))
        return SUCCESS;
    else
        return FAILURE;
}

PHP_INI_BEGIN()
PHP_INI_ENTRY("facedetect.cascade", "", PHP_INI_ALL, on_cascade_change)
PHP_INI_END()

PHP_FUNCTION(face_detect) {
    php_facedetect(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
}

PHP_FUNCTION(face_count) {
    php_facedetect(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
}

/* {{{ PHP_MINIT_FUNCTION
 */
PHP_MINIT_FUNCTION(facedetect) {
    REGISTER_INI_ENTRIES();
    return SUCCESS;
}
/* }}} */

/* {{{ PHP_MSHUTDOWN_FUNCTION
 */
PHP_MSHUTDOWN_FUNCTION(facedetect) {
    UNREGISTER_INI_ENTRIES();
    return SUCCESS;
}
/* }}} */

/* {{{ PHP_MINFO_FUNCTION
 */
PHP_MINFO_FUNCTION(facedetect) {
    php_info_print_table_start();
    php_info_print_table_row(2, "facedetect support", "enabled");
    php_info_print_table_row(2, "facedetect version", PHP_FACEDETECT_VERSION);
    php_info_print_table_row(2, "OpenCV version", CV_VERSION);
    php_info_print_table_end();
}
/* }}} */

/* {{{ facedetect_functions[]
 *
 * Every user visible function must have an entry in facedetect_functions[].
 */
const zend_function_entry facedetect_functions[] = {
    PHP_FE(face_detect, NULL)
    PHP_FE(face_count, NULL)
    PHP_FE_END
};
/* }}} */

/* {{{ facedetect_module_entry
 */
zend_module_entry facedetect_module_entry = {
    STANDARD_MODULE_HEADER,
    "facedetect",
    facedetect_functions,
    PHP_MINIT(facedetect),
    PHP_MSHUTDOWN(facedetect),
    NULL,
    NULL,
    PHP_MINFO(facedetect),
    PHP_FACEDETECT_VERSION,
    STANDARD_MODULE_PROPERTIES
};
/* }}} */

#ifdef COMPILE_DL_FACEDETECT
#ifdef ZTS
ZEND_TSRMLS_CACHE_DEFINE()
#endif
extern "C" {
    ZEND_GET_MODULE(facedetect)
}
#endif

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 * vim600: noet sw=4 ts=4 fdm=marker
 * vim<600: noet sw=4 ts=4
 */
<commit_msg>add missing arginfo + PHP 8 compatibility<commit_after>/*
  +----------------------------------------------------------------------+
  | PHP Version 7                                                        |
  +----------------------------------------------------------------------+
  | Copyright (c) 1997-2018 The PHP Group                                |
  +----------------------------------------------------------------------+
  | This source file is subject to version 3.01 of the PHP license,      |
  | that is bundled with this package in the file LICENSE, and is        |
  | available through the world-wide-web at the following url:           |
  | http://www.php.net/license/3_01.txt                                  |
  | If you did not receive a copy of the PHP license and are unable to   |
  | obtain it through the world-wide-web, please send a note to          |
  | license@php.net so we can mail you a copy immediately.               |
  +----------------------------------------------------------------------+
  | Author: Robert Eisele (https://www.xarg.org/)                        |
  +----------------------------------------------------------------------+
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

extern "C" {
#include "php.h"
}
#include "ext/standard/info.h"
#include "php_facedetect.h"

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/objdetect/objdetect.hpp>

/* for PHP 8 */
#ifndef TSRMLS_CC
#define TSRMLS_CC
#endif

using namespace cv;

CascadeClassifier cascade;

static void php_facedetect(INTERNAL_FUNCTION_PARAMETERS, int return_type) {

#ifdef ZEND_ENGINE_3
    zval array;
#else
    zval *array;
#endif
    zval *pArray;

    char *file = NULL, *casc = NULL;
#if PHP_VERSION_ID < 70000
    long flen, clen;
#else
    size_t flen, clen;
#endif

    Mat img;
    Mat gray;
    std::vector<Rect> faces;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|p", &file, &flen, &casc, &clen) == FAILURE) {
        RETURN_NULL();
    }

    if (access(file, R_OK) == -1) {
        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Image file is missing or could not be read.\n");
        RETURN_FALSE;
    }

    if (casc && access(casc, R_OK) == -1) {
        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Haar-cascade file is missing or could not be read.\n");
        RETURN_FALSE;
    }

    if (casc && !cascade.load(casc)) {
        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Haar-cascade file could not be loaded.\n");
        RETURN_FALSE;
    }

    if (!casc && cascade.empty()) {
        php_error_docref(NULL TSRMLS_CC, E_WARNING, "No Haar-cascade file loaded.\n");
        RETURN_FALSE;
    }

    img = imread(file);

    if (!img.data) {
        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Image could not be loaded.\n");
        RETURN_FALSE;
    }

    cvtColor(img, gray, COLOR_BGR2GRAY);
    equalizeHist(gray, gray);

    cascade.detectMultiScale(gray, faces, 1.1, 2, 0 | CASCADE_SCALE_IMAGE, Size(30, 30));

    if (return_type) {

        array_init(return_value);

        for (size_t i = 0; i < faces.size(); i++) {
#ifdef ZEND_ENGINE_3
            ZVAL_NEW_ARR(&array);
            pArray = &array;
#else
            MAKE_STD_ZVAL(array);
            pArray = array;
#endif
            array_init(pArray);

            add_assoc_long(pArray, "x", faces[i].x);
            add_assoc_long(pArray, "y", faces[i].y);
            add_assoc_long(pArray, "w", faces[i].width);
            add_assoc_long(pArray, "h", faces[i].height);

            add_next_index_zval(return_value, pArray);
        }

    } else {
        RETVAL_LONG(faces.size());
    }
}

PHP_INI_MH(on_cascade_change) {

    if (ZSTR_LEN(new_value) > 0 && cascade.load(ZSTR_VAL(new_value)))
        return SUCCESS;
    else
        return FAILURE;
}

PHP_INI_BEGIN()
PHP_INI_ENTRY("facedetect.cascade", "", PHP_INI_ALL, on_cascade_change)
PHP_INI_END()

#if PHP_VERSION_ID < 80000
ZEND_BEGIN_ARG_INFO_EX(arginfo_face_detect, 0, 0, 1)
	ZEND_ARG_INFO(0, image_path)
	ZEND_ARG_INFO(0, cascade_path)
ZEND_END_ARG_INFO()

#define arginfo_face_count arginfo_face_detect

#else
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_face_detect, 0, 1, MAY_BE_FALSE|MAY_BE_ARRAY)
	ZEND_ARG_TYPE_INFO(0, image_path, IS_STRING, 0)
	ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, cascade_path, IS_STRING, 1, "null")
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_face_count, 0, 1, MAY_BE_FALSE|MAY_BE_LONG)
	ZEND_ARG_TYPE_INFO(0, image_path, IS_STRING, 0)
	ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, cascade_path, IS_STRING, 1, "null")
ZEND_END_ARG_INFO()
#endif

PHP_FUNCTION(face_detect) {
    php_facedetect(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
}

PHP_FUNCTION(face_count) {
    php_facedetect(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
}

/* {{{ PHP_MINIT_FUNCTION
 */
PHP_MINIT_FUNCTION(facedetect) {
    REGISTER_INI_ENTRIES();
    return SUCCESS;
}
/* }}} */

/* {{{ PHP_MSHUTDOWN_FUNCTION
 */
PHP_MSHUTDOWN_FUNCTION(facedetect) {
    UNREGISTER_INI_ENTRIES();
    return SUCCESS;
}
/* }}} */

/* {{{ PHP_MINFO_FUNCTION
 */
PHP_MINFO_FUNCTION(facedetect) {
    php_info_print_table_start();
    php_info_print_table_row(2, "facedetect support", "enabled");
    php_info_print_table_row(2, "facedetect version", PHP_FACEDETECT_VERSION);
    php_info_print_table_row(2, "OpenCV version", CV_VERSION);
    php_info_print_table_end();
}
/* }}} */

/* {{{ facedetect_functions[]
 *
 * Every user visible function must have an entry in facedetect_functions[].
 */
const zend_function_entry facedetect_functions[] = {
    PHP_FE(face_detect, arginfo_face_detect)
    PHP_FE(face_count, arginfo_face_count)
    PHP_FE_END
};
/* }}} */

/* {{{ facedetect_module_entry
 */
zend_module_entry facedetect_module_entry = {
    STANDARD_MODULE_HEADER,
    "facedetect",
    facedetect_functions,
    PHP_MINIT(facedetect),
    PHP_MSHUTDOWN(facedetect),
    NULL,
    NULL,
    PHP_MINFO(facedetect),
    PHP_FACEDETECT_VERSION,
    STANDARD_MODULE_PROPERTIES
};
/* }}} */

#ifdef COMPILE_DL_FACEDETECT
#ifdef ZTS
ZEND_TSRMLS_CACHE_DEFINE()
#endif
extern "C" {
    ZEND_GET_MODULE(facedetect)
}
#endif

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 * vim600: noet sw=4 ts=4 fdm=marker
 * vim<600: noet sw=4 ts=4
 */
<|endoftext|>


<commit_before>#include "base/logging.h"
#include "gl_state.h"
#ifdef _WIN32
#include "GL/wglew.h"
#endif

#if defined(USING_GLES2)
#if defined(ANDROID) || defined(BLACKBERRY)
PFNGLALPHAFUNCQCOMPROC glAlphaFuncQCOM;
PFNEGLGETSYSTEMTIMEFREQUENCYNVPROC eglGetSystemTimeFrequencyNV;
PFNEGLGETSYSTEMTIMENVPROC eglGetSystemTimeNV;
PFNGLMAPBUFFERPROC glMapBuffer;
#endif
#if !defined(IOS) && !defined(__SYMBIAN32__) && !defined(MEEGO_EDITION_HARMATTAN) && !defined(MAEMO)
PFNGLDISCARDFRAMEBUFFEREXTPROC glDiscardFramebufferEXT;
PFNGLGENVERTEXARRAYSOESPROC glGenVertexArraysOES;
PFNGLBINDVERTEXARRAYOESPROC glBindVertexArrayOES;
PFNGLDELETEVERTEXARRAYSOESPROC glDeleteVertexArraysOES;
PFNGLISVERTEXARRAYOESPROC glIsVertexArrayOES;
#endif
#endif

OpenGLState glstate;
GLExtensions gl_extensions;
std::string g_all_gl_extensions;
std::string g_all_egl_extensions;

int OpenGLState::state_count = 0;

void OpenGLState::Initialize() {
	if(initialized) return;

	Restore();

	initialized = true;
}

void OpenGLState::Restore() {
	int count = 0;

	blend.restore(); count++;
	blendEquation.restore(); count++;
	blendFuncSeparate.restore(); count++;
	blendColor.restore(); count++;

#if defined(ANDROID) || defined(BLACKBERRY)
	if (gl_extensions.QCOM_alpha_test) {
		alphaTestQCOM.restore();
	}
	count++;
	if (gl_extensions.QCOM_alpha_test) {
		alphaFuncQCOM.restore();
	}
	count++;
#endif

	scissorTest.restore(); count++;
	scissorRect.restore(); count++;

	cullFace.restore(); count++;
	cullFaceMode.restore(); count++;
	frontFace.restore(); count++;

	depthTest.restore(); count++;
	depthRange.restore(); count++;
	depthFunc.restore(); count++;
	depthWrite.restore(); count++;

	colorMask.restore(); count++;
	viewport.restore(); count++;

	stencilTest.restore(); count++;
	stencilOp.restore(); count++;
	stencilFunc.restore(); count++;

	dither.restore(); count++;

#if !defined(USING_GLES2)
	colorLogicOp.restore(); count++;
	logicOp.restore(); count++;
#endif

	if (count != state_count) {
		FLOG("OpenGLState::Restore is missing some states");
	}
}

// http://stackoverflow.com/questions/16147700/opengl-es-using-tegra-specific-extensions-gl-ext-texture-array

void CheckGLExtensions() {
	static bool done = false;
	if (done)
		return;
	done = true;

	memset(&gl_extensions, 0, sizeof(gl_extensions));

	const char *extString = (const char *)glGetString(GL_EXTENSIONS);
	if (extString) {
		g_all_gl_extensions = extString;
	} else {
		g_all_gl_extensions = "";
	}

#ifdef WIN32
	const char *wglString = 0;
	if (wglGetExtensionsStringEXT)
		wglString = wglGetExtensionsStringEXT();
	if (wglString) {
		gl_extensions.EXT_swap_control_tear = strstr(wglString, "WGL_EXT_swap_control_tear") != 0;
		g_all_egl_extensions = wglString;
	} else {
		g_all_egl_extensions = "";
	}
#elif !defined(USING_GLES2)
	// const char *glXString = glXQueryExtensionString();
	// gl_extensions.EXT_swap_control_tear = strstr(glXString, "GLX_EXT_swap_control_tear") != 0;
#endif

#ifdef USING_GLES2
	gl_extensions.OES_packed_depth_stencil = strstr(extString, "GL_OES_packed_depth_stencil") != 0;
	gl_extensions.OES_depth24 = strstr(extString, "GL_OES_depth24") != 0;
	gl_extensions.OES_depth_texture = strstr(extString, "GL_OES_depth_texture") != 0;
	gl_extensions.OES_mapbuffer = strstr(extString, "GL_OES_mapbuffer") != 0;
	gl_extensions.EXT_shader_framebuffer_fetch = (strstr(extString, "GL_EXT_shader_framebuffer_fetch") != 0) || (strstr(extString, "GL_NV_shader_framebuffer_fetch") != 0);
#if defined(IOS) || defined(__SYMBIAN32__) || defined(MEEGO_EDITION_HARMATTAN) || defined(MAEMO)
	gl_extensions.OES_vertex_array_object = false;
	gl_extensions.EXT_discard_framebuffer = false;
#else
	gl_extensions.OES_vertex_array_object = strstr(extString, "GL_OES_vertex_array_object") != 0;
	if (gl_extensions.OES_vertex_array_object) {
		glGenVertexArraysOES = (PFNGLGENVERTEXARRAYSOESPROC)eglGetProcAddress ( "glGenVertexArraysOES" );
		glBindVertexArrayOES = (PFNGLBINDVERTEXARRAYOESPROC)eglGetProcAddress ( "glBindVertexArrayOES" );
		glDeleteVertexArraysOES = (PFNGLDELETEVERTEXARRAYSOESPROC)eglGetProcAddress ( "glDeleteVertexArraysOES" );
		glIsVertexArrayOES = (PFNGLISVERTEXARRAYOESPROC)eglGetProcAddress ( "glIsVertexArrayOES" );
	}

	gl_extensions.EXT_discard_framebuffer = strstr(extString, "GL_EXT_discard_framebuffer") != 0;
	if (gl_extensions.EXT_discard_framebuffer) {
		glDiscardFramebufferEXT = (PFNGLDISCARDFRAMEBUFFEREXTPROC)eglGetProcAddress("glDiscardFramebufferEXT");
	}

#endif
#endif

#if defined(ANDROID) || defined(BLACKBERRY)
	if (gl_extensions.OES_mapbuffer) {
		glMapBuffer = (PFNGLMAPBUFFERPROC)eglGetProcAddress( "glMapBufferOES" );
	}
	gl_extensions.QCOM_binning_control = strstr(extString, "GL_QCOM_binning_control") != 0;
	gl_extensions.QCOM_alpha_test = strstr(extString, "GL_QCOM_alpha_test") != 0;
	// Load extensions that are not auto-loaded by Android.
	if (gl_extensions.QCOM_alpha_test) {
		glAlphaFuncQCOM = (PFNGLALPHAFUNCQCOMPROC)eglGetProcAddress("glAlphaFuncQCOM");
	}

	// Look for EGL extensions
	EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);

	const char *eglString = eglQueryString(display, EGL_EXTENSIONS);
	if (eglString) {
		g_all_egl_extensions = eglString;

		gl_extensions.EGL_NV_system_time = strstr(eglString, "EGL_NV_system_time") != 0;
		gl_extensions.EGL_NV_coverage_sample = strstr(eglString, "EGL_NV_coverage_sample") != 0;

		if (gl_extensions.EGL_NV_system_time) {
			eglGetSystemTimeNV = (PFNEGLGETSYSTEMTIMENVPROC) eglGetProcAddress("eglGetSystemTimeNV");
			eglGetSystemTimeFrequencyNV = (PFNEGLGETSYSTEMTIMEFREQUENCYNVPROC) eglGetProcAddress("eglGetSystemTimeFrequencyNV");
		}
	} else {
		g_all_egl_extensions = "";
	}

#endif

#ifdef USING_GLES2
	gl_extensions.FBO_ARB = true;
	gl_extensions.FBO_EXT = false;
#else
	gl_extensions.FBO_ARB = false;
	gl_extensions.FBO_EXT = false;
	if (extString) {
		gl_extensions.FBO_ARB = strstr(extString, "GL_ARB_framebuffer_object") != 0;
		gl_extensions.FBO_EXT = strstr(extString, "GL_EXT_framebuffer_object") != 0;
	}
#endif
}

void OpenGLState::SetVSyncInterval(int interval) {
#ifdef _WIN32
	if( wglSwapIntervalEXT )
		wglSwapIntervalEXT(interval);
#endif
}
<commit_msg>Add GL_ARB_pixel_buffer_object detection<commit_after>#include "base/logging.h"
#include "gl_state.h"
#ifdef _WIN32
#include "GL/wglew.h"
#endif

#if defined(USING_GLES2)
#if defined(ANDROID) || defined(BLACKBERRY)
PFNGLALPHAFUNCQCOMPROC glAlphaFuncQCOM;
PFNEGLGETSYSTEMTIMEFREQUENCYNVPROC eglGetSystemTimeFrequencyNV;
PFNEGLGETSYSTEMTIMENVPROC eglGetSystemTimeNV;
PFNGLMAPBUFFERPROC glMapBuffer;
#endif
#if !defined(IOS) && !defined(__SYMBIAN32__) && !defined(MEEGO_EDITION_HARMATTAN) && !defined(MAEMO)
PFNGLDISCARDFRAMEBUFFEREXTPROC glDiscardFramebufferEXT;
PFNGLGENVERTEXARRAYSOESPROC glGenVertexArraysOES;
PFNGLBINDVERTEXARRAYOESPROC glBindVertexArrayOES;
PFNGLDELETEVERTEXARRAYSOESPROC glDeleteVertexArraysOES;
PFNGLISVERTEXARRAYOESPROC glIsVertexArrayOES;
#endif
#endif

OpenGLState glstate;
GLExtensions gl_extensions;
std::string g_all_gl_extensions;
std::string g_all_egl_extensions;

int OpenGLState::state_count = 0;

void OpenGLState::Initialize() {
	if(initialized) return;

	Restore();

	initialized = true;
}

void OpenGLState::Restore() {
	int count = 0;

	blend.restore(); count++;
	blendEquation.restore(); count++;
	blendFuncSeparate.restore(); count++;
	blendColor.restore(); count++;

#if defined(ANDROID) || defined(BLACKBERRY)
	if (gl_extensions.QCOM_alpha_test) {
		alphaTestQCOM.restore();
	}
	count++;
	if (gl_extensions.QCOM_alpha_test) {
		alphaFuncQCOM.restore();
	}
	count++;
#endif

	scissorTest.restore(); count++;
	scissorRect.restore(); count++;

	cullFace.restore(); count++;
	cullFaceMode.restore(); count++;
	frontFace.restore(); count++;

	depthTest.restore(); count++;
	depthRange.restore(); count++;
	depthFunc.restore(); count++;
	depthWrite.restore(); count++;

	colorMask.restore(); count++;
	viewport.restore(); count++;

	stencilTest.restore(); count++;
	stencilOp.restore(); count++;
	stencilFunc.restore(); count++;

	dither.restore(); count++;

#if !defined(USING_GLES2)
	colorLogicOp.restore(); count++;
	logicOp.restore(); count++;
#endif

	if (count != state_count) {
		FLOG("OpenGLState::Restore is missing some states");
	}
}

// http://stackoverflow.com/questions/16147700/opengl-es-using-tegra-specific-extensions-gl-ext-texture-array

void CheckGLExtensions() {
	static bool done = false;
	if (done)
		return;
	done = true;

	memset(&gl_extensions, 0, sizeof(gl_extensions));

	const char *extString = (const char *)glGetString(GL_EXTENSIONS);
	if (extString) {
		g_all_gl_extensions = extString;
	} else {
		g_all_gl_extensions = "";
	}

#ifdef WIN32
	const char *wglString = 0;
	if (wglGetExtensionsStringEXT)
		wglString = wglGetExtensionsStringEXT();
	if (wglString) {
		gl_extensions.EXT_swap_control_tear = strstr(wglString, "WGL_EXT_swap_control_tear") != 0;
		g_all_egl_extensions = wglString;
	} else {
		g_all_egl_extensions = "";
	}
#elif !defined(USING_GLES2)
	// const char *glXString = glXQueryExtensionString();
	// gl_extensions.EXT_swap_control_tear = strstr(glXString, "GLX_EXT_swap_control_tear") != 0;
#endif

#ifdef USING_GLES2
	gl_extensions.OES_packed_depth_stencil = strstr(extString, "GL_OES_packed_depth_stencil") != 0;
	gl_extensions.OES_depth24 = strstr(extString, "GL_OES_depth24") != 0;
	gl_extensions.OES_depth_texture = strstr(extString, "GL_OES_depth_texture") != 0;
	gl_extensions.OES_mapbuffer = strstr(extString, "GL_OES_mapbuffer") != 0;
	gl_extensions.EXT_shader_framebuffer_fetch = (strstr(extString, "GL_EXT_shader_framebuffer_fetch") != 0) || (strstr(extString, "GL_NV_shader_framebuffer_fetch") != 0);
#if defined(IOS) || defined(__SYMBIAN32__) || defined(MEEGO_EDITION_HARMATTAN) || defined(MAEMO)
	gl_extensions.OES_vertex_array_object = false;
	gl_extensions.EXT_discard_framebuffer = false;
#else
	gl_extensions.OES_vertex_array_object = strstr(extString, "GL_OES_vertex_array_object") != 0;
	if (gl_extensions.OES_vertex_array_object) {
		glGenVertexArraysOES = (PFNGLGENVERTEXARRAYSOESPROC)eglGetProcAddress ( "glGenVertexArraysOES" );
		glBindVertexArrayOES = (PFNGLBINDVERTEXARRAYOESPROC)eglGetProcAddress ( "glBindVertexArrayOES" );
		glDeleteVertexArraysOES = (PFNGLDELETEVERTEXARRAYSOESPROC)eglGetProcAddress ( "glDeleteVertexArraysOES" );
		glIsVertexArrayOES = (PFNGLISVERTEXARRAYOESPROC)eglGetProcAddress ( "glIsVertexArrayOES" );
	}

	gl_extensions.EXT_discard_framebuffer = strstr(extString, "GL_EXT_discard_framebuffer") != 0;
	if (gl_extensions.EXT_discard_framebuffer) {
		glDiscardFramebufferEXT = (PFNGLDISCARDFRAMEBUFFEREXTPROC)eglGetProcAddress("glDiscardFramebufferEXT");
	}

#endif
#endif

#if defined(ANDROID) || defined(BLACKBERRY)
	if (gl_extensions.OES_mapbuffer) {
		glMapBuffer = (PFNGLMAPBUFFERPROC)eglGetProcAddress( "glMapBufferOES" );
	}
	gl_extensions.QCOM_binning_control = strstr(extString, "GL_QCOM_binning_control") != 0;
	gl_extensions.QCOM_alpha_test = strstr(extString, "GL_QCOM_alpha_test") != 0;
	// Load extensions that are not auto-loaded by Android.
	if (gl_extensions.QCOM_alpha_test) {
		glAlphaFuncQCOM = (PFNGLALPHAFUNCQCOMPROC)eglGetProcAddress("glAlphaFuncQCOM");
	}

	// Look for EGL extensions
	EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);

	const char *eglString = eglQueryString(display, EGL_EXTENSIONS);
	if (eglString) {
		g_all_egl_extensions = eglString;

		gl_extensions.EGL_NV_system_time = strstr(eglString, "EGL_NV_system_time") != 0;
		gl_extensions.EGL_NV_coverage_sample = strstr(eglString, "EGL_NV_coverage_sample") != 0;

		if (gl_extensions.EGL_NV_system_time) {
			eglGetSystemTimeNV = (PFNEGLGETSYSTEMTIMENVPROC) eglGetProcAddress("eglGetSystemTimeNV");
			eglGetSystemTimeFrequencyNV = (PFNEGLGETSYSTEMTIMEFREQUENCYNVPROC) eglGetProcAddress("eglGetSystemTimeFrequencyNV");
		}
	} else {
		g_all_egl_extensions = "";
	}

#endif

#ifdef USING_GLES2
	gl_extensions.FBO_ARB = true;
	gl_extensions.FBO_EXT = false;
#else
	gl_extensions.FBO_ARB = false;
	gl_extensions.FBO_EXT = false;
	gl_extensions.PBO_ARB = true;
	if (extString) {
		gl_extensions.FBO_ARB = strstr(extString, "GL_ARB_framebuffer_object") != 0;
		gl_extensions.FBO_EXT = strstr(extString, "GL_EXT_framebuffer_object") != 0;
		gl_extensions.PBO_ARB = strstr(extString, "GL_ARB_pixel_buffer_object") != 0;
	}
#endif
}

void OpenGLState::SetVSyncInterval(int interval) {
#ifdef _WIN32
	if( wglSwapIntervalEXT )
		wglSwapIntervalEXT(interval);
#endif
}
<|endoftext|>


<commit_before>#include <assert.h>
#include "gl_state.h"
#ifdef _WIN32
#include "GL/wglew.h"
#endif

#ifdef USING_GLES2
PFNGLALPHAFUNCQCOMPROC glAlphaFuncQCOM;
#endif

OpenGLState glstate;
GLExtensions gl_extensions;

int OpenGLState::state_count = 0;

void OpenGLState::Initialize() {
	if(initialized) return;

	Restore();

	initialized = true;
}

void OpenGLState::Restore() {
	int count = 0;
	blend.restore(); count++;
	blendEquation.restore(); count++;
	blendFunc.restore(); count++;
	blendColor.restore(); count++;

	scissorTest.restore(); count++;
	scissorRect.restore(); count++;

	cullFace.restore(); count++;
	cullFaceMode.restore(); count++;
	frontFace.restore(); count++;

	depthTest.restore(); count++;
	depthRange.restore(); count++;
	depthFunc.restore(); count++;
	depthWrite.restore(); count++;

	colorMask.restore(); count++;
	viewport.restore(); count++;

	stencilTest.restore(); count++;
	stencilOp.restore(); count++;
	stencilFunc.restore(); count++;

	dither.restore(); count++;

	assert(count == state_count && "OpenGLState::Restore is missing some states");
}

// http://stackoverflow.com/questions/16147700/opengl-es-using-tegra-specific-extensions-gl-ext-texture-array

void CheckGLExtensions() {
	static bool done = false;
	if (done)
		return;
	done = true;

	memset(&gl_extensions, 0, sizeof(gl_extensions));

	const char *extString = (const char *)glGetString(GL_EXTENSIONS);

#ifdef WIN32
	const char *wglString = wglGetExtensionsStringEXT();
	gl_extensions.EXT_swap_control_tear = strstr(wglString, "WGL_EXT_swap_control_tear") != 0;
#elif !defined(USING_GLES2)
	// const char *glXString = glXQueryExtensionString();
	// gl_extensions.EXT_swap_control_tear = strstr(glXString, "GLX_EXT_swap_control_tear") != 0;
#endif
	gl_extensions.OES_packed_depth_stencil = strstr(extString, "GL_OES_packed_depth_stencil") != 0;
	gl_extensions.OES_depth24 = strstr(extString, "GL_OES_depth24") != 0;
	gl_extensions.OES_depth_texture = strstr(extString, "GL_OES_depth_texture") != 0;
	gl_extensions.EXT_discard_framebuffer = strstr(extString, "GL_EXT_discard_framebuffer") != 0;

	// TODO: Change to USING_GLES2 if it works on those other platforms too
#ifdef ANDROID
	gl_extensions.QCOM_alpha_test = strstr(extString, "GL_QCOM_alpha_test") != 0;
	// Load extensions that are not auto-loaded by Android.
	glAlphaFuncQCOM = (PFNGLALPHAFUNCQCOMPROC)eglGetProcAddress("glAlphaFuncQCOM");
#endif

#ifdef USING_GLES2
	gl_extensions.FBO_ARB = true;
	gl_extensions.FBO_EXT = false;
#else
	gl_extensions.FBO_ARB = strstr(extString, "GL_ARB_framebuffer_object") != 0;
	gl_extensions.FBO_EXT = strstr(extString, "GL_EXT_framebuffer_object") != 0;
#endif
}

void OpenGLState::SetVSyncInterval(int interval) {
#ifdef _WIN32
	if( wglSwapIntervalEXT )
		wglSwapIntervalEXT(interval);
#endif
}<commit_msg>Just for cleanness, check first.<commit_after>#include <assert.h>
#include "gl_state.h"
#ifdef _WIN32
#include "GL/wglew.h"
#endif

#ifdef USING_GLES2
PFNGLALPHAFUNCQCOMPROC glAlphaFuncQCOM;
#endif

OpenGLState glstate;
GLExtensions gl_extensions;

int OpenGLState::state_count = 0;

void OpenGLState::Initialize() {
	if(initialized) return;

	Restore();

	initialized = true;
}

void OpenGLState::Restore() {
	int count = 0;
	blend.restore(); count++;
	blendEquation.restore(); count++;
	blendFunc.restore(); count++;
	blendColor.restore(); count++;

	scissorTest.restore(); count++;
	scissorRect.restore(); count++;

	cullFace.restore(); count++;
	cullFaceMode.restore(); count++;
	frontFace.restore(); count++;

	depthTest.restore(); count++;
	depthRange.restore(); count++;
	depthFunc.restore(); count++;
	depthWrite.restore(); count++;

	colorMask.restore(); count++;
	viewport.restore(); count++;

	stencilTest.restore(); count++;
	stencilOp.restore(); count++;
	stencilFunc.restore(); count++;

	dither.restore(); count++;

	assert(count == state_count && "OpenGLState::Restore is missing some states");
}

// http://stackoverflow.com/questions/16147700/opengl-es-using-tegra-specific-extensions-gl-ext-texture-array

void CheckGLExtensions() {
	static bool done = false;
	if (done)
		return;
	done = true;

	memset(&gl_extensions, 0, sizeof(gl_extensions));

	const char *extString = (const char *)glGetString(GL_EXTENSIONS);

#ifdef WIN32
	const char *wglString = wglGetExtensionsStringEXT();
	gl_extensions.EXT_swap_control_tear = strstr(wglString, "WGL_EXT_swap_control_tear") != 0;
#elif !defined(USING_GLES2)
	// const char *glXString = glXQueryExtensionString();
	// gl_extensions.EXT_swap_control_tear = strstr(glXString, "GLX_EXT_swap_control_tear") != 0;
#endif
	gl_extensions.OES_packed_depth_stencil = strstr(extString, "GL_OES_packed_depth_stencil") != 0;
	gl_extensions.OES_depth24 = strstr(extString, "GL_OES_depth24") != 0;
	gl_extensions.OES_depth_texture = strstr(extString, "GL_OES_depth_texture") != 0;
	gl_extensions.EXT_discard_framebuffer = strstr(extString, "GL_EXT_discard_framebuffer") != 0;

	// TODO: Change to USING_GLES2 if it works on those other platforms too
#ifdef ANDROID
	gl_extensions.QCOM_alpha_test = strstr(extString, "GL_QCOM_alpha_test") != 0;
	// Load extensions that are not auto-loaded by Android.
	if (gl_extensions.QCOM_alpha_test) {
		glAlphaFuncQCOM = (PFNGLALPHAFUNCQCOMPROC)eglGetProcAddress("glAlphaFuncQCOM");
	}
#endif

#ifdef USING_GLES2
	gl_extensions.FBO_ARB = true;
	gl_extensions.FBO_EXT = false;
#else
	gl_extensions.FBO_ARB = strstr(extString, "GL_ARB_framebuffer_object") != 0;
	gl_extensions.FBO_EXT = strstr(extString, "GL_EXT_framebuffer_object") != 0;
#endif
}

void OpenGLState::SetVSyncInterval(int interval) {
#ifdef _WIN32
	if( wglSwapIntervalEXT )
		wglSwapIntervalEXT(interval);
#endif
}<|endoftext|>


<commit_before>#include "demoParticle.h"

//------------------------------------------------------------------
demoParticle::demoParticle(){
	attractPoints = NULL;
	attractPoint = NULL;
}

//------------------------------------------------------------------
void demoParticle::setMode(particleMode newMode){
	mode = newMode;
}

//------------------------------------------------------------------
void demoParticle::setAttractPoints( vector <ofPoint> * attract ){
	attractPoints = attract;
}

void demoParticle::setAttractPoint(ofPoint * attractP) {
	attractPoint = attractP;
}
//------------------------------------------------------------------
void demoParticle::reset(){
	//the unique val allows us to set properties slightly differently for each particle
	uniqueVal = ofRandom(-10000, 10000); //TODO: move hard coded values into GUI

	//pos.x = ofRandomWidth();
	//pos.y = ofRandomHeight();

	vel.x = ofRandom(-3.9, 3.9); //TODO: move hard coded values into GUI
	vel.y = ofRandom(-3.9, 3.9); //TODO: move hard coded values into GUI

	frc   = ofPoint(0,0,0);

	scale = ofRandom(0.5, 1.0);//TODO: move hard coded values into GUI

	if( mode == PARTICLE_MODE_NOISE ){
		drag  = ofRandom(0.97, 0.99);//TODO: move hard coded values into GUI
		vel.y = fabs(vel.y) * 3.0; //make the particles all be going down //TODO: move hard coded values into GUI
	}else{
		drag  = ofRandom(0.95, 0.998);	//TODO: move hard coded values into GUI
	}
}

//------------------------------------------------------------------
void demoParticle::update(){

	//1 - APPLY THE FORCES BASED ON WHICH MODE WE ARE IN

	if( mode == PARTICLE_MODE_ATTRACT ){
		ofPoint attractPt(ofGetMouseX(), ofGetMouseY());
		frc = attractPt-pos; // we get the attraction force/vector by looking at the mouse pos relative to our pos
		frc.normalize(); //by normalizing we disregard how close the particle is to the attraction point

		vel *= drag; //apply drag
		vel += frc * 0.6; //apply force //TODO: move hard coded values into GUI
	}
	else if( mode == PARTICLE_MODE_REPEL ){ //TODO: update this to be repelled by attract points
		ofPoint attractPt(ofGetMouseX(), ofGetMouseY());
		frc = attractPt-pos;

		//let get the distance and only repel points close to the mouse
		float dist = frc.length();
		frc.normalize();

		vel *= drag;
		if( dist < 150 ){//TODO: move hard coded values into GUI
			vel += -frc * 0.6; //notice the frc is negative //TODO: move hard coded values into GUI
		}else{
			//if the particles are not close to us, lets add a little bit of random movement using noise. this is where uniqueVal comes in handy.
			frc.x = ofSignedNoise(uniqueVal, pos.y * 0.01, ofGetElapsedTimef()*0.2);//TODO: move hard coded values into GUI
			frc.y = ofSignedNoise(uniqueVal, pos.x * 0.01, ofGetElapsedTimef()*0.2);//TODO: move hard coded values into GUI
			vel += frc * 0.04;//TODO: move hard coded values into GUI
		}
	}
	else if( mode == PARTICLE_MODE_NOISE || attractPoint == NULL){
		//lets simulate falling snow
		//the fake wind is meant to add a shift to the particles based on where in x they are
		//we add pos.y as an arg so to prevent obvious vertical banding around x values - try removing the pos.y * 0.006 to see the banding
		float fakeWindX = ofSignedNoise(pos.x * 0.003, pos.y * 0.006, ofGetElapsedTimef() * 0.6);

		frc.x = fakeWindX * 0.25 + ofSignedNoise(uniqueVal, pos.y * 0.04) * 0.6;
		frc.y = ofSignedNoise(uniqueVal, pos.x * 0.006, ofGetElapsedTimef()*0.2) * 0.09 + 0.18;

		vel *= drag;
		vel += frc * 0.4;

		//we do this so as to skip the bounds check for the bottom and make the particles go back to the top of the screen
		if( pos.y + vel.y > ofGetHeight() ){
			pos.y -= ofGetHeight();
		}
	}
	else if( mode == PARTICLE_MODE_NEAREST_POINTS ){

		if( attractPoints ){

			//1 - find closest attractPoint
			ofPoint closestPt;
			int closest = -1;
			float closestDist = 9999999;

			for(unsigned int i = 0; i < attractPoints->size(); i++){
				float lenSq = ( attractPoints->at(i)-pos ).lengthSquared();
				if( lenSq < closestDist ){
					closestDist = lenSq;
					closest = i;
				}
			}

			//2 - if we have a closest point - lets calcuate the force towards it
			if( closest != -1 ){
				closestPt = attractPoints->at(closest);
				float dist = sqrt(closestDist);

				//in this case we don't normalize as we want to have the force proportional to distance
				frc = closestPt - pos;

				vel *= drag;

				//lets also limit our attraction to a certain distance and don't apply if 'n' key is pressed
				if( dist < 300 && dist > 40 && !ofGetKeyPressed('n') ){//TODO: move hard coded values into GUI
					vel += frc * 0.003; //TODO: move hard coded values into GUI
				}else{
					//if the particles are not close to us, lets add a little bit of random movement using noise. this is where uniqueVal comes in handy.
					frc.x = ofSignedNoise(uniqueVal, pos.y * 0.01, ofGetElapsedTimef()*0.2);//TODO: move hard coded values into GUI
					frc.y = ofSignedNoise(uniqueVal, pos.x * 0.01, ofGetElapsedTimef()*0.2);//TODO: move hard coded values into GUI
					vel += frc * 0.4;//TODO: move hard coded values into GUI
				}

			}

		}

	}

	//2 - UPDATE OUR POSITION

	pos += vel;

	//3 - (optional) LIMIT THE PARTICLES TO STAY ON SCREEN
	//we could also pass in bounds to check - or alternatively do this at the ofApp level
	if( pos.x > ofGetWidth() ){
		pos.x = ofGetWidth();
		vel.x *= -1.0;
	}else if( pos.x < 0 ){
		pos.x = 0;
		vel.x *= -1.0;
	}
	if( pos.y > ofGetHeight() ){
		pos.y = ofGetHeight();
		vel.y *= -1.0;
	}
	else if( pos.y < 0 ){
		pos.y = 0;
		vel.y *= -1.0;
	}

}

//------------------------------------------------------------------
void demoParticle::draw(){

	if( mode == PARTICLE_MODE_ATTRACT ){
		ofSetColor(255, 63, 180);//TODO: move hard coded values into GUI
	}
	else if( mode == PARTICLE_MODE_REPEL ){
		ofSetColor(208, 255, 63);//TODO: move hard coded values into GUI
	}
	else if( mode == PARTICLE_MODE_NOISE ){
		ofSetColor(99, 63, 255);//TODO: move hard coded values into GUI
	}
	else if( mode == PARTICLE_MODE_NEAREST_POINTS ){
		ofSetColor(103, 160, 237);//TODO: move hard coded values into GUI
	}

	ofDrawCircle(pos.x, pos.y, scale * 4.0);//TODO: move hard coded values into GUI
}

<commit_msg>Attract mode now follows one hand.<commit_after>#include "demoParticle.h"

//------------------------------------------------------------------
demoParticle::demoParticle(){
	attractPoints = NULL;
	attractPoint = NULL;
}

//------------------------------------------------------------------
void demoParticle::setMode(particleMode newMode){
	mode = newMode;
}

//------------------------------------------------------------------
void demoParticle::setAttractPoints( vector <ofPoint> * attract ){
	attractPoints = attract;
}

void demoParticle::setAttractPoint(ofPoint * attractP) {
	attractPoint = attractP;
}
//------------------------------------------------------------------
void demoParticle::reset(){
	//the unique val allows us to set properties slightly differently for each particle
	uniqueVal = ofRandom(-10000, 10000); //TODO: move hard coded values into GUI

	//pos.x = ofRandomWidth();
	//pos.y = ofRandomHeight();

	vel.x = ofRandom(-3.9, 3.9); //TODO: move hard coded values into GUI
	vel.y = ofRandom(-3.9, 3.9); //TODO: move hard coded values into GUI

	frc   = ofPoint(0,0,0);

	scale = ofRandom(0.5, 1.0);//TODO: move hard coded values into GUI

	if( mode == PARTICLE_MODE_NOISE ){
		drag  = ofRandom(0.97, 0.99);//TODO: move hard coded values into GUI
		vel.y = fabs(vel.y) * 3.0; //make the particles all be going down //TODO: move hard coded values into GUI
	}else{
		drag  = ofRandom(0.95, 0.998);	//TODO: move hard coded values into GUI
	}
}

//------------------------------------------------------------------
void demoParticle::update(){

	//1 - APPLY THE FORCES BASED ON WHICH MODE WE ARE IN

	//if( mode == PARTICLE_MODE_ATTRACT ){
		//ofPoint attractPt(ofGetMouseX(), ofGetMouseY());
		//frc = attractPt-pos; // we get the attraction force/vector by looking at the mouse pos relative to our pos
	if( mode == PARTICLE_MODE_ATTRACT && attractPoint){
		frc = *attractPoint-pos; // we get the attraction force/vector by looking at the mouse pos relative to our pos
		frc.normalize(); //by normalizing we disregard how close the particle is to the attraction point

		vel *= drag; //apply drag
		vel += frc * 0.6; //apply force //TODO: move hard coded values into GUI
	}
	else if( mode == PARTICLE_MODE_REPEL && attractPoints ){ //TODO: update this to be repelled by attract points
		ofPoint attractPt(ofGetMouseX(), ofGetMouseY());
		frc = attractPt-pos;

		//let get the distance and only repel points close to the mouse
		float dist = frc.length();
		frc.normalize();

		vel *= drag;
		if( dist < 150 ){//TODO: move hard coded values into GUI
			vel += -frc * 0.6; //notice the frc is negative //TODO: move hard coded values into GUI
		}else{
			//if the particles are not close to us, lets add a little bit of random movement using noise. this is where uniqueVal comes in handy.
			frc.x = ofSignedNoise(uniqueVal, pos.y * 0.01, ofGetElapsedTimef()*0.2);//TODO: move hard coded values into GUI
			frc.y = ofSignedNoise(uniqueVal, pos.x * 0.01, ofGetElapsedTimef()*0.2);//TODO: move hard coded values into GUI
			vel += frc * 0.04;//TODO: move hard coded values into GUI
		}
	}
	else if( mode == PARTICLE_MODE_NOISE || attractPoint == NULL || attractPoints == NULL){
		//lets simulate falling snow
		//the fake wind is meant to add a shift to the particles based on where in x they are
		//we add pos.y as an arg so to prevent obvious vertical banding around x values - try removing the pos.y * 0.006 to see the banding
		float fakeWindX = ofSignedNoise(pos.x * 0.003, pos.y * 0.006, ofGetElapsedTimef() * 0.6);

		frc.x = fakeWindX * 0.25 + ofSignedNoise(uniqueVal, pos.y * 0.04) * 0.6;
		frc.y = ofSignedNoise(uniqueVal, pos.x * 0.006, ofGetElapsedTimef()*0.2) * 0.09 + 0.18;

		vel *= drag;
		vel += frc * 0.4;

		//we do this so as to skip the bounds check for the bottom and make the particles go back to the top of the screen
		if( pos.y + vel.y > ofGetHeight() ){
			pos.y -= ofGetHeight();
		}
	}
	else if( mode == PARTICLE_MODE_NEAREST_POINTS ){

		if( attractPoints ){

			//1 - find closest attractPoint
			ofPoint closestPt;
			int closest = -1;
			float closestDist = 9999999;

			for(unsigned int i = 0; i < attractPoints->size(); i++){
				float lenSq = ( attractPoints->at(i)-pos ).lengthSquared();
				if( lenSq < closestDist ){
					closestDist = lenSq;
					closest = i;
				}
			}

			//2 - if we have a closest point - lets calcuate the force towards it
			if( closest != -1 ){
				closestPt = attractPoints->at(closest);
				float dist = sqrt(closestDist);

				//in this case we don't normalize as we want to have the force proportional to distance
				frc = closestPt - pos;

				vel *= drag;

				//lets also limit our attraction to a certain distance and don't apply if 'n' key is pressed
				if( dist < 300 && dist > 40 && !ofGetKeyPressed('n') ){//TODO: move hard coded values into GUI
					vel += frc * 0.003; //TODO: move hard coded values into GUI
				}else{
					//if the particles are not close to us, lets add a little bit of random movement using noise. this is where uniqueVal comes in handy.
					frc.x = ofSignedNoise(uniqueVal, pos.y * 0.01, ofGetElapsedTimef()*0.2);//TODO: move hard coded values into GUI
					frc.y = ofSignedNoise(uniqueVal, pos.x * 0.01, ofGetElapsedTimef()*0.2);//TODO: move hard coded values into GUI
					vel += frc * 0.4;//TODO: move hard coded values into GUI
				}

			}

		}

	}

	//2 - UPDATE OUR POSITION

	pos += vel;

	//3 - (optional) LIMIT THE PARTICLES TO STAY ON SCREEN
	//we could also pass in bounds to check - or alternatively do this at the ofApp level
	if( pos.x > ofGetWidth() ){
		pos.x = ofGetWidth();
		vel.x *= -1.0;
	}else if( pos.x < 0 ){
		pos.x = 0;
		vel.x *= -1.0;
	}
	if( pos.y > ofGetHeight() ){
		pos.y = ofGetHeight();
		vel.y *= -1.0;
	}
	else if( pos.y < 0 ){
		pos.y = 0;
		vel.y *= -1.0;
	}

}

//------------------------------------------------------------------
void demoParticle::draw(){

	if( mode == PARTICLE_MODE_ATTRACT ){
		ofSetColor(255, 63, 180);//TODO: move hard coded values into GUI
	}
	else if( mode == PARTICLE_MODE_REPEL ){
		ofSetColor(208, 255, 63);//TODO: move hard coded values into GUI
	}
	else if( mode == PARTICLE_MODE_NOISE ){
		ofSetColor(99, 63, 255);//TODO: move hard coded values into GUI
	}
	else if( mode == PARTICLE_MODE_NEAREST_POINTS ){
		ofSetColor(103, 160, 237);//TODO: move hard coded values into GUI
	}

	ofDrawCircle(pos.x, pos.y, scale * 4.0);//TODO: move hard coded values into GUI
}

<|endoftext|>


<commit_before>//============================================================================
// Name        : SSaoEffect.cpp
// Author      : Duarte Peixinho
// Version     :
// Copyright   : ;)
// Description : SSAO Effect
//============================================================================

#include <Pyros3D/Rendering/PostEffects/Effects/SSAOEffect.h>
#include <time.h>
namespace p3d {

	SSAOEffect::SSAOEffect(const uint32 Tex1, const uint32 Width, const uint32 Height) : IEffect(Width, Height)
	{

		// Set RTT
		UseRTT(Tex1);

		// Use Sample
		rnm = new Texture();
		uint32 noiseSize = 16;
		std::vector<Vec3> noise; noise.resize(16);
		srand(time(NULL));
		for (int i = 0; i < noiseSize; ++i) {
			noise[i].x = (rand() % 200 - 100) * 0.01f;
			noise[i].y = (rand() % 200 - 100) * 0.01f;
			noise[i].z = 0.0f;
			noise[i].normalize();
		}
		rnm->CreateEmptyTexture(TextureType::Texture, TextureDataType::RGB, 4, 4, false);
		rnm->UpdateData(&noise[0]);
		rnm->SetRepeat(TextureRepeat::Repeat, TextureRepeat::Repeat);
		UseCustomTexture(rnm);

		// Create Fragment Shader
		FragmentShaderString =
		"uniform sampler2D uTex0;\n"
		"uniform sampler2D uTex1;\n"
		"uniform vec2 uNearFar;\n"
		"uniform vec2 uScreen;\n"
		"uniform float uStrength;\n"
		"uniform int uSamples;\n"
		"uniform float uRadius;\n"
		"uniform float uScale;\n"
		"varying vec2 vTexcoord;\n"
		"uniform mat4 matProj;\n"
		"uniform mat4 uInverseView;\n"
		"uniform mat4 uView;\n"
		"\n"
		"// Reconstruct Positions and Normals\n"
		"float DecodeLinearDepth(float z, vec4 z_info_local)\n"
		"{\n"
		"	return z_info_local.x - z * z_info_local.w;\n"
		"}\n"
		"\n"
		"float DecodeNativeDepth(float native_z, vec4 z_info_local)\n"
		"{\n"
		"	return z_info_local.z / (native_z * z_info_local.w + z_info_local.y);\n"
		"}\n"
		"\n"
		"vec2 getPosViewSpace(vec2 uv, vec4 z_info_local, mat4 matProj_local, vec4 viewport_transform_local)\n"
		"{\n"
		"	vec2 screenPos = (uv + .5) * viewport_transform_local.zw - viewport_transform_local.xy;\n"
		"	vec2 screenSpaceRay = vec2(screenPos.x / matProj_local[0][0], screenPos.y / matProj_local[1][1]);\n"
		"	return screenSpaceRay;\n"
		"}\n"
		"\n"
		"vec3 getPosViewSpace(float depth_sampled, vec2 uv, vec4 z_info_local, out vec3 vpos, mat4 matProj_local, vec4 viewport_transform_local)\n"
		"{\n"
		"	vec2 screenSpaceRay = getPosViewSpace(uv, z_info_local, matProj_local, viewport_transform_local);\n"
		"\n"
		"	float lDepth = DecodeNativeDepth(depth_sampled, z_info_local);\n"
		"	vpos.xy = lDepth * screenSpaceRay;\n"
		"	vpos.z = -lDepth;\n"
		"\n"
		"	return vec3(screenSpaceRay, -1);\n"
		"}\n"
		"\n"
		"void main() {\n"
		"\n"
		"	float total_strength = uStrength;\n"
		"	float radius = uRadius;\n"
		"	int samples = uSamples;\n"
		"	vec3 sample_sphere[16];\n"
		"	sample_sphere[0] = vec3( 0.5381, 0.1856,0.4319);\n"
		"	sample_sphere[1] = vec3( 0.1379, 0.2486,0.4430);\n"
		"	sample_sphere[2] = vec3( 0.3371, 0.5679,0.57);\n"
		"	sample_sphere[3] = vec3(-0.6999,-0.451,0.19);\n"
		"	sample_sphere[4] = vec3( 0.0689,-0.1598,0.8547);\n"
		"	sample_sphere[5] = vec3( 0.0560, 0.69,0.1843);\n"
		"	sample_sphere[6] = vec3(-0.0146, 0.1402,0.762);\n"
		"	sample_sphere[7] = vec3( 0.0100,-0.1924,0.344);\n"
		"	sample_sphere[8] = vec3(-0.3577,-0.5301,0.4358);\n"
		"	sample_sphere[9] = vec3(-0.3169, 0.1063,0.158);\n"
		"	sample_sphere[10] = vec3( 0.103,-0.5869,0.46);\n"
		"	sample_sphere[11] = vec3(-0.897,-0.4940,0.3287);\n"
		"	sample_sphere[12] = vec3( 0.7119,-0.154,0.918);\n"
		"	sample_sphere[13] = vec3(-0.533, 0.596,0.5411);\n"
		"	sample_sphere[14] = vec3( 0.352,-0.631,0.5460);\n"
		"	sample_sphere[15] = vec3(-0.4776, 0.2847,0.271);\n"
		"\n"
		"	vec4 z_info = vec4(uNearFar.x, uNearFar.y, uNearFar.x*uNearFar.y, uNearFar.x - uNearFar.y);\n"
		"	vec2 ssaoOut = vec2(uScreen.x, uScreen.y);\n"
		"	vec4 ssao_vp = vec4(1.0, 1.0, 2.0/ssaoOut.x, 2.0/ssaoOut.y);\n"
		"	vec3 v1, v2, v3;\n"
		"	vec4 out_dim = vec4(uScreen.x, uScreen.y, 1.0/uScreen.x, 1.0/uScreen.y);\n"
		"	vec2 screenCoord = vec2(uScreen.x*vTexcoord.x, uScreen.y*vTexcoord.y);\n"
		"\n"
		" 	getPosViewSpace(texture2D(uTex0, vTexcoord).r, screenCoord, z_info, v1, matProj, ssao_vp);\n"
		"    getPosViewSpace(texture2D(uTex0, vTexcoord + vec2(out_dim.z, 0)).r, screenCoord + vec2(1, 0), z_info, v2, matProj, ssao_vp);\n"
		"    getPosViewSpace(texture2D(uTex0, vTexcoord + vec2(0,out_dim.w)).r, screenCoord + vec2(0, 1), z_info, v3, matProj, ssao_vp);\n"
		"	vec3 vViewNormal = normalize(cross(v1 - v2, v1 - v3));\n"
		"\n"
		"	vec4 vs_position = vec4(v1, 1.0);\n"
		"	vec4 ws_position = uInverseView * vec4(v1, 1.0);\n"
		"	vec4 cs_position = matProj * vec4(v1, 1.0);\n"
		"\n"
		"	float depth = texture2D(uTex0, vTexcoord.xy).r;\n"
		"	vec3 normal = vViewNormal;\n"
		"	vec3 rvec = vec3(texture2D(uTex1, (ws_position.xy + ws_position.z) * uScale).xy * 2.0 - 1.0, 0.0);\n"
		"	vec3 tangent = normalize(rvec - normal * dot(rvec, normal));\n"
		"	vec3 bitangent = cross(normal, tangent);\n"
		"	mat3 TBN = mat3(tangent, bitangent, normal);\n"
		"\n"
		"	float occlusion = 0.0;\n"
		"	\n"
		"	samples = uSamples;\n"
		"	\n"
		"	for(int i=0; i < samples; i++) {\n"
		"		vec3 samplePos = vs_position.xyz + (TBN * (sample_sphere[i] * radius));\n"
		"		vec4 offset = vec4(samplePos, 1.0);\n"
		"\n"
		"		float orig_offset = offset.z;\n"
		"\n"
		"		offset = matProj * offset;\n"
		"		offset.xy /= offset.w;\n"
		"		offset.xy = offset.xy * 0.5 + 0.5;\n"
		"		\n"
		"		float sampleDepth = texture2D(uTex0, offset.xy).r;\n"
		"		float zz = DecodeNativeDepth(sampleDepth, z_info);\n"
		"		//bool inside_wall = DecodeNativeDepth(sampleDepth, z_info) < -orig_offset;\n"
		"\n"
		"		float rangeCheck = -orig_offset - zz < radius ? 1.0 : 0.0;\n"
		"		occlusion += (zz <= -orig_offset ? 1.0 : 0.0) * rangeCheck;\n"
		"		\n"
		"	}\n"
		"	float ao = (1.0 - (occlusion / samples) * total_strength);\n"
		"	gl_FragColor = vec4(ao);\n"
		"}";

		CompileShaders();

		total_strength = 2.0f;
		radius = .2f;
		samples = 16;
		scale = 100.f;

		AddUniform(Uniform("uStrength", Uniforms::DataType::Float, &total_strength));
		AddUniform(Uniform("uRadius", Uniforms::DataType::Float, &radius));
		AddUniform(Uniform("uSamples", Uniforms::DataType::Int, &samples));
		AddUniform(Uniform("uScale", Uniforms::DataType::Float, &scale));
		AddUniform(Uniform("uNearFar", Uniforms::PostEffects::NearFarPlane));
		AddUniform(Uniform("uScreen", Uniforms::PostEffects::ScreenDimensions));
		AddUniform(Uniform("matProj", Uniforms::PostEffects::ProjectionFromScene));
		uInverseViewMatrixUniform = AddUniform(Uniform("uInverseView", Uniforms::DataUsage::Other, Uniforms::DataType::Matrix));
		uViewMatrixUniform = AddUniform(Uniform("uView", Uniforms::DataUsage::Other, Uniforms::DataType::Matrix));
	}

	SSAOEffect::~SSAOEffect()
	{
		delete rnm;
	}

};<commit_msg>Small fix in travis build<commit_after>//============================================================================
// Name        : SSaoEffect.cpp
// Author      : Duarte Peixinho
// Version     :
// Copyright   : ;)
// Description : SSAO Effect
//============================================================================

#include <Pyros3D/Rendering/PostEffects/Effects/SSAOEffect.h>
#include <cstdlib>
#include <time.h>
namespace p3d {

	SSAOEffect::SSAOEffect(const uint32 Tex1, const uint32 Width, const uint32 Height) : IEffect(Width, Height)
	{

		// Set RTT
		UseRTT(Tex1);

		// Use Sample
		rnm = new Texture();
		uint32 noiseSize = 16;
		std::vector<Vec3> noise; noise.resize(16);
		srand(time(NULL));
		for (int i = 0; i < noiseSize; ++i) {
			noise[i].x = (rand() % 200 - 100) * 0.01f;
			noise[i].y = (rand() % 200 - 100) * 0.01f;
			noise[i].z = 0.0f;
			noise[i].normalize();
		}
		rnm->CreateEmptyTexture(TextureType::Texture, TextureDataType::RGB, 4, 4, false);
		rnm->UpdateData(&noise[0]);
		rnm->SetRepeat(TextureRepeat::Repeat, TextureRepeat::Repeat);
		UseCustomTexture(rnm);

		// Create Fragment Shader
		FragmentShaderString =
		"uniform sampler2D uTex0;\n"
		"uniform sampler2D uTex1;\n"
		"uniform vec2 uNearFar;\n"
		"uniform vec2 uScreen;\n"
		"uniform float uStrength;\n"
		"uniform int uSamples;\n"
		"uniform float uRadius;\n"
		"uniform float uScale;\n"
		"varying vec2 vTexcoord;\n"
		"uniform mat4 matProj;\n"
		"uniform mat4 uInverseView;\n"
		"uniform mat4 uView;\n"
		"\n"
		"// Reconstruct Positions and Normals\n"
		"float DecodeLinearDepth(float z, vec4 z_info_local)\n"
		"{\n"
		"	return z_info_local.x - z * z_info_local.w;\n"
		"}\n"
		"\n"
		"float DecodeNativeDepth(float native_z, vec4 z_info_local)\n"
		"{\n"
		"	return z_info_local.z / (native_z * z_info_local.w + z_info_local.y);\n"
		"}\n"
		"\n"
		"vec2 getPosViewSpace(vec2 uv, vec4 z_info_local, mat4 matProj_local, vec4 viewport_transform_local)\n"
		"{\n"
		"	vec2 screenPos = (uv + .5) * viewport_transform_local.zw - viewport_transform_local.xy;\n"
		"	vec2 screenSpaceRay = vec2(screenPos.x / matProj_local[0][0], screenPos.y / matProj_local[1][1]);\n"
		"	return screenSpaceRay;\n"
		"}\n"
		"\n"
		"vec3 getPosViewSpace(float depth_sampled, vec2 uv, vec4 z_info_local, out vec3 vpos, mat4 matProj_local, vec4 viewport_transform_local)\n"
		"{\n"
		"	vec2 screenSpaceRay = getPosViewSpace(uv, z_info_local, matProj_local, viewport_transform_local);\n"
		"\n"
		"	float lDepth = DecodeNativeDepth(depth_sampled, z_info_local);\n"
		"	vpos.xy = lDepth * screenSpaceRay;\n"
		"	vpos.z = -lDepth;\n"
		"\n"
		"	return vec3(screenSpaceRay, -1);\n"
		"}\n"
		"\n"
		"void main() {\n"
		"\n"
		"	float total_strength = uStrength;\n"
		"	float radius = uRadius;\n"
		"	int samples = uSamples;\n"
		"	vec3 sample_sphere[16];\n"
		"	sample_sphere[0] = vec3( 0.5381, 0.1856,0.4319);\n"
		"	sample_sphere[1] = vec3( 0.1379, 0.2486,0.4430);\n"
		"	sample_sphere[2] = vec3( 0.3371, 0.5679,0.57);\n"
		"	sample_sphere[3] = vec3(-0.6999,-0.451,0.19);\n"
		"	sample_sphere[4] = vec3( 0.0689,-0.1598,0.8547);\n"
		"	sample_sphere[5] = vec3( 0.0560, 0.69,0.1843);\n"
		"	sample_sphere[6] = vec3(-0.0146, 0.1402,0.762);\n"
		"	sample_sphere[7] = vec3( 0.0100,-0.1924,0.344);\n"
		"	sample_sphere[8] = vec3(-0.3577,-0.5301,0.4358);\n"
		"	sample_sphere[9] = vec3(-0.3169, 0.1063,0.158);\n"
		"	sample_sphere[10] = vec3( 0.103,-0.5869,0.46);\n"
		"	sample_sphere[11] = vec3(-0.897,-0.4940,0.3287);\n"
		"	sample_sphere[12] = vec3( 0.7119,-0.154,0.918);\n"
		"	sample_sphere[13] = vec3(-0.533, 0.596,0.5411);\n"
		"	sample_sphere[14] = vec3( 0.352,-0.631,0.5460);\n"
		"	sample_sphere[15] = vec3(-0.4776, 0.2847,0.271);\n"
		"\n"
		"	vec4 z_info = vec4(uNearFar.x, uNearFar.y, uNearFar.x*uNearFar.y, uNearFar.x - uNearFar.y);\n"
		"	vec2 ssaoOut = vec2(uScreen.x, uScreen.y);\n"
		"	vec4 ssao_vp = vec4(1.0, 1.0, 2.0/ssaoOut.x, 2.0/ssaoOut.y);\n"
		"	vec3 v1, v2, v3;\n"
		"	vec4 out_dim = vec4(uScreen.x, uScreen.y, 1.0/uScreen.x, 1.0/uScreen.y);\n"
		"	vec2 screenCoord = vec2(uScreen.x*vTexcoord.x, uScreen.y*vTexcoord.y);\n"
		"\n"
		" 	getPosViewSpace(texture2D(uTex0, vTexcoord).r, screenCoord, z_info, v1, matProj, ssao_vp);\n"
		"    getPosViewSpace(texture2D(uTex0, vTexcoord + vec2(out_dim.z, 0)).r, screenCoord + vec2(1, 0), z_info, v2, matProj, ssao_vp);\n"
		"    getPosViewSpace(texture2D(uTex0, vTexcoord + vec2(0,out_dim.w)).r, screenCoord + vec2(0, 1), z_info, v3, matProj, ssao_vp);\n"
		"	vec3 vViewNormal = normalize(cross(v1 - v2, v1 - v3));\n"
		"\n"
		"	vec4 vs_position = vec4(v1, 1.0);\n"
		"	vec4 ws_position = uInverseView * vec4(v1, 1.0);\n"
		"	vec4 cs_position = matProj * vec4(v1, 1.0);\n"
		"\n"
		"	float depth = texture2D(uTex0, vTexcoord.xy).r;\n"
		"	vec3 normal = vViewNormal;\n"
		"	vec3 rvec = vec3(texture2D(uTex1, (ws_position.xy + ws_position.z) * uScale).xy * 2.0 - 1.0, 0.0);\n"
		"	vec3 tangent = normalize(rvec - normal * dot(rvec, normal));\n"
		"	vec3 bitangent = cross(normal, tangent);\n"
		"	mat3 TBN = mat3(tangent, bitangent, normal);\n"
		"\n"
		"	float occlusion = 0.0;\n"
		"	\n"
		"	samples = uSamples;\n"
		"	\n"
		"	for(int i=0; i < samples; i++) {\n"
		"		vec3 samplePos = vs_position.xyz + (TBN * (sample_sphere[i] * radius));\n"
		"		vec4 offset = vec4(samplePos, 1.0);\n"
		"\n"
		"		float orig_offset = offset.z;\n"
		"\n"
		"		offset = matProj * offset;\n"
		"		offset.xy /= offset.w;\n"
		"		offset.xy = offset.xy * 0.5 + 0.5;\n"
		"		\n"
		"		float sampleDepth = texture2D(uTex0, offset.xy).r;\n"
		"		float zz = DecodeNativeDepth(sampleDepth, z_info);\n"
		"		//bool inside_wall = DecodeNativeDepth(sampleDepth, z_info) < -orig_offset;\n"
		"\n"
		"		float rangeCheck = -orig_offset - zz < radius ? 1.0 : 0.0;\n"
		"		occlusion += (zz <= -orig_offset ? 1.0 : 0.0) * rangeCheck;\n"
		"		\n"
		"	}\n"
		"	float ao = (1.0 - (occlusion / samples) * total_strength);\n"
		"	gl_FragColor = vec4(ao);\n"
		"}";

		CompileShaders();

		total_strength = 2.0f;
		radius = .2f;
		samples = 16;
		scale = 100.f;

		AddUniform(Uniform("uStrength", Uniforms::DataType::Float, &total_strength));
		AddUniform(Uniform("uRadius", Uniforms::DataType::Float, &radius));
		AddUniform(Uniform("uSamples", Uniforms::DataType::Int, &samples));
		AddUniform(Uniform("uScale", Uniforms::DataType::Float, &scale));
		AddUniform(Uniform("uNearFar", Uniforms::PostEffects::NearFarPlane));
		AddUniform(Uniform("uScreen", Uniforms::PostEffects::ScreenDimensions));
		AddUniform(Uniform("matProj", Uniforms::PostEffects::ProjectionFromScene));
		uInverseViewMatrixUniform = AddUniform(Uniform("uInverseView", Uniforms::DataUsage::Other, Uniforms::DataType::Matrix));
		uViewMatrixUniform = AddUniform(Uniform("uView", Uniforms::DataUsage::Other, Uniforms::DataType::Matrix));
	}

	SSAOEffect::~SSAOEffect()
	{
		delete rnm;
	}

};<|endoftext|>


<commit_before>#include <cstddef>

#include <cstdint>

#include <type_traits>

#include <utility>

#include <new>

namespace generic
{

template<typename F>
class forwarder;

template<typename R, typename ...A>
class forwarder<R (A...)>
{
public:
	template<typename T>
	forwarder(T&& functor) noexcept :
		stub_(&handler<T>::invoke)
  {
		static_assert(sizeof(T) <= sizeof(store_), "functor too large");
		static_assert(::std::is_trivially_destructible<T>::value,
				"functor not trivially destructible");
		new (&store_) handler<T>(::std::forward<T>(functor));
	}

	R operator() (A... args)
  {
		return stub_(&store_, args...);
	}

private:
	template<typename T>
	class handler
  {
		T functor_;

  public:
		handler(const T &functor) noexcept : functor_(functor) { }

		static R invoke(void* ptr, A... args)
    {
			return static_cast<handler<T>*>(ptr)->functor_(args...);
		}
	};

#if defined(__clang__)
  using max_align_type = long double;
#elif defined(__GNUC__)
  using max_align_type = ::max_align_t;
#else
  using max_align_type = ::std::max_align_t;
#endif

	alignas(max_align_type) ::std::uintptr_t store_;

	R (*stub_)(void*, A...);
};

}
<commit_msg>some fixes<commit_after>#include <cstddef>

#include <cstdint>

#include <type_traits>

#include <utility>

#include <new>

namespace generic
{

template<typename F>
class forwarder;

template<typename R, typename ...A>
class forwarder<R (A...)>
{
public:
  forwarder() = default;

  template<typename T>
  forwarder(T&& f) noexcept :
    stub_(&handler<T>::invoke)
  {
    static_assert(sizeof(T) <= sizeof(store_), "functor too large");
    static_assert(::std::is_trivially_destructible<T>::value,
      "functor not trivially destructible");
    new (&store_) handler<T>(::std::forward<T>(f));
  }

  forwarder& operator=(forwarder const&) = delete;

  template <
    typename T,
    typename = typename ::std::enable_if<
      !::std::is_same<forwarder, typename ::std::decay<T>::type>{}
    >::type
  >
  forwarder& operator=(T&& f) noexcept
  {
    static_assert(sizeof(T) <= sizeof(store_), "functor too large");
    static_assert(::std::is_trivially_destructible<T>::value,
      "functor not trivially destructible");
    stub_ = &handler<T>::invoke;
    new (&store_) handler<T>(::std::forward<T>(f));
  }

  R operator() (A... args)
  {
    return stub_(&store_, args...);
  }

private:
  template<typename T>
  class handler
  {
    T functor_;

  public:
    handler(const T &functor) noexcept : functor_(functor) { }

    static R invoke(void* ptr, A... args)
    {
      return static_cast<handler<T>*>(ptr)->functor_(args...);
    }
  };

#if defined(__clang__)
  using max_align_type = long double;
#elif defined(__GNUC__)
  using max_align_type = ::max_align_t;
#else
  using max_align_type = ::std::max_align_t;
#endif

  alignas(max_align_type) ::std::uintptr_t store_;

  R (*stub_)(void*, A...);
};

}
<|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS changefileheader (1.17.34); FILE MERGED 2008/04/01 12:34:08 thb 1.17.34.2: #i85898# Stripping all external header guards 2008/03/31 13:23:43 rt 1.17.34.1: #i87441# Change license header to LPGL v3.<commit_after><|endoftext|>


<commit_before>/***********************************************************************
    created:    Fri, 4th July 2014
    author:     Henri I Hyyryläinen
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team
 *
 *   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 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.
 ***************************************************************************/

namespace CEGUI
{
// Shaders for Ogre renderer adapted from OpenGL and Direct3D11 shaders

//! A string containing an HLSL vertex shader for solid colouring of a polygon
static Ogre::String VertexShaderColoured_HLSL(""
"float4x4 modelViewProjMatrix;\n"
"\n"
"struct VertOut\n"
"{\n"
"	float4 pos : SV_Position;\n"
"	float4 colour : COLOR;\n"
"};\n"
"\n"
"VertOut main(float3 inPos : POSITION, float4 inColour : COLOR)\n"
"{\n"
"	VertOut output;\n"
"\n"
"   output.pos = mul(modelViewProjMatrix, float4(inPos, 1.0));\n"
"	output.colour = inColour;\n"
"\n"
"	return output;\n"
"}\n"
);

//! A string containing an HLSL fragment shader for solid colouring of a polygon
static Ogre::String PixelShaderColoured_HLSL(""
"uniform float alphaPercentage;\n"
"\n"
"struct VS_OUT\n"
"{\n"
"	float4 position : POSITION;\n"
"	float4 colour : COLOR;\n"
"};\n"
"\n"
"float4 main(VS_OUT input) : COLOR\n"
"{\n"
"   float4 colour = input.colour;\n"
"   colour.a *= alphaPercentage;\n"
"	return colour;\n"
"}\n"
"\n"
);

/*!
A string containing an HLSL vertex shader for polygons that should be coloured
based on a texture. The fetched texture colour will be multiplied by a colour
supplied to the shader, resulting in the final colour.
*/
static Ogre::String VertexShaderTextured_HLSL(""
"float4x4 modelViewProjMatrix;\n"
"\n"
"struct VertOut\n"
"{\n"
"	float4 pos : SV_Position;\n"
"	float4 colour : COLOR;\n"
"	float2 texcoord0 : TEXCOORD;\n"
"};\n"
"\n"
"// Vertex shader\n"
"VertOut main(float4 inPos : POSITION, float4 inColour : COLOR, float2 inTexCoord0 : TEXCOORD)\n"
"{\n"
"	VertOut output;\n"
"\n"
"   output.pos = mul(modelViewProjMatrix, inPos);\n"
"   output.texcoord0 = inTexCoord0;\n"
"	output.colour = inColour;\n"
"\n"
"	return output;\n"
"}\n"
);

/*!
A string containing an HLSL fragment shader for polygons that should be coloured
based on a texture. The fetched texture colour will be multiplied by a colour
supplied to the shader, resulting in the final colour.
*/
static Ogre::String PixelShaderTextured_HLSL(""
"uniform float alphaPercentage;\n"
"struct VS_OUT\n"
"{\n"
"	float4 position : POSITION;\n"
"	float4 colour : COLOR;\n"
"   float2 uv : TEXCOORD0;\n"
"};\n"
"\n"
"float4 main(float4 colour : COLOR, float2 uv : TEXCOORD0, "
"               uniform sampler2D texture0 : TEXUNIT0) : COLOR\n"
"{\n"
"   colour = tex2D(texture0, uv) * colour;\n"
"   colour.a *= alphaPercentage;\n"
"	return colour;\n"
"}\n"
"\n"
);

//! Shader for older OpenGL versions < 3
static Ogre::String VertexShaderTextured_GLSL_Compat(""
    "uniform mat4 modelViewProjMatrix;\n"
    "void main(void)"
    "{"
    "    gl_TexCoord[0] = gl_MultiTexCoord0;"
    "    gl_FrontColor = gl_Color;"
    "    gl_Position = modelViewProjMatrix * gl_Vertex;"
    "}"
);

//! Shader for older OpenGL versions < 3
static Ogre::String PixelShaderTextured_GLSL_Compat(""
    "uniform sampler2D texture0;"
    "uniform float alphaPercentage;\n"
    "void main(void)"
    "{"
    "    gl_FragColor = texture2D(texture0, gl_TexCoord[0].st) * gl_Color;"
    "    gl_FragColor.a *= alphaPercentage;\n"
    "}"
);

//! Shader for older OpenGL versions < 3
static Ogre::String VertexShaderColoured_GLSL_Compat(""
    "uniform mat4 modelViewProjMatrix;\n"
    "void main(void)"
    "{"
    "    gl_FrontColor = gl_Color;"
    "    gl_Position = modelViewProjMatrix * gl_Vertex;"
    "}"
);

//! Shader for older OpenGL versions < 3
static Ogre::String PixelShaderColoured_GLSL_Compat(""
    "uniform float alphaPercentage;\n"
    "void main(void)\n"
    "{"
    "    gl_FragColor = gl_Color;"
    "    gl_FragColor.a *= alphaPercentage;\n"
    "}"
);

//! A string containing an OpenGL3 vertex shader for solid colouring of a polygon
static Ogre::String VertexShaderColoured_GLSL(""
    "#version 130\n"

    "uniform mat4 modelViewProjMatrix;\n"

    "in vec4 vertex;\n"
    "in vec4 colour;\n"

    "out vec4 exColour;"

    "void main(void)\n"
    "{\n"
    "   exColour = colour;\n"

    "   gl_Position = modelViewProjMatrix * vertex;\n"
    "}"
);

//! A string containing an OpenGL3 fragment shader for solid colouring of a polygon
static Ogre::String PixelShaderColoured_GLSL(""
    "#version 130\n"

    "in vec4 exColour;\n"

    "out vec4 fragColour;\n"

    "uniform float alphaPercentage;\n"

    "void main(void)\n"
    "{\n"
    "   fragColour = exColour;\n"
    "   fragColour.a *= alphaPercentage;\n"
    "}"
);

/*!
A string containing an OpenGL3 vertex shader for polygons that should be coloured
based on a texture. The fetched texture colour will be multiplied by a colour
supplied to the shader, resulting in the final colour.
*/
static Ogre::String VertexShaderTextured_GLSL(""
    "#version 130\n"

    "uniform mat4 modelViewProjMatrix;\n"

    "in vec4 vertex;\n"
    "in vec4 colour;\n"
    "in vec2 uv0;\n"

    "out vec2 exTexCoord;\n"
    "out vec4 exColour;\n"

    "void main()\n"
    "{\n"
    "   exTexCoord = uv0;\n"
    "   exColour = colour;\n"

    "   gl_Position = modelViewProjMatrix * vertex;\n"
    "}"
);

/*!
A string containing an OpenGL3 fragment shader for polygons that should be coloured
based on a texture. The fetched texture colour will be multiplied by a colour
supplied to the shader, resulting in the final colour.
*/
static Ogre::String PixelShaderTextured_GLSL(""
    "#version 130\n"

    "uniform sampler2D texture0;\n"
    "uniform float alphaPercentage;\n"

    "in vec2 exTexCoord;\n"
    "in vec4 exColour;\n"

    "out vec4 fragColour;\n"

    "void main(void)\n"
    "{\n"
    "   fragColour = texture(texture0, exTexCoord) * exColour;\n"
    "   fragColour.a *= alphaPercentage;\n"
    "}"
);

//! A string containing an OpenGL ES 2.0 / GLES 1.0 vertex shader for solid colouring of a polygon
static Ogre::String VertexShaderColoured_GLSLES1(""
    "#version 100\n"
    "uniform mat4 modelViewProjMatrix;\n"
    "attribute vec4 vertex;\n"
    "attribute vec4 colour;\n"
    "varying vec4 exColour;\n"
    "void main(void)\n"
    "{\n"
    "   exColour = colour;\n"
    "   gl_Position = modelViewProjMatrix * vertex;\n"
    "}"
);

//! A string containing an OpenGL ES 2.0 / GLES 1.0 fragment shader for solid colouring of a polygon
static Ogre::String PixelShaderColoured_GLSLES1(""
    "#version 100\n"
    "varying vec4 exColour;\n"
    //"varying vec4 dummyColor;\n"
    "uniform float alphaPercentage;\n"
    "void main(void)\n"
    "{\n"
    //"     dummyColor = exColour;\n"
    "     gl_FragColor = exColour;\n"
    //"     gl_FragColor.a = gl_FragColor.a * alphaPercentage;\n"
    "     gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n"
    "}"
);

/*!
A string containing an OpenGL ES 2.0 / GLES 1.0 vertex shader for polygons that should be coloured
based on a texture. The fetched texture colour will be multiplied by a colour
supplied to the shader, resulting in the final colour.
*/
static Ogre::String VertexShaderTextured_GLSLES1(""
    "#version 100\n"
    "uniform mat4 modelViewProjMatrix;\n"
    "attribute vec4 vertex;\n"
    "attribute vec4 colour;\n"
    "attribute vec2 uv0;\n"
    "varying vec2 exTexCoord;\n"
    "varying vec4 exColour;\n"
    "void main()\n"
    "{\n"
    "   exTexCoord = uv0;\n"
    "   exColour = colour;"
    "   gl_Position = modelViewProjMatrix * vertex;\n"
    "}"
);

/*!
A string containing an OpenGL ES 2.0 / GLES 1.0 fragment shader for polygons that should be coloured
based on a texture. The fetched texture colour will be multiplied by a colour
supplied to the shader, resulting in the final colour.
*/
static Ogre::String PixelShaderTextured_GLSLES1(""
    "#version 100\n"
    "uniform sampler2D texture0;\n"
    "uniform lowp float alphaPercentage;\n"
    "varying vec2 exTexCoord;\n"
    "varying vec4 exColour;\n"
    "void main(void)\n"
    "{\n"
    "     gl_FragColor = texture2D(texture0, exTexCoord) * exColour;\n"
    "     gl_FragColor.a = gl_FragColor.a * alphaPercentage;\n"
    "}"
);

}

<commit_msg>MOD: Fixing OGL3 Renderer support in CEGUIOgreRenderer<commit_after>/***********************************************************************
    created:    Fri, 4th July 2014
    author:     Henri I Hyyryläinen
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team
 *
 *   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 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.
 ***************************************************************************/

namespace CEGUI
{
// Shaders for Ogre renderer adapted from OpenGL and Direct3D11 shaders

//! A string containing an HLSL vertex shader for solid colouring of a polygon
static Ogre::String VertexShaderColoured_HLSL(""
"float4x4 modelViewProjMatrix;\n"
"\n"
"struct VertOut\n"
"{\n"
"	float4 pos : SV_Position;\n"
"	float4 colour : COLOR;\n"
"};\n"
"\n"
"VertOut main(float3 inPos : POSITION, float4 inColour : COLOR)\n"
"{\n"
"	VertOut output;\n"
"\n"
"   output.pos = mul(modelViewProjMatrix, float4(inPos, 1.0));\n"
"	output.colour = inColour;\n"
"\n"
"	return output;\n"
"}\n"
);

//! A string containing an HLSL fragment shader for solid colouring of a polygon
static Ogre::String PixelShaderColoured_HLSL(""
"uniform float alphaPercentage;\n"
"\n"
"struct VS_OUT\n"
"{\n"
"	float4 position : POSITION;\n"
"	float4 colour : COLOR;\n"
"};\n"
"\n"
"float4 main(VS_OUT input) : COLOR\n"
"{\n"
"   float4 colour = input.colour;\n"
"   colour.a *= alphaPercentage;\n"
"	return colour;\n"
"}\n"
"\n"
);

/*!
A string containing an HLSL vertex shader for polygons that should be coloured
based on a texture. The fetched texture colour will be multiplied by a colour
supplied to the shader, resulting in the final colour.
*/
static Ogre::String VertexShaderTextured_HLSL(""
"float4x4 modelViewProjMatrix;\n"
"\n"
"struct VertOut\n"
"{\n"
"	float4 pos : SV_Position;\n"
"	float4 colour : COLOR;\n"
"	float2 texcoord0 : TEXCOORD;\n"
"};\n"
"\n"
"// Vertex shader\n"
"VertOut main(float4 inPos : POSITION, float4 inColour : COLOR, float2 inTexCoord0 : TEXCOORD)\n"
"{\n"
"	VertOut output;\n"
"\n"
"   output.pos = mul(modelViewProjMatrix, inPos);\n"
"   output.texcoord0 = inTexCoord0;\n"
"	output.colour = inColour;\n"
"\n"
"	return output;\n"
"}\n"
);

/*!
A string containing an HLSL fragment shader for polygons that should be coloured
based on a texture. The fetched texture colour will be multiplied by a colour
supplied to the shader, resulting in the final colour.
*/
static Ogre::String PixelShaderTextured_HLSL(""
"uniform float alphaPercentage;\n"
"struct VS_OUT\n"
"{\n"
"	float4 position : POSITION;\n"
"	float4 colour : COLOR;\n"
"   float2 uv : TEXCOORD0;\n"
"};\n"
"\n"
"float4 main(float4 colour : COLOR, float2 uv : TEXCOORD0, "
"               uniform sampler2D texture0 : TEXUNIT0) : COLOR\n"
"{\n"
"   colour = tex2D(texture0, uv) * colour;\n"
"   colour.a *= alphaPercentage;\n"
"	return colour;\n"
"}\n"
"\n"
);

//! Shader for older OpenGL versions < 3
static Ogre::String VertexShaderTextured_GLSL_Compat(""
    "uniform mat4 modelViewProjMatrix;\n"
    "void main(void)"
    "{"
    "    gl_TexCoord[0] = gl_MultiTexCoord0;"
    "    gl_FrontColor = gl_Color;"
    "    gl_Position = modelViewProjMatrix * gl_Vertex;"
    "}"
);

//! Shader for older OpenGL versions < 3
static Ogre::String PixelShaderTextured_GLSL_Compat(""
    "uniform sampler2D texture0;"
    "uniform float alphaPercentage;\n"
    "void main(void)"
    "{"
    "    gl_FragColor = texture2D(texture0, gl_TexCoord[0].st) * gl_Color;"
    "    gl_FragColor.a *= alphaPercentage;\n"
    "}"
);

//! Shader for older OpenGL versions < 3
static Ogre::String VertexShaderColoured_GLSL_Compat(""
    "uniform mat4 modelViewProjMatrix;\n"
    "void main(void)"
    "{"
    "    gl_FrontColor = gl_Color;"
    "    gl_Position = modelViewProjMatrix * gl_Vertex;"
    "}"
);

//! Shader for older OpenGL versions < 3
static Ogre::String PixelShaderColoured_GLSL_Compat(""
    "uniform float alphaPercentage;\n"
    "void main(void)\n"
    "{"
    "    gl_FragColor = gl_Color;"
    "    gl_FragColor.a *= alphaPercentage;\n"
    "}"
);

//! A string containing an OpenGL3 vertex shader for solid colouring of a polygon
static Ogre::String VertexShaderColoured_GLSL(""
    "#version 150 core\n"

    "uniform mat4 modelViewProjMatrix;\n"

    "in vec4 vertex;\n"
    "in vec4 colour;\n"

    "out vec4 exColour;"

    "void main(void)\n"
    "{\n"
    "   exColour = colour;\n"

    "   gl_Position = modelViewProjMatrix * vertex;\n"
    "}"
);

//! A string containing an OpenGL3 fragment shader for solid colouring of a polygon
static Ogre::String PixelShaderColoured_GLSL(""
    "#version 150 core\n"

    "in vec4 exColour;\n"

    "out vec4 fragColour;\n"

    "uniform float alphaPercentage;\n"

    "void main(void)\n"
    "{\n"
    "   fragColour = exColour;\n"
    "   fragColour.a *= alphaPercentage;\n"
    "}"
);

/*!
A string containing an OpenGL3 vertex shader for polygons that should be coloured
based on a texture. The fetched texture colour will be multiplied by a colour
supplied to the shader, resulting in the final colour.
*/
static Ogre::String VertexShaderTextured_GLSL(""
    "#version 150 core\n"

    "uniform mat4 modelViewProjMatrix;\n"

    "in vec4 vertex;\n"
    "in vec4 colour;\n"
    "in vec2 uv0;\n"

    "out vec2 exTexCoord;\n"
    "out vec4 exColour;\n"

    "void main()\n"
    "{\n"
    "   exTexCoord = uv0;\n"
    "   exColour = colour;\n"

    "   gl_Position = modelViewProjMatrix * vertex;\n"
    "}"
);

/*!
A string containing an OpenGL3 fragment shader for polygons that should be coloured
based on a texture. The fetched texture colour will be multiplied by a colour
supplied to the shader, resulting in the final colour.
*/
static Ogre::String PixelShaderTextured_GLSL(""
    "#version 150 core\n"

    "uniform sampler2D texture0;\n"
    "uniform float alphaPercentage;\n"

    "in vec2 exTexCoord;\n"
    "in vec4 exColour;\n"

    "out vec4 fragColour;\n"

    "void main(void)\n"
    "{\n"
    "   fragColour = texture(texture0, exTexCoord) * exColour;\n"
    "   fragColour.a *= alphaPercentage;\n"
    "}"
);

//! A string containing an OpenGL ES 2.0 / GLES 1.0 vertex shader for solid colouring of a polygon
static Ogre::String VertexShaderColoured_GLSLES1(""
    "#version 100\n"
    "uniform mat4 modelViewProjMatrix;\n"
    "attribute vec4 vertex;\n"
    "attribute vec4 colour;\n"
    "varying vec4 exColour;\n"
    "void main(void)\n"
    "{\n"
    "   exColour = colour;\n"
    "   gl_Position = modelViewProjMatrix * vertex;\n"
    "}"
);

//! A string containing an OpenGL ES 2.0 / GLES 1.0 fragment shader for solid colouring of a polygon
static Ogre::String PixelShaderColoured_GLSLES1(""
    "#version 100\n"
    "varying vec4 exColour;\n"
    //"varying vec4 dummyColor;\n"
    "uniform float alphaPercentage;\n"
    "void main(void)\n"
    "{\n"
    //"     dummyColor = exColour;\n"
    "     gl_FragColor = exColour;\n"
    //"     gl_FragColor.a = gl_FragColor.a * alphaPercentage;\n"
    "     gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n"
    "}"
);

/*!
A string containing an OpenGL ES 2.0 / GLES 1.0 vertex shader for polygons that should be coloured
based on a texture. The fetched texture colour will be multiplied by a colour
supplied to the shader, resulting in the final colour.
*/
static Ogre::String VertexShaderTextured_GLSLES1(""
    "#version 100\n"
    "uniform mat4 modelViewProjMatrix;\n"
    "attribute vec4 vertex;\n"
    "attribute vec4 colour;\n"
    "attribute vec2 uv0;\n"
    "varying vec2 exTexCoord;\n"
    "varying vec4 exColour;\n"
    "void main()\n"
    "{\n"
    "   exTexCoord = uv0;\n"
    "   exColour = colour;"
    "   gl_Position = modelViewProjMatrix * vertex;\n"
    "}"
);

/*!
A string containing an OpenGL ES 2.0 / GLES 1.0 fragment shader for polygons that should be coloured
based on a texture. The fetched texture colour will be multiplied by a colour
supplied to the shader, resulting in the final colour.
*/
static Ogre::String PixelShaderTextured_GLSLES1(""
    "#version 100\n"
    "uniform sampler2D texture0;\n"
    "uniform lowp float alphaPercentage;\n"
    "varying vec2 exTexCoord;\n"
    "varying vec4 exColour;\n"
    "void main(void)\n"
    "{\n"
    "     gl_FragColor = texture2D(texture0, exTexCoord) * exColour;\n"
    "     gl_FragColor.a = gl_FragColor.a * alphaPercentage;\n"
    "}"
);

}

<|endoftext|>