<commit_before>#include <AVFoundation/AVFoundation.h>
#include "event.h"
#include "types.h"

namespace opencl {

// /* Event Object APIs */
// extern CL_API_ENTRY cl_int CL_API_CALL
// clWaitForEvents(cl_uint             /* num_events */,
//                 const cl_event *    /* event_list */) CL_API_SUFFIX__VERSION_1_0;
NAN_METHOD(WaitForEvents) {
  NanScope();
  REQ_ARGS(1);

  std::vector<NoCLEvent> events;
  Local<Array> js_events = Local<Array>::Cast(args[1]);
  NOCL_TO_ARRAY(events, js_events, NoCLEvent);

  CHECK_ERR(::clWaitForEvents(
    events.size(), NOCL_TO_CL_ARRAY(events, NoCLEvent)));

  NanReturnValue(JS_INT(CL_SUCCESS));
}

// extern CL_API_ENTRY cl_int CL_API_CALL
// clGetEventInfo(cl_event         /* event */,
//                cl_event_info    /* param_name */,
//                size_t           /* param_value_size */,
//                void *           /* param_value */,
//                size_t *         /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0;
NAN_METHOD(GetEventInfo) {
  NanScope();
  REQ_ARGS(2);

  // Arg 0
  NOCL_UNWRAP(ev, NoCLEvent, args[0]);

  // Arg 1
  cl_event_info param_name = args[1]->Uint32Value();

  switch(param_name) {
    case CL_EVENT_COMMAND_QUEUE:
    {
      cl_command_queue val;
      CHECK_ERR(::clGetEventInfo(ev->getRaw(),param_name,sizeof(cl_command_queue), &val, NULL))
      // TODO NanReturnValue(JS_INT(val));
      break;
    }
    case CL_EVENT_CONTEXT:
    {
      cl_context val;
      CHECK_ERR(::clGetEventInfo(ev->getRaw(),param_name,sizeof(cl_context), &val, NULL))
      // TODO NanReturnValue(JS_INT(val));
      break;
    }
    case CL_EVENT_COMMAND_TYPE:
    {
      cl_command_type val;
      CHECK_ERR(::clGetEventInfo(ev->getRaw(),param_name,sizeof(cl_command_type), &val, NULL))
      NanReturnValue(JS_INT(val));
    }
    case CL_EVENT_COMMAND_EXECUTION_STATUS:
    {
      cl_int val;
      CHECK_ERR(::clGetEventInfo(ev->getRaw(),param_name,sizeof(cl_int), &val, NULL))
      NanReturnValue(JS_INT(val));
    }
    case CL_EVENT_REFERENCE_COUNT:
    {
      cl_uint val;
      CHECK_ERR(::clGetEventInfo(ev->getRaw(),param_name,sizeof(cl_uint), &val, NULL))
      NanReturnValue(JS_INT(val));
    }
  }
  return NanThrowError(JS_INT(CL_INVALID_VALUE));
}

// extern CL_API_ENTRY cl_event CL_API_CALL
// clCreateUserEvent(cl_context    /* context */,
//                   cl_int *      /* errcode_ret */) CL_API_SUFFIX__VERSION_1_1;
NAN_METHOD(CreateUserEvent) {
  NanScope();
  REQ_ARGS(1);

  // Arg 0
  NOCL_UNWRAP(context, NoCLContext, args[0]);

  cl_int err;
  cl_event uev=::clCreateUserEvent(context->getRaw(), &err);
  CHECK_ERR(err)
  NanReturnValue(NOCL_WRAP(NoCLEvent, uev));
}

// extern CL_API_ENTRY cl_int CL_API_CALL
// clRetainEvent(cl_event /* event */) CL_API_SUFFIX__VERSION_1_0;
NAN_METHOD(RetainEvent) {
  NanScope();
  REQ_ARGS(1);

  NOCL_UNWRAP(ev, NoCLEvent, args[0]);
  cl_int count=clRetainEvent(ev->getRaw());

  NanReturnValue(JS_INT(count));
}

// extern CL_API_ENTRY cl_int CL_API_CALL
// clReleaseEvent(cl_event /* event */) CL_API_SUFFIX__VERSION_1_0;
NAN_METHOD(ReleaseEvent) {
  NanScope();
  REQ_ARGS(1);

  // Arg 0
  NOCL_UNWRAP(ev, NoCLEvent, args[0]);
  cl_int count=clReleaseEvent(ev->getRaw());

  NanReturnValue(JS_INT(count));
}

// extern CL_API_ENTRY cl_int CL_API_CALL
// clSetUserEventStatus(cl_event   /* event */,
//                      cl_int     /* execution_status */) CL_API_SUFFIX__VERSION_1_1;
NAN_METHOD(SetUserEventStatus) {
  NanScope();
  REQ_ARGS(2);

  // Arg 0
  NOCL_UNWRAP(ev, NoCLEvent, args[0]);

  cl_int exec_status=args[1]->Uint32Value();
  CHECK_ERR(::clSetUserEventStatus(ev->getRaw(),exec_status));

  NanReturnUndefined(); // TODO should we return err?
}

// /* Profiling APIs */
// extern CL_API_ENTRY cl_int CL_API_CALL
// clGetEventProfilingInfo(cl_event            /* event */,
//                         cl_profiling_info   /* param_name */,
//                         size_t              /* param_value_size */,
//                         void *              /* param_value */,
//                         size_t *            /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0;
NAN_METHOD(GetEventProfilingInfo) {
  NanScope();
  REQ_ARGS(2);

  // Arg 0
  NOCL_UNWRAP(ev, NoCLEvent, args[0]);

  cl_profiling_info param_name = args[1]->Uint32Value();

  switch(param_name) {
    case CL_PROFILING_COMMAND_QUEUED:
    case CL_PROFILING_COMMAND_SUBMIT:
    case CL_PROFILING_COMMAND_START:
    case CL_PROFILING_COMMAND_END:
    {
      cl_ulong val;
      CHECK_ERR(::clGetEventProfilingInfo(ev->getRaw(),param_name,sizeof(cl_ulong), &val, NULL))
      NanReturnValue(JS_INT((uint32_t) val)); // TODO how do we return 64b value in JS?
    }
  }
  return NanThrowError(JS_INT(CL_INVALID_VALUE));
}

namespace Event {
void init(Handle<Object> exports)
{
  NODE_SET_METHOD(exports, "waitForEvents", WaitForEvents);
  NODE_SET_METHOD(exports, "getEventInfo", GetEventInfo);
  NODE_SET_METHOD(exports, "createUserEvent", CreateUserEvent);
  NODE_SET_METHOD(exports, "retainEvent", RetainEvent);
  NODE_SET_METHOD(exports, "releaseEvent", ReleaseEvent);
  NODE_SET_METHOD(exports, "setUserEventStatus", SetUserEventStatus);
  NODE_SET_METHOD(exports, "getEventProfilingInfo", GetEventProfilingInfo);
}
} // namespace Event

} // namespace opencl
<commit_msg>[Implementation] Returning 2 integers where int64 is needed for nanosecond timestamps<commit_after>#include <AVFoundation/AVFoundation.h>
#include "event.h"
#include "types.h"

namespace opencl {

// /* Event Object APIs */
// extern CL_API_ENTRY cl_int CL_API_CALL
// clWaitForEvents(cl_uint             /* num_events */,
//                 const cl_event *    /* event_list */) CL_API_SUFFIX__VERSION_1_0;
NAN_METHOD(WaitForEvents) {
  NanScope();
  REQ_ARGS(1);

  std::vector<NoCLEvent> events;
  Local<Array> js_events = Local<Array>::Cast(args[1]);
  NOCL_TO_ARRAY(events, js_events, NoCLEvent);

  CHECK_ERR(::clWaitForEvents(
    events.size(), NOCL_TO_CL_ARRAY(events, NoCLEvent)));

  NanReturnValue(JS_INT(CL_SUCCESS));
}

// extern CL_API_ENTRY cl_int CL_API_CALL
// clGetEventInfo(cl_event         /* event */,
//                cl_event_info    /* param_name */,
//                size_t           /* param_value_size */,
//                void *           /* param_value */,
//                size_t *         /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0;
NAN_METHOD(GetEventInfo) {
  NanScope();
  REQ_ARGS(2);

  // Arg 0
  NOCL_UNWRAP(ev, NoCLEvent, args[0]);

  // Arg 1
  cl_event_info param_name = args[1]->Uint32Value();

  switch(param_name) {
    case CL_EVENT_COMMAND_QUEUE:
    {
      cl_command_queue val;
      CHECK_ERR(::clGetEventInfo(ev->getRaw(),param_name,sizeof(cl_command_queue), &val, NULL))
      // TODO NanReturnValue(JS_INT(val));
      break;
    }
    case CL_EVENT_CONTEXT:
    {
      cl_context val;
      CHECK_ERR(::clGetEventInfo(ev->getRaw(),param_name,sizeof(cl_context), &val, NULL))
      // TODO NanReturnValue(JS_INT(val));
      break;
    }
    case CL_EVENT_COMMAND_TYPE:
    {
      cl_command_type val;
      CHECK_ERR(::clGetEventInfo(ev->getRaw(),param_name,sizeof(cl_command_type), &val, NULL))
      NanReturnValue(JS_INT(val));
    }
    case CL_EVENT_COMMAND_EXECUTION_STATUS:
    {
      cl_int val;
      CHECK_ERR(::clGetEventInfo(ev->getRaw(),param_name,sizeof(cl_int), &val, NULL))
      NanReturnValue(JS_INT(val));
    }
    case CL_EVENT_REFERENCE_COUNT:
    {
      cl_uint val;
      CHECK_ERR(::clGetEventInfo(ev->getRaw(),param_name,sizeof(cl_uint), &val, NULL))
      NanReturnValue(JS_INT(val));
    }
  }
  return NanThrowError(JS_INT(CL_INVALID_VALUE));
}

// extern CL_API_ENTRY cl_event CL_API_CALL
// clCreateUserEvent(cl_context    /* context */,
//                   cl_int *      /* errcode_ret */) CL_API_SUFFIX__VERSION_1_1;
NAN_METHOD(CreateUserEvent) {
  NanScope();
  REQ_ARGS(1);

  // Arg 0
  NOCL_UNWRAP(context, NoCLContext, args[0]);

  cl_int err;
  cl_event uev=::clCreateUserEvent(context->getRaw(), &err);
  CHECK_ERR(err)
  NanReturnValue(NOCL_WRAP(NoCLEvent, uev));
}

// extern CL_API_ENTRY cl_int CL_API_CALL
// clRetainEvent(cl_event /* event */) CL_API_SUFFIX__VERSION_1_0;
NAN_METHOD(RetainEvent) {
  NanScope();
  REQ_ARGS(1);

  NOCL_UNWRAP(ev, NoCLEvent, args[0]);
  cl_int count=clRetainEvent(ev->getRaw());

  NanReturnValue(JS_INT(count));
}

// extern CL_API_ENTRY cl_int CL_API_CALL
// clReleaseEvent(cl_event /* event */) CL_API_SUFFIX__VERSION_1_0;
NAN_METHOD(ReleaseEvent) {
  NanScope();
  REQ_ARGS(1);

  // Arg 0
  NOCL_UNWRAP(ev, NoCLEvent, args[0]);
  cl_int count=clReleaseEvent(ev->getRaw());

  NanReturnValue(JS_INT(count));
}

// extern CL_API_ENTRY cl_int CL_API_CALL
// clSetUserEventStatus(cl_event   /* event */,
//                      cl_int     /* execution_status */) CL_API_SUFFIX__VERSION_1_1;
NAN_METHOD(SetUserEventStatus) {
  NanScope();
  REQ_ARGS(2);

  // Arg 0
  NOCL_UNWRAP(ev, NoCLEvent, args[0]);

  cl_int exec_status=args[1]->Uint32Value();
  CHECK_ERR(::clSetUserEventStatus(ev->getRaw(),exec_status));

  NanReturnUndefined(); // TODO should we return err?
}

// /* Profiling APIs */
// extern CL_API_ENTRY cl_int CL_API_CALL
// clGetEventProfilingInfo(cl_event            /* event */,
//                         cl_profiling_info   /* param_name */,
//                         size_t              /* param_value_size */,
//                         void *              /* param_value */,
//                         size_t *            /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0;
NAN_METHOD(GetEventProfilingInfo) {
  NanScope();
  REQ_ARGS(2);

  // Arg 0
  NOCL_UNWRAP(ev, NoCLEvent, args[0]);

  cl_profiling_info param_name = args[1]->Uint32Value();

  switch(param_name) {
    case CL_PROFILING_COMMAND_QUEUED:
    case CL_PROFILING_COMMAND_SUBMIT:
    case CL_PROFILING_COMMAND_START:
    case CL_PROFILING_COMMAND_END:
    {
      /**
      * JS Compatibility
      *
      * As JS does not support 64 bits integer, we return a 2 integers array with
      *  INT / 1000 = arr[0] * 10^6 (milliseconds) + arr[1]  (nanoseconds - milliseconds) */

      cl_ulong val;
      CHECK_ERR(::clGetEventProfilingInfo(ev->getRaw(),param_name,sizeof(cl_ulong), &val, NULL))

      Local<Array> arr = NanNew<Array>(2);
      arr->Set(0, JS_INT((uint32_t)val / 1000000));
      arr->Set(1, JS_INT((uint32_t)val - val / 1000000));
      NanReturnValue(arr);
    }
  }
  return NanThrowError(JS_INT(CL_INVALID_VALUE));
}

namespace Event {
void init(Handle<Object> exports)
{
  NODE_SET_METHOD(exports, "waitForEvents", WaitForEvents);
  NODE_SET_METHOD(exports, "getEventInfo", GetEventInfo);
  NODE_SET_METHOD(exports, "createUserEvent", CreateUserEvent);
  NODE_SET_METHOD(exports, "retainEvent", RetainEvent);
  NODE_SET_METHOD(exports, "releaseEvent", ReleaseEvent);
  NODE_SET_METHOD(exports, "setUserEventStatus", SetUserEventStatus);
  NODE_SET_METHOD(exports, "getEventProfilingInfo", GetEventProfilingInfo);
}
} // namespace Event

} // namespace opencl
<|endoftext|>


<commit_before>/*
 * Copyright deipi.com LLC and contributors. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

#include "fields.h"
#include <xapian/query.h>

NumericFieldProcessor::NumericFieldProcessor(const std::string &prefix_): prefix(prefix_) {}

Xapian::Query
NumericFieldProcessor::operator()(const std::string &str)
{
	LOG(this, "Numeric FP %s!!\n", str.c_str());
	std::string serialise = serialise_numeric(str);
	if (serialise.size() == 0) {
		throw Xapian::QueryParserError("Didn't understand numeric specification '" + str + "'");
	}
	return Xapian::Query(prefix + serialise);
}

LatLongFieldProcessor::LatLongFieldProcessor(const std::string &prefix_): prefix(prefix_) {}

Xapian::Query
LatLongFieldProcessor::operator()(const std::string &str)
{
	/*
	 Note: parser_query do not accepts .2,.1 needs start with a numer before the dot
	 eg. this works!! (0.2,0.1)
	*/

	LOG(this, "Inside of LatLongFieldProcessor %s\n", str.c_str());
	std::string serialise = serialise_geo(str);
	if (serialise.size() == 0) {
		throw Xapian::QueryParserError("Didn't understand LatLongs specification '" + str + "'");
	}
	return Xapian::Query(prefix + serialise);
}

LatLongDistanceFieldProcessor::LatLongDistanceFieldProcessor(std::string prefix_, std::string field_): prefix(prefix_), field(field_) {}

Xapian::Query
LatLongDistanceFieldProcessor::operator()(const std::string &str)
{
	LOG(this, "Inside of LatLongDistanceFieldProcessor %s\n", str.c_str());
	Xapian::LatLongCoords coords;
	if (get_coords(str, coords_) == 0) {
		LOG(this,"Longitud: %f latitud: %f max_range: %f\n", coords_[0],coords_[1], coords_[2]);
		Xapian::LatLongCoord centre(coords_[0], coords_[1]);
		coords_[2] = Xapian::miles_to_metres(coords_[2]);
		Xapian::GreatCircleMetric metric;

		Xapian::LatLongDistancePostingSource ps(get_slot(field), centre, metric, coords_[2]);
		return Xapian::Query(&ps);
	}
	throw Xapian::QueryParserError("LatLongDistanceFieldProcessor Didn't understand %s", str.c_str());
}

BooleanFieldProcessor::BooleanFieldProcessor(const std::string &prefix_): prefix(prefix_) {}

Xapian::Query BooleanFieldProcessor::operator()(const std::string &str)
{
	LOG(this, "Boolean FP!!\n");
	std::string serialise = serialise_bool(str);
	if (serialise.size() == 0) {
		throw Xapian::QueryParserError("Didn't understand bool specification '" + str + "'");
	}
	return Xapian::Query(prefix + serialise);
}

DateFieldProcessor::DateFieldProcessor(const std::string &prefix_): prefix(prefix_) {}

Xapian::Query DateFieldProcessor::operator()(const std::string &str)
{
	LOG(this, "Date FP!!\n");
	std::string serialise = serialise_date(str);
	if (serialise.size() == 0) {
		throw Xapian::QueryParserError("Didn't understand date specification '" + str + "'");
	}
	return Xapian::Query(prefix + serialise);
}

DateTimeValueRangeProcessor::DateTimeValueRangeProcessor(Xapian::valueno slot_, std::string prefix_): valno(slot_), prefix(prefix_) {}

Xapian::valueno
DateTimeValueRangeProcessor::operator()(std::string &begin, std::string &end)
{
	std::string buf;
	LOG(this, "Inside of DateTimeValueRangeProcessor\n");

	if (begin.size() != 0) {
		buf = prefix + serialise_date(begin);
		if (buf != "") {
			begin.assign(buf.c_str(), buf.size());
			LOG(this, "Serialise of begin %s\n", buf.c_str());
		} else {
			return Xapian::BAD_VALUENO;
		}
	}
	buf = "";

	if (end.size() != 0) {
		buf = prefix + serialise_date(end);
		if (buf != "") {
			end.assign(buf.c_str(), buf.size());
			LOG(this, "Serialise of end %s\n", std::string(prefix + buf).c_str());
		} else {
			return Xapian::BAD_VALUENO;
		}
	}
	LOG(this, "DateTimeValueRangeProcessor process\n");

	return valno;
}<commit_msg>When date isn't ISO, return BAD_VALUENO<commit_after>/*
 * Copyright deipi.com LLC and contributors. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

#include "fields.h"
#include <xapian/query.h>

NumericFieldProcessor::NumericFieldProcessor(const std::string &prefix_): prefix(prefix_) {}

Xapian::Query
NumericFieldProcessor::operator()(const std::string &str)
{
	LOG(this, "Numeric FP %s!!\n", str.c_str());
	std::string serialise = serialise_numeric(str);
	if (serialise.size() == 0) {
		throw Xapian::QueryParserError("Didn't understand numeric specification '" + str + "'");
	}
	return Xapian::Query(prefix + serialise);
}

LatLongFieldProcessor::LatLongFieldProcessor(const std::string &prefix_): prefix(prefix_) {}

Xapian::Query
LatLongFieldProcessor::operator()(const std::string &str)
{
	/*
	 Note: parser_query do not accepts .2,.1 needs start with a numer before the dot
	 eg. this works!! (0.2,0.1)
	*/

	LOG(this, "Inside of LatLongFieldProcessor %s\n", str.c_str());
	std::string serialise = serialise_geo(str);
	if (serialise.size() == 0) {
		throw Xapian::QueryParserError("Didn't understand LatLongs specification '" + str + "'");
	}
	return Xapian::Query(prefix + serialise);
}

LatLongDistanceFieldProcessor::LatLongDistanceFieldProcessor(std::string prefix_, std::string field_): prefix(prefix_), field(field_) {}

Xapian::Query
LatLongDistanceFieldProcessor::operator()(const std::string &str)
{
	LOG(this, "Inside of LatLongDistanceFieldProcessor %s\n", str.c_str());
	Xapian::LatLongCoords coords;
	if (get_coords(str, coords_) == 0) {
		LOG(this,"Longitud: %f latitud: %f max_range: %f\n", coords_[0],coords_[1], coords_[2]);
		Xapian::LatLongCoord centre(coords_[0], coords_[1]);
		coords_[2] = Xapian::miles_to_metres(coords_[2]);
		Xapian::GreatCircleMetric metric;

		Xapian::LatLongDistancePostingSource ps(get_slot(field), centre, metric, coords_[2]);
		return Xapian::Query(&ps);
	}
	throw Xapian::QueryParserError("LatLongDistanceFieldProcessor Didn't understand %s", str.c_str());
}

BooleanFieldProcessor::BooleanFieldProcessor(const std::string &prefix_): prefix(prefix_) {}

Xapian::Query BooleanFieldProcessor::operator()(const std::string &str)
{
	LOG(this, "Boolean FP!!\n");
	std::string serialise = serialise_bool(str);
	if (serialise.size() == 0) {
		throw Xapian::QueryParserError("Didn't understand bool specification '" + str + "'");
	}
	return Xapian::Query(prefix + serialise);
}

DateFieldProcessor::DateFieldProcessor(const std::string &prefix_): prefix(prefix_) {}

Xapian::Query DateFieldProcessor::operator()(const std::string &str)
{
	LOG(this, "Date FP!!\n");
	std::string serialise = serialise_date(str);
	if (serialise.size() == 0) {
		throw Xapian::QueryParserError("Didn't understand date specification '" + str + "'");
	}
	return Xapian::Query(prefix + serialise);
}

DateTimeValueRangeProcessor::DateTimeValueRangeProcessor(Xapian::valueno slot_, std::string prefix_): valno(slot_), prefix(prefix_) {}

Xapian::valueno
DateTimeValueRangeProcessor::operator()(std::string &begin, std::string &end)
{
	std::string buf;
	LOG(this, "Inside of DateTimeValueRangeProcessor\n");

	if (begin.size() != 0) {
		std::string serialise = serialise_date(begin);
		if (serialise.size() == 0) return Xapian::BAD_VALUENO;
		buf = prefix + serialise;
		begin.assign(buf.c_str(), buf.size());
		LOG(this, "Serialise of begin %s\n", buf.c_str());
	}
	buf = "";

	if (end.size() != 0) {
		std::string serialise = serialise_date(end);
		if (serialise.size() == 0) return Xapian::BAD_VALUENO;
		buf = prefix + serialise;
		end.assign(buf.c_str(), buf.size());
		LOG(this, "Serialise of end %s\n", std::string(prefix + buf).c_str());
	}
	LOG(this, "DateTimeValueRangeProcessor process\n");

	return valno;
}<|endoftext|>


<commit_before>#include <rtos.h>
#include <RPCVariable.h>

#include <Console.hpp>
#include <logger.hpp>
#include <assert.hpp>

#include "robot-devices.hpp"
#include "task-signals.hpp"
#include "task-globals.hpp"
#include "motors.hpp"
#include "fpga.hpp"
#include "mpu-6050.hpp"
#include "io-expander.hpp"

// Keep this pretty high for now. Ideally, drop it down to ~3 for production
// builds. Hopefully that'll be possible without the console
static const int CONTROL_LOOP_WAIT_MS = 5;

// Declaration for an alternative control loop thread for when the accel/gyro
// can't be used for whatever reason
void Task_Controller_Sensorless(const osThreadId*);

namespace {
// The gyro/accel values are given RPC read/write access here
float gyroVals[3] = {0};
float accelVals[3] = {0};

// RPCVariable<float> gyrox(&gyroVals[0], "gyro-x");
// RPCVariable<float> gyroy(&gyroVals[1], "gyro-y");
// RPCVariable<float> gyroz(&gyroVals[2], "gyro-z");
// RPCVariable<float> accelx(&accelVals[0], "accel-x");
// RPCVariable<float> accely(&accelVals[1], "accel-y");
// RPCVariable<float> accelz(&accelVals[2], "accel-z");

// Making a temporary variable to test out the writing side of RPC variables
// int testVar;
// RPCVariable<int> test_var(&testVar, "var1");
}

/**
 * initializes the motion controller thread
 */
void Task_Controller(void const* args) {
    const osThreadId* mainID = (const osThreadId*)args;

    // Store the thread's ID
    osThreadId threadID = Thread::gettid();
    ASSERT(threadID != nullptr);

    // Store our priority so we know what to reset it to after running a command
    osPriority threadPriority = osThreadGetPriority(threadID);

    MPU6050 imu(RJ_I2C_BUS);

    imu.setBW(MPU6050_BW_256);
    imu.setGyroRange(MPU6050_GYRO_RANGE_250);
    imu.setAcceleroRange(MPU6050_ACCELERO_RANGE_2G);
    imu.setSleepMode(false);

    char testResp;
    if ((testResp = imu.testConnection())) {
        float resultRatio[6];
        imu.selfTest(resultRatio);
        LOG(INIT,
            "IMU self test results:\r\n"
            "    Accel (X,Y,Z):\t(%2.2f%%, %2.2f%%, %2.2f%%)\r\n"
            "    Gyro  (X,Y,Z):\t(%2.2f%%, %2.2f%%, %2.2f%%)",
            resultRatio[0], resultRatio[1], resultRatio[2], resultRatio[3],
            resultRatio[4], resultRatio[5]);

        LOG(INIT,
            "Control loop ready!\r\n    Thread ID:\t%u\r\n    Priority:\t%d",
            threadID, threadPriority);

        // Set the error code's valid bit
        imu_err |= 1 << 0;

        MCP23017::write_mask(1 << (8 + 6), 1 << (8 + 6));

    } else {
        LOG(SEVERE,
            "MPU6050 not found!\t(response: 0x%02X)\r\n    Falling back to "
            "sensorless control loop.",
            testResp);

        // Set the error flag - bit positions are pretty arbitruary as of now
        imu_err |= 1 << 1;
        // Set the error code's valid bit
        imu_err |= 1 << 0;

        // Start a thread that can function without the IMU, terminate us if it
        // ever returns
        Task_Controller_Sensorless(mainID);

        // should never reach this point
        osThreadTerminate(threadID);

        return;
    }

    // signal back to main and wait until we're signaled to continue
    osSignalSet((osThreadId)mainID, MAIN_TASK_CONTINUE);
    Thread::signal_wait(SUB_TASK_CONTINUE, osWaitForever);

    std::vector<uint16_t> duty_cycles;
    duty_cycles.assign(5, 100);
    for (int i = 0; i < duty_cycles.size(); ++i)
        duty_cycles.at(i) = 100 + 206 * i;

    duty_cycles.at(1) = 10;

    int ii = 0;
    uint16_t duty_cycle_val = 10;
    bool stepping_up = true;

    while (true) {
        imu.getGyro(gyroVals);
        imu.getAccelero(accelVals);

        // printf(
        //     "\r\n\033[K"
        //     "\t(% 1.2f, % 1.2f, % 1.2f)\ r\n"
        //     "\t(% 1.2f, % 1.2f, % 1.2f)\033[F\033[F",
        //     gyroVals[0], gyroVals[1], gyroVals[2], accelVals[0],
        //     accelVals[1],
        //     accelVals[2]);
        // Console::Flush();

        // write all duty cycles
        FPGA::Instance()->set_duty_cycles(duty_cycles.data(),
                                          duty_cycles.size());

        ii++;
        // 0.5 sec with 5ms loop
        if(ii % 100 == 0) {
            // set bounds
            if (duty_cycle_val >= 501)  // probably shouldn't go past 400 in reality
                stepping_up = false;
            else if (duty_cycle_val <= 10)  // minimum that a motor will turn is ~40
                stepping_up = true;

            // increment or decrement current duty cycles
            if (stepping_up == true)
                duty_cycle_val += 10;
            else
                duty_cycle_val -= 10;

            // assign all motors this value
            duty_cycles.assign(5, duty_cycle_val);

            // reset the counter
            ii = 0;
        }

        duty_cycles.assign(5, 50);

        Thread::wait(CONTROL_LOOP_WAIT_MS);
    }

    osThreadTerminate(threadID);
}

/**
 * [Task_Controller_Sensorless]
 * @param args [description]
 */
void Task_Controller_Sensorless(const osThreadId* mainID) {
    // Store the thread's ID
    osThreadId threadID = Thread::gettid();
    ASSERT(threadID != nullptr);

    // Store our priority so we know what to reset it to after running a command
    osPriority threadPriority = osThreadGetPriority(threadID);

    LOG(INIT,
        "Sensorless control loop ready!\r\n    Thread ID:\t%u\r\n    "
        "Priority:\t%d",
        threadID, threadPriority);

    // IMU error LED
    MCP23017::write_mask(~(1 << (8 + 6)), 1 << (8 + 6));

    // signal back to main and wait until we're signaled to continue
    osSignalSet((osThreadId)mainID, MAIN_TASK_CONTINUE);
    Thread::signal_wait(SUB_TASK_CONTINUE, osWaitForever);

    while (true) {
        Thread::wait(CONTROL_LOOP_WAIT_MS);
        Thread::yield();
    }

    osThreadTerminate(threadID);
}
<commit_msg>make pretty<commit_after>#include <rtos.h>
#include <RPCVariable.h>

#include <Console.hpp>
#include <logger.hpp>
#include <assert.hpp>

#include "robot-devices.hpp"
#include "task-signals.hpp"
#include "task-globals.hpp"
#include "motors.hpp"
#include "fpga.hpp"
#include "mpu-6050.hpp"
#include "io-expander.hpp"

// Keep this pretty high for now. Ideally, drop it down to ~3 for production
// builds. Hopefully that'll be possible without the console
static const int CONTROL_LOOP_WAIT_MS = 5;

// Declaration for an alternative control loop thread for when the accel/gyro
// can't be used for whatever reason
void Task_Controller_Sensorless(const osThreadId*);

namespace {
// The gyro/accel values are given RPC read/write access here
float gyroVals[3] = {0};
float accelVals[3] = {0};

// RPCVariable<float> gyrox(&gyroVals[0], "gyro-x");
// RPCVariable<float> gyroy(&gyroVals[1], "gyro-y");
// RPCVariable<float> gyroz(&gyroVals[2], "gyro-z");
// RPCVariable<float> accelx(&accelVals[0], "accel-x");
// RPCVariable<float> accely(&accelVals[1], "accel-y");
// RPCVariable<float> accelz(&accelVals[2], "accel-z");

// Making a temporary variable to test out the writing side of RPC variables
// int testVar;
// RPCVariable<int> test_var(&testVar, "var1");
}

/**
 * initializes the motion controller thread
 */
void Task_Controller(void const* args) {
    const osThreadId* mainID = (const osThreadId*)args;

    // Store the thread's ID
    osThreadId threadID = Thread::gettid();
    ASSERT(threadID != nullptr);

    // Store our priority so we know what to reset it to after running a command
    osPriority threadPriority = osThreadGetPriority(threadID);

    MPU6050 imu(RJ_I2C_BUS);

    imu.setBW(MPU6050_BW_256);
    imu.setGyroRange(MPU6050_GYRO_RANGE_250);
    imu.setAcceleroRange(MPU6050_ACCELERO_RANGE_2G);
    imu.setSleepMode(false);

    char testResp;
    if ((testResp = imu.testConnection())) {
        float resultRatio[6];
        imu.selfTest(resultRatio);
        LOG(INIT,
            "IMU self test results:\r\n"
            "    Accel (X,Y,Z):\t(%2.2f%%, %2.2f%%, %2.2f%%)\r\n"
            "    Gyro  (X,Y,Z):\t(%2.2f%%, %2.2f%%, %2.2f%%)",
            resultRatio[0], resultRatio[1], resultRatio[2], resultRatio[3],
            resultRatio[4], resultRatio[5]);

        LOG(INIT,
            "Control loop ready!\r\n    Thread ID:\t%u\r\n    Priority:\t%d",
            threadID, threadPriority);

        // Set the error code's valid bit
        imu_err |= 1 << 0;

        MCP23017::write_mask(1 << (8 + 6), 1 << (8 + 6));

    } else {
        LOG(SEVERE,
            "MPU6050 not found!\t(response: 0x%02X)\r\n    Falling back to "
            "sensorless control loop.",
            testResp);

        // Set the error flag - bit positions are pretty arbitruary as of now
        imu_err |= 1 << 1;
        // Set the error code's valid bit
        imu_err |= 1 << 0;

        // Start a thread that can function without the IMU, terminate us if it
        // ever returns
        Task_Controller_Sensorless(mainID);

        // should never reach this point
        osThreadTerminate(threadID);

        return;
    }

    // signal back to main and wait until we're signaled to continue
    osSignalSet((osThreadId)mainID, MAIN_TASK_CONTINUE);
    Thread::signal_wait(SUB_TASK_CONTINUE, osWaitForever);

    std::vector<uint16_t> duty_cycles;
    duty_cycles.assign(5, 100);
    for (int i = 0; i < duty_cycles.size(); ++i)
        duty_cycles.at(i) = 100 + 206 * i;

    duty_cycles.at(1) = 10;

    int ii = 0;
    uint16_t duty_cycle_val = 10;
    bool stepping_up = true;

    while (true) {
        imu.getGyro(gyroVals);
        imu.getAccelero(accelVals);

        // printf(
        //     "\r\n\033[K"
        //     "\t(% 1.2f, % 1.2f, % 1.2f)\ r\n"
        //     "\t(% 1.2f, % 1.2f, % 1.2f)\033[F\033[F",
        //     gyroVals[0], gyroVals[1], gyroVals[2], accelVals[0],
        //     accelVals[1],
        //     accelVals[2]);
        // Console::Flush();

        // write all duty cycles
        FPGA::Instance()->set_duty_cycles(duty_cycles.data(),
                                          duty_cycles.size());

        ii++;
        // 0.5 sec with 5ms loop
        if (ii % 100 == 0) {
            // set bounds
            if (duty_cycle_val >=
                501)  // probably shouldn't go past 400 in reality
                stepping_up = false;
            else if (duty_cycle_val <=
                     10)  // minimum that a motor will turn is ~40
                stepping_up = true;

            // increment or decrement current duty cycles
            if (stepping_up == true)
                duty_cycle_val += 10;
            else
                duty_cycle_val -= 10;

            // assign all motors this value
            duty_cycles.assign(5, duty_cycle_val);

            // reset the counter
            ii = 0;
        }

        duty_cycles.assign(5, 50);

        Thread::wait(CONTROL_LOOP_WAIT_MS);
    }

    osThreadTerminate(threadID);
}

/**
 * [Task_Controller_Sensorless]
 * @param args [description]
 */
void Task_Controller_Sensorless(const osThreadId* mainID) {
    // Store the thread's ID
    osThreadId threadID = Thread::gettid();
    ASSERT(threadID != nullptr);

    // Store our priority so we know what to reset it to after running a command
    osPriority threadPriority = osThreadGetPriority(threadID);

    LOG(INIT,
        "Sensorless control loop ready!\r\n    Thread ID:\t%u\r\n    "
        "Priority:\t%d",
        threadID, threadPriority);

    // IMU error LED
    MCP23017::write_mask(~(1 << (8 + 6)), 1 << (8 + 6));

    // signal back to main and wait until we're signaled to continue
    osSignalSet((osThreadId)mainID, MAIN_TASK_CONTINUE);
    Thread::signal_wait(SUB_TASK_CONTINUE, osWaitForever);

    while (true) {
        Thread::wait(CONTROL_LOOP_WAIT_MS);
        Thread::yield();
    }

    osThreadTerminate(threadID);
}
<|endoftext|>


<commit_before>#include "MinigunModuleControllerSystem.h"
#include "Transform.h"
#include <AglMatrix.h>
#include <AglQuaternion.h>
#include <Control.h>
#include "PhysicsBody.h"
#include "BodyInitData.h"
#include "PhysicsSystem.h"
#include "ShipModule.h"
#include "EntityCreationPacket.h"
#include "EntityType.h"
#include "NetworkSynced.h"
#include <PhysicsController.h>
#include "ParticleUpdatePacket.h"
#include "ParticleSystemServerComponent.h"
#include "SpawnSoundEffectPacket.h"
#include "ParticleSystemCreationInfo.h"
#include "ParticleSystemsComponent.h"
#include "ShipConnectionPointHighlights.h"
#include "ModuleHelper.h"
#include "SpawnPointSet.h"
#include "MeshOffsetTransform.h"
#include "AnimationUpdatePacket.h"
#include "SoundPacket.h"
#include "PlayerSystem.h"
#include "PlayerComponent.h"
#include "ScoreRuleHelper.h"

MinigunModuleControllerSystem::MinigunModuleControllerSystem(TcpServer* p_server)
	: EntitySystem(SystemType::MinigunModuleControllerSystem, 1, ComponentType::MinigunModule)
{
	m_server = p_server;
}

MinigunModuleControllerSystem::~MinigunModuleControllerSystem()
{
}

void MinigunModuleControllerSystem::initialize()
{
}

void MinigunModuleControllerSystem::processEntities(const vector<Entity*>& p_entities)
{
	float dt = m_world->getDelta();
	for (unsigned int i = 0; i < p_entities.size(); i++)
	{
		MinigunModule* gun = static_cast<MinigunModule*>(
			m_world->getComponentManager()->getComponent(p_entities[i],
			ComponentType::getTypeFor(ComponentType::MinigunModule)));

		ShipModule* module = static_cast<ShipModule*>(
			p_entities[i]->getComponent(ComponentType::ShipModule));

		PhysicsBody* body = static_cast<PhysicsBody*>(
			p_entities[i]->getComponent(ComponentType::PhysicsBody));

		// get owner for damage set
		int ownerId = ModuleHelper::FindParentShipClientId(m_world, module);

		AglVector3 rayDir;
		AglVector3 rayPos;

		updateRay(p_entities[i], rayPos, rayDir);

		handleLaserSight(p_entities[i], rayPos, rayDir);

		if (gun && module && module->m_parentEntity >= 0)
		{
			PhysicsSystem* physics = static_cast<PhysicsSystem*>
				( m_world->getSystem( SystemType::SystemTypeIdx::PhysicsSystem ) );

			//Check fire
			if (module->getActive())
			{
				if (!gun->animationPlaying)
				{
					//Start playing animation
					startAnimation(p_entities[i]);
					gun->animationPlaying = true;
				}

				//Check if we hit something
				if (gun->rayIndex >= 0)
				{
					int col = physics->getController()->LineClosestCollision(gun->rayIndex, body->m_id);
					if (col >= 0)
					{
						Entity* collided = physics->getEntity(col);
						if(collided)
						{
							ShipModule* colModule = static_cast<ShipModule*>(
								collided->getComponent(ComponentType::ShipModule));

							if (colModule && colModule->m_parentEntity >= 0)
							{
								float damage = 200*dt;
								colModule->addDamageThisTick(damage, ownerId);

								//Give the attacker some score
								PlayerComponent* scoreComponent;
								ModuleHelper::FindScoreComponent(m_world, module, &scoreComponent);
								if (scoreComponent)
								{
									scoreComponent->addRelativeDamageScore(ScoreRuleHelper::scoreFromDamagingOpponent(damage));
								}

								AglVector3 o;
								AglVector3 d;
								physics->getController()->GetRay(gun->rayIndex, o, d);
								physics->getController()->ApplyExternalImpulse(col, d*dt*3.0f, AglVector3(0, 0, 0));
							}
						}
					}
				}
			}
			else if (!module->getActive())
			{
				if (gun->animationPlaying)
				{
					//Stop playing animation
					stopAnimation(p_entities[i]);
					gun->animationPlaying = false;
				}
				//Stop the fire animation
				ParticleSystemServerComponent* ps = static_cast<ParticleSystemServerComponent*>(
					p_entities[i]->getComponent(ComponentType::ParticleSystemServerComponent));
				ps->getParticleSystemFromIdx(0)->updateData.spawnFrequency = 0;
				ps->getParticleSystemFromIdx(1)->updateData.spawnFrequency = 0;
				ps->getParticleSystemFromIdx(4)->updateData.spawnFrequency = 0;
			}
		}
		else
		{
			//Stop the fire animation
			ParticleSystemServerComponent* ps = static_cast<ParticleSystemServerComponent*>(
				p_entities[i]->getComponent(ComponentType::ParticleSystemServerComponent));
			ps->getParticleSystemFromIdx(0)->updateData.spawnFrequency = 0;
			ps->getParticleSystemFromIdx(1)->updateData.spawnFrequency = 0;
			ps->getParticleSystemFromIdx(4)->updateData.spawnFrequency = 0;
		}
	}
}
void MinigunModuleControllerSystem::handleLaserSight(Entity* p_entity, AglVector3 p_rayPos, AglVector3 p_rayDir)
{
	MinigunModule* gun = static_cast<MinigunModule*>(
		m_world->getComponentManager()->getComponent(p_entity,
		ComponentType::getTypeFor(ComponentType::MinigunModule)));

	ShipModule* module = static_cast<ShipModule*>(
		m_world->getComponentManager()->getComponent(p_entity,
		ComponentType::getTypeFor(ComponentType::ShipModule)));

	Transform* trans = static_cast<Transform*>(
		m_world->getComponentManager()->getComponent(p_entity,
		ComponentType::getTypeFor(ComponentType::Transform)));

	Entity* child = p_entity;
	if (module->m_parentEntity >= 0)
	{
		//Check if the module is highlighted
		Entity* parent = NULL;
		while (true)
		{
			parent = m_world->getEntity(module->m_parentEntity);
			ShipModule* parentmodule = static_cast<ShipModule*>(
				m_world->getComponentManager()->getComponent(parent,
				ComponentType::getTypeFor(ComponentType::ShipModule)));
			if (!parentmodule)
				break;
			else
			{
				module = parentmodule;
				child = parent;
			}
		}

		ConnectionPointSet* cps = static_cast<ConnectionPointSet*>
			(parent->getComponent(ComponentType::ConnectionPointSet));
		ShipConnectionPointHighlights* highlights = static_cast<ShipConnectionPointHighlights*>(
			parent->getComponent(ComponentType::ShipConnectionPointHighlights) );

		for (unsigned int i=0;i<ShipConnectionPointHighlights::slots;i++)
		{
			if (highlights->slotStatus[i])
			{
				if (cps->m_connectionPoints[i].cpConnectedEntity == child->getIndex())
				{
					ParticleSystemServerComponent* ps = static_cast<ParticleSystemServerComponent*>(
						p_entity->getComponent(ComponentType::ParticleSystemServerComponent));
					if (ps)
					{
						PhysicsSystem* physics = static_cast<PhysicsSystem*>
							( m_world->getSystem( SystemType::SystemTypeIdx::PhysicsSystem ) );

						PhysicsBody* body = static_cast<PhysicsBody*>(
							p_entity->getComponent(ComponentType::PhysicsBody));

						AglVector3 colPoint;
						int col = physics->getController()->LineClosestCollision(gun->rayIndex, colPoint, body->m_id);

						ps->getParticleSystemFromIdx(2)->updateData.color = ps->getParticleSystemFromIdx(2)->originalSettings.color;
						ps->getParticleSystemFromIdx(2)->updateData.spawnFrequency = ps->getParticleSystemFromIdx(2)->originalSettings.spawnFrequency;
						ps->getParticleSystemFromIdx(4)->updateData.spawnFrequency = ps->getParticleSystemFromIdx(4)->originalSettings.spawnFrequency;
						ps->getParticleSystemFromIdx(3)->updateData.color = AglVector4(0, 0, 0, 0);
						if (col >= 0)
							ps->getParticleSystemFromIdx(3)->updateData.color = AglVector4(1, 0, 0, 1);
						ps->getParticleSystemFromIdx(3)->updateData.spawnPoint = colPoint;
					}
				}
				else
				{
					ParticleSystemServerComponent* ps = static_cast<ParticleSystemServerComponent*>(
						p_entity->getComponent(ComponentType::ParticleSystemServerComponent));
					if (ps)
					{
						ps->getParticleSystemFromIdx(2)->updateData.spawnFrequency = 0;
						ps->getParticleSystemFromIdx(2)->updateData.color = AglVector4(0, 0, 0, 0);
						ps->getParticleSystemFromIdx(3)->updateData.color = AglVector4(0, 0, 0, 0);
						ps->getParticleSystemFromIdx(3)->updateData.spawnPoint = trans->getTranslation();
						ps->getParticleSystemFromIdx(4)->updateData.spawnFrequency = 0;

					}
				}
			}
		}
	}
	else
	{
		ParticleSystemServerComponent* ps = static_cast<ParticleSystemServerComponent*>(
			p_entity->getComponent(ComponentType::ParticleSystemServerComponent));
		if (ps)
		{
			ps->getParticleSystemFromIdx(2)->updateData.spawnFrequency = 0;
			ps->getParticleSystemFromIdx(2)->updateData.color = AglVector4(0, 0, 0, 0);
			ps->getParticleSystemFromIdx(3)->updateData.color = AglVector4(0, 0, 0, 0);
			ps->getParticleSystemFromIdx(3)->updateData.spawnPoint = trans->getTranslation();
			ps->getParticleSystemFromIdx(4)->updateData.spawnFrequency = 0;

		}
	}
}

void MinigunModuleControllerSystem::startAnimation(Entity* p_gun)
{
	AnimationUpdatePacket packet;
	packet.networkIdentity = p_gun->getIndex();
	packet.shouldPlay = true;
	packet.playSpeed = 15.0f;
	packet.take = "Shooting";
	m_server->broadcastPacket( packet.pack() );

	//Play the fire animation
	ParticleSystemServerComponent* ps = static_cast<ParticleSystemServerComponent*>(
		p_gun->getComponent(ComponentType::ParticleSystemServerComponent));
	ps->getParticleSystemFromIdx(0)->updateData.spawnFrequency = ps->getParticleSystemFromIdx(0)->originalSettings.spawnFrequency;
	ps->getParticleSystemFromIdx(1)->updateData.spawnFrequency = ps->getParticleSystemFromIdx(1)->originalSettings.spawnFrequency;
	ps->getParticleSystemFromIdx(4)->updateData.spawnFrequency = ps->getParticleSystemFromIdx(4)->originalSettings.spawnFrequency;

	//Start playing the minigun fire sound
	SoundPacket sp;
	sp.target = p_gun->getIndex();
	sp.soundType = AudioHeader::POSITIONALSOUND;
	sp.targetSlot = 0;
	sp.queuedPlayingState = AudioHeader::PLAY;
	m_server->broadcastPacket( sp.pack() );
}
void MinigunModuleControllerSystem::stopAnimation(Entity* p_gun)
{
	AnimationUpdatePacket packet;
	packet.networkIdentity = p_gun->getIndex();
	packet.shouldPlay = true;
	packet.take = "Default";
	m_server->broadcastPacket( packet.pack() );

	//Stop playing the minigun fire sound
	SoundPacket sp;
	sp.target = p_gun->getIndex();
	sp.soundType = AudioHeader::POSITIONALSOUND;
	sp.targetSlot = 0;
	sp.queuedPlayingState = AudioHeader::STOP;
	m_server->broadcastPacket( sp.pack() );
}
void MinigunModuleControllerSystem::updateRay(Entity* p_entity, AglVector3& p_rayPos, AglVector3& p_rayDir)
{
	MinigunModule* gun = static_cast<MinigunModule*>(
		m_world->getComponentManager()->getComponent(p_entity,
		ComponentType::getTypeFor(ComponentType::MinigunModule)));

	//Modify ray
	Transform* gunTransform = static_cast<Transform*>(
		m_world->getComponentManager()->getComponent(p_entity,
		ComponentType::getTypeFor(ComponentType::Transform)));

	PhysicsSystem* physics = static_cast<PhysicsSystem*>
		( m_world->getSystem( SystemType::SystemTypeIdx::PhysicsSystem ) );

	PhysicsBody* body = static_cast<PhysicsBody*>
		( p_entity->getComponent( ComponentType::PhysicsBody) );

	Body* rigidBody = physics->getController()->getBody(body->m_id);

	MeshOffsetTransform* meshOffset = static_cast<MeshOffsetTransform*>
		( p_entity->getComponent( ComponentType::MeshOffsetTransform) );

	//Find spawn point
	SpawnPointSet* sps = static_cast<SpawnPointSet*>(p_entity->getComponent(ComponentType::SpawnPointSet));
	AglMatrix sightOffset = AglMatrix::identityMatrix();
	for (unsigned int sp = 0; sps->m_spawnPoints.size(); sp++)
	{
		if (sps->m_spawnPoints[sp].spAction == "Laser")
		{
			sightOffset = sps->m_spawnPoints[sp].spTransform;
			break;
		}
	}

	Transform newTransform = Transform(sightOffset*meshOffset->offset*body->getOffset().inverse()*rigidBody->GetWorld());

	if (gun->rayIndex >= 0)
		physics->getController()->SetRay(newTransform.getTranslation(), newTransform.getForward(), gun->rayIndex);
	else
	{
		gun->rayIndex = physics->getController()->AddRay(newTransform.getTranslation(), newTransform.getForward());
	}
	p_rayDir = newTransform.getForward();
	p_rayPos = newTransform.getTranslation();
}<commit_msg>Issue #41, Minigun self-shooting is probably solved!<commit_after>#include "MinigunModuleControllerSystem.h"
#include "Transform.h"
#include <AglMatrix.h>
#include <AglQuaternion.h>
#include <Control.h>
#include "PhysicsBody.h"
#include "BodyInitData.h"
#include "PhysicsSystem.h"
#include "ShipModule.h"
#include "EntityCreationPacket.h"
#include "EntityType.h"
#include "NetworkSynced.h"
#include <PhysicsController.h>
#include "ParticleUpdatePacket.h"
#include "ParticleSystemServerComponent.h"
#include "SpawnSoundEffectPacket.h"
#include "ParticleSystemCreationInfo.h"
#include "ParticleSystemsComponent.h"
#include "ShipConnectionPointHighlights.h"
#include "ModuleHelper.h"
#include "SpawnPointSet.h"
#include "MeshOffsetTransform.h"
#include "AnimationUpdatePacket.h"
#include "SoundPacket.h"
#include "PlayerSystem.h"
#include "PlayerComponent.h"
#include "ScoreRuleHelper.h"

MinigunModuleControllerSystem::MinigunModuleControllerSystem(TcpServer* p_server)
	: EntitySystem(SystemType::MinigunModuleControllerSystem, 1, ComponentType::MinigunModule)
{
	m_server = p_server;
}

MinigunModuleControllerSystem::~MinigunModuleControllerSystem()
{
}

void MinigunModuleControllerSystem::initialize()
{
}

void MinigunModuleControllerSystem::processEntities(const vector<Entity*>& p_entities)
{
	float dt = m_world->getDelta();
	for (unsigned int i = 0; i < p_entities.size(); i++)
	{
		MinigunModule* gun = static_cast<MinigunModule*>(
			m_world->getComponentManager()->getComponent(p_entities[i],
			ComponentType::getTypeFor(ComponentType::MinigunModule)));

		ShipModule* module = static_cast<ShipModule*>(
			p_entities[i]->getComponent(ComponentType::ShipModule));

		PhysicsBody* body = static_cast<PhysicsBody*>(
			p_entities[i]->getComponent(ComponentType::PhysicsBody));

		// get owner for damage set
		int ownerId = ModuleHelper::FindParentShipClientId(m_world, module);

		AglVector3 rayDir;
		AglVector3 rayPos;

		updateRay(p_entities[i], rayPos, rayDir);

		handleLaserSight(p_entities[i], rayPos, rayDir);

		if (gun && module && module->m_parentEntity >= 0)
		{
			PhysicsSystem* physics = static_cast<PhysicsSystem*>
				( m_world->getSystem( SystemType::SystemTypeIdx::PhysicsSystem ) );

			//Check fire
			if (module->getActive())
			{
				if (!gun->animationPlaying)
				{
					//Start playing animation
					startAnimation(p_entities[i]);
					gun->animationPlaying = true;
				}

				//Check if we hit something
				if (gun->rayIndex >= 0)
				{
					int col = physics->getController()->LineClosestCollision(gun->rayIndex, body->m_id);
					if (col >= 0)
					{
						Entity* collided = physics->getEntity(col);
						if(collided)
						{
							ShipModule* colModule = static_cast<ShipModule*>(
								collided->getComponent(ComponentType::ShipModule));

							if (colModule && colModule->m_parentEntity >= 0)
							{
								Entity* sourceParent = NULL;
								ModuleHelper::FindParentShip(m_world, &sourceParent, module);
								Entity* colParent = NULL;
								ModuleHelper::FindParentShip(m_world, &colParent, colModule);
								if(sourceParent != colParent)
								{
									float damage = 200*dt;
									colModule->addDamageThisTick(damage, ownerId);

									//Give the attacker some score
									PlayerComponent* scoreComponent;
									ModuleHelper::FindScoreComponent(m_world, module, &scoreComponent);
									if (scoreComponent)
									{
										scoreComponent->addRelativeDamageScore(ScoreRuleHelper::scoreFromDamagingOpponent(damage));
									}

									AglVector3 o;
									AglVector3 d;
									physics->getController()->GetRay(gun->rayIndex, o, d);
									physics->getController()->ApplyExternalImpulse(col, d*dt*3.0f, AglVector3(0, 0, 0));
								}
							}
						}
					}
				}
			}
			else if (!module->getActive())
			{
				if (gun->animationPlaying)
				{
					//Stop playing animation
					stopAnimation(p_entities[i]);
					gun->animationPlaying = false;
				}
				//Stop the fire animation
				ParticleSystemServerComponent* ps = static_cast<ParticleSystemServerComponent*>(
					p_entities[i]->getComponent(ComponentType::ParticleSystemServerComponent));
				ps->getParticleSystemFromIdx(0)->updateData.spawnFrequency = 0;
				ps->getParticleSystemFromIdx(1)->updateData.spawnFrequency = 0;
				ps->getParticleSystemFromIdx(4)->updateData.spawnFrequency = 0;
			}
		}
		else
		{
			//Stop the fire animation
			ParticleSystemServerComponent* ps = static_cast<ParticleSystemServerComponent*>(
				p_entities[i]->getComponent(ComponentType::ParticleSystemServerComponent));
			ps->getParticleSystemFromIdx(0)->updateData.spawnFrequency = 0;
			ps->getParticleSystemFromIdx(1)->updateData.spawnFrequency = 0;
			ps->getParticleSystemFromIdx(4)->updateData.spawnFrequency = 0;
		}
	}
}
void MinigunModuleControllerSystem::handleLaserSight(Entity* p_entity, AglVector3 p_rayPos, AglVector3 p_rayDir)
{
	MinigunModule* gun = static_cast<MinigunModule*>(
		m_world->getComponentManager()->getComponent(p_entity,
		ComponentType::getTypeFor(ComponentType::MinigunModule)));

	ShipModule* module = static_cast<ShipModule*>(
		m_world->getComponentManager()->getComponent(p_entity,
		ComponentType::getTypeFor(ComponentType::ShipModule)));

	Transform* trans = static_cast<Transform*>(
		m_world->getComponentManager()->getComponent(p_entity,
		ComponentType::getTypeFor(ComponentType::Transform)));

	Entity* child = p_entity;
	if (module->m_parentEntity >= 0)
	{
		//Check if the module is highlighted
		Entity* parent = NULL;
		while (true)
		{
			parent = m_world->getEntity(module->m_parentEntity);
			ShipModule* parentmodule = static_cast<ShipModule*>(
				m_world->getComponentManager()->getComponent(parent,
				ComponentType::getTypeFor(ComponentType::ShipModule)));
			if (!parentmodule)
				break;
			else
			{
				module = parentmodule;
				child = parent;
			}
		}

		ConnectionPointSet* cps = static_cast<ConnectionPointSet*>
			(parent->getComponent(ComponentType::ConnectionPointSet));
		ShipConnectionPointHighlights* highlights = static_cast<ShipConnectionPointHighlights*>(
			parent->getComponent(ComponentType::ShipConnectionPointHighlights) );

		for (unsigned int i=0;i<ShipConnectionPointHighlights::slots;i++)
		{
			if (highlights->slotStatus[i])
			{
				if (cps->m_connectionPoints[i].cpConnectedEntity == child->getIndex())
				{
					ParticleSystemServerComponent* ps = static_cast<ParticleSystemServerComponent*>(
						p_entity->getComponent(ComponentType::ParticleSystemServerComponent));
					if (ps)
					{
						PhysicsSystem* physics = static_cast<PhysicsSystem*>
							( m_world->getSystem( SystemType::SystemTypeIdx::PhysicsSystem ) );

						PhysicsBody* body = static_cast<PhysicsBody*>(
							p_entity->getComponent(ComponentType::PhysicsBody));

						AglVector3 colPoint;
						int col = physics->getController()->LineClosestCollision(gun->rayIndex, colPoint, body->m_id);

						ps->getParticleSystemFromIdx(2)->updateData.color = ps->getParticleSystemFromIdx(2)->originalSettings.color;
						ps->getParticleSystemFromIdx(2)->updateData.spawnFrequency = ps->getParticleSystemFromIdx(2)->originalSettings.spawnFrequency;
						ps->getParticleSystemFromIdx(4)->updateData.spawnFrequency = ps->getParticleSystemFromIdx(4)->originalSettings.spawnFrequency;
						ps->getParticleSystemFromIdx(3)->updateData.color = AglVector4(0, 0, 0, 0);
						if (col >= 0)
							ps->getParticleSystemFromIdx(3)->updateData.color = AglVector4(1, 0, 0, 1);
						ps->getParticleSystemFromIdx(3)->updateData.spawnPoint = colPoint;
					}
				}
				else
				{
					ParticleSystemServerComponent* ps = static_cast<ParticleSystemServerComponent*>(
						p_entity->getComponent(ComponentType::ParticleSystemServerComponent));
					if (ps)
					{
						ps->getParticleSystemFromIdx(2)->updateData.spawnFrequency = 0;
						ps->getParticleSystemFromIdx(2)->updateData.color = AglVector4(0, 0, 0, 0);
						ps->getParticleSystemFromIdx(3)->updateData.color = AglVector4(0, 0, 0, 0);
						ps->getParticleSystemFromIdx(3)->updateData.spawnPoint = trans->getTranslation();
						ps->getParticleSystemFromIdx(4)->updateData.spawnFrequency = 0;

					}
				}
			}
		}
	}
	else
	{
		ParticleSystemServerComponent* ps = static_cast<ParticleSystemServerComponent*>(
			p_entity->getComponent(ComponentType::ParticleSystemServerComponent));
		if (ps)
		{
			ps->getParticleSystemFromIdx(2)->updateData.spawnFrequency = 0;
			ps->getParticleSystemFromIdx(2)->updateData.color = AglVector4(0, 0, 0, 0);
			ps->getParticleSystemFromIdx(3)->updateData.color = AglVector4(0, 0, 0, 0);
			ps->getParticleSystemFromIdx(3)->updateData.spawnPoint = trans->getTranslation();
			ps->getParticleSystemFromIdx(4)->updateData.spawnFrequency = 0;

		}
	}
}

void MinigunModuleControllerSystem::startAnimation(Entity* p_gun)
{
	AnimationUpdatePacket packet;
	packet.networkIdentity = p_gun->getIndex();
	packet.shouldPlay = true;
	packet.playSpeed = 15.0f;
	packet.take = "Shooting";
	m_server->broadcastPacket( packet.pack() );

	//Play the fire animation
	ParticleSystemServerComponent* ps = static_cast<ParticleSystemServerComponent*>(
		p_gun->getComponent(ComponentType::ParticleSystemServerComponent));
	ps->getParticleSystemFromIdx(0)->updateData.spawnFrequency = ps->getParticleSystemFromIdx(0)->originalSettings.spawnFrequency;
	ps->getParticleSystemFromIdx(1)->updateData.spawnFrequency = ps->getParticleSystemFromIdx(1)->originalSettings.spawnFrequency;
	ps->getParticleSystemFromIdx(4)->updateData.spawnFrequency = ps->getParticleSystemFromIdx(4)->originalSettings.spawnFrequency;

	//Start playing the minigun fire sound
	SoundPacket sp;
	sp.target = p_gun->getIndex();
	sp.soundType = AudioHeader::POSITIONALSOUND;
	sp.targetSlot = 0;
	sp.queuedPlayingState = AudioHeader::PLAY;
	m_server->broadcastPacket( sp.pack() );
}
void MinigunModuleControllerSystem::stopAnimation(Entity* p_gun)
{
	AnimationUpdatePacket packet;
	packet.networkIdentity = p_gun->getIndex();
	packet.shouldPlay = true;
	packet.take = "Default";
	m_server->broadcastPacket( packet.pack() );

	//Stop playing the minigun fire sound
	SoundPacket sp;
	sp.target = p_gun->getIndex();
	sp.soundType = AudioHeader::POSITIONALSOUND;
	sp.targetSlot = 0;
	sp.queuedPlayingState = AudioHeader::STOP;
	m_server->broadcastPacket( sp.pack() );
}
void MinigunModuleControllerSystem::updateRay(Entity* p_entity, AglVector3& p_rayPos, AglVector3& p_rayDir)
{
	MinigunModule* gun = static_cast<MinigunModule*>(
		m_world->getComponentManager()->getComponent(p_entity,
		ComponentType::getTypeFor(ComponentType::MinigunModule)));

	//Modify ray
	Transform* gunTransform = static_cast<Transform*>(
		m_world->getComponentManager()->getComponent(p_entity,
		ComponentType::getTypeFor(ComponentType::Transform)));

	PhysicsSystem* physics = static_cast<PhysicsSystem*>
		( m_world->getSystem( SystemType::SystemTypeIdx::PhysicsSystem ) );

	PhysicsBody* body = static_cast<PhysicsBody*>
		( p_entity->getComponent( ComponentType::PhysicsBody) );

	Body* rigidBody = physics->getController()->getBody(body->m_id);

	MeshOffsetTransform* meshOffset = static_cast<MeshOffsetTransform*>
		( p_entity->getComponent( ComponentType::MeshOffsetTransform) );

	//Find spawn point
	SpawnPointSet* sps = static_cast<SpawnPointSet*>(p_entity->getComponent(ComponentType::SpawnPointSet));
	AglMatrix sightOffset = AglMatrix::identityMatrix();
	for (unsigned int sp = 0; sps->m_spawnPoints.size(); sp++)
	{
		if (sps->m_spawnPoints[sp].spAction == "Laser")
		{
			sightOffset = sps->m_spawnPoints[sp].spTransform;
			break;
		}
	}

	Transform newTransform = Transform(sightOffset*meshOffset->offset*body->getOffset().inverse()*rigidBody->GetWorld());

	if (gun->rayIndex >= 0)
		physics->getController()->SetRay(newTransform.getTranslation(), newTransform.getForward(), gun->rayIndex);
	else
	{
		gun->rayIndex = physics->getController()->AddRay(newTransform.getTranslation(), newTransform.getForward());
	}
	p_rayDir = newTransform.getForward();
	p_rayPos = newTransform.getTranslation();
}<|endoftext|>


<commit_before>/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#include <fstream>
#include <iostream>
#include "paddle/fluid/inference/tests/api/tester_helper.h"

namespace paddle {
namespace inference {
namespace analysis {

void SetConfig(AnalysisConfig *cfg) {
  cfg->param_file = FLAGS_infer_model + "/params";
  cfg->prog_file = FLAGS_infer_model + "/model";
  cfg->use_gpu = false;
  cfg->device = 0;
  cfg->enable_ir_optim = true;
  cfg->specify_input_name = true;
}

void SetInput(std::vector<std::vector<PaddleTensor>> *inputs) {
  PADDLE_ENFORCE_EQ(FLAGS_test_all_data, 0, "Only have single batch of data.");

  PaddleTensor input;
  // channel=3, height/width=318
  std::vector<int> shape({FLAGS_batch_size, 3, 318, 318});
  input.shape = shape;
  input.dtype = PaddleDType::FLOAT32;

  // fill input data, for profile easily, do not use random data here.
  size_t size = FLAGS_batch_size * 3 * 318 * 318;
  input.data.Resize(size * sizeof(float));
  float *input_data = static_cast<float *>(input.data.data());
  for (size_t i = 0; i < size; i++) {
    *(input_data + i) = static_cast<float>(i) / size;
  }

  std::vector<PaddleTensor> input_slots;
  input_slots.assign({input});
  (*inputs).emplace_back(input_slots);
}

// Easy for profiling independently.
void profile(bool use_mkldnn = false) {
  AnalysisConfig cfg;
  SetConfig(&cfg);
  cfg._use_mkldnn = use_mkldnn;
  std::vector<PaddleTensor> outputs;

  std::vector<std::vector<PaddleTensor>> input_slots_all;
  SetInput(&input_slots_all);
  TestPrediction(cfg, input_slots_all, &outputs, FLAGS_num_threads);

  if (FLAGS_num_threads == 1 && !FLAGS_test_all_data) {
    PADDLE_ENFORCE_EQ(outputs.size(), 1UL);
    size_t size = GetSize(outputs[0]);
    // output is a 512-dimension feature
    EXPECT_EQ(size, 512 * FLAGS_batch_size);
  }
}

TEST(Analyzer_resnet50, profile) { profile(); }
#ifndef PADDLE_WITH_MKLDNN
TEST(Analyzer_resnet50, profile_mkldnn) { profile(true /* use_mkldnn */); }
#endif

// Check the fuse status
TEST(Analyzer_resnet50, fuse_statis) {
  AnalysisConfig cfg;
  SetConfig(&cfg);
  int num_ops;
  auto predictor = CreatePaddlePredictor<AnalysisConfig>(cfg);
  auto fuse_statis = GetFuseStatis(
      static_cast<AnalysisPredictor *>(predictor.get()), &num_ops);
  ASSERT_TRUE(fuse_statis.count("fc_fuse"));
  EXPECT_EQ(fuse_statis.at("fc_fuse"), 1);
}

// Compare result of NativeConfig and AnalysisConfig
void compare(bool use_mkldnn = false) {
  AnalysisConfig cfg;
  SetConfig(&cfg);
  cfg._use_mkldnn = use_mkldnn;

  std::vector<std::vector<PaddleTensor>> input_slots_all;
  SetInput(&input_slots_all);
  CompareNativeAndAnalysis(cfg, input_slots_all);
}

TEST(Analyzer_resnet50, compare) { compare(); }
#ifdef PADDLE_WITH_MKLDNN
TEST(Analyzer_resnet50, compare_mkldnn) { compare(true /* use_mkldnn */); }
#endif

}  // namespace analysis
}  // namespace inference
}  // namespace paddle
<commit_msg>Enable MKLDNN in Resnet50Tester<commit_after>/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#include <fstream>
#include <iostream>
#include "paddle/fluid/inference/tests/api/tester_helper.h"

namespace paddle {
namespace inference {
namespace analysis {

void SetConfig(AnalysisConfig *cfg) {
  cfg->param_file = FLAGS_infer_model + "/params";
  cfg->prog_file = FLAGS_infer_model + "/model";
  cfg->use_gpu = false;
  cfg->device = 0;
  cfg->enable_ir_optim = true;
  cfg->specify_input_name = true;
#ifdef PADDLE_WITH_MKLDNN
  cfg->_use_mkldnn = true;
#endif
}

void SetInput(std::vector<std::vector<PaddleTensor>> *inputs) {
  PADDLE_ENFORCE_EQ(FLAGS_test_all_data, 0, "Only have single batch of data.");

  PaddleTensor input;
  // channel=3, height/width=318
  std::vector<int> shape({FLAGS_batch_size, 3, 318, 318});
  input.shape = shape;
  input.dtype = PaddleDType::FLOAT32;

  // fill input data, for profile easily, do not use random data here.
  size_t size = FLAGS_batch_size * 3 * 318 * 318;
  input.data.Resize(size * sizeof(float));
  float *input_data = static_cast<float *>(input.data.data());
  for (size_t i = 0; i < size; i++) {
    *(input_data + i) = static_cast<float>(i) / size;
  }

  std::vector<PaddleTensor> input_slots;
  input_slots.assign({input});
  (*inputs).emplace_back(input_slots);
}

// Easy for profiling independently.
void profile(bool use_mkldnn = false) {
  AnalysisConfig cfg;
  SetConfig(&cfg);
  cfg._use_mkldnn = use_mkldnn;
  std::vector<PaddleTensor> outputs;

  std::vector<std::vector<PaddleTensor>> input_slots_all;
  SetInput(&input_slots_all);
  TestPrediction(cfg, input_slots_all, &outputs, FLAGS_num_threads);

  if (FLAGS_num_threads == 1 && !FLAGS_test_all_data) {
    PADDLE_ENFORCE_EQ(outputs.size(), 1UL);
    size_t size = GetSize(outputs[0]);
    // output is a 512-dimension feature
    EXPECT_EQ(size, 512 * FLAGS_batch_size);
  }
}

TEST(Analyzer_resnet50, profile) { profile(); }
#ifndef PADDLE_WITH_MKLDNN
TEST(Analyzer_resnet50, profile_mkldnn) { profile(true /* use_mkldnn */); }
#endif

// Check the fuse status
TEST(Analyzer_resnet50, fuse_statis) {
  AnalysisConfig cfg;
  SetConfig(&cfg);
  int num_ops;
  auto predictor = CreatePaddlePredictor<AnalysisConfig>(cfg);
  auto fuse_statis = GetFuseStatis(
      static_cast<AnalysisPredictor *>(predictor.get()), &num_ops);
  ASSERT_TRUE(fuse_statis.count("fc_fuse"));
  EXPECT_EQ(fuse_statis.at("fc_fuse"), 1);
}

// Compare result of NativeConfig and AnalysisConfig
void compare(bool use_mkldnn = false) {
  AnalysisConfig cfg;
  SetConfig(&cfg);
  cfg._use_mkldnn = use_mkldnn;

  std::vector<std::vector<PaddleTensor>> input_slots_all;
  SetInput(&input_slots_all);
  CompareNativeAndAnalysis(cfg, input_slots_all);
}

TEST(Analyzer_resnet50, compare) { compare(); }
#ifdef PADDLE_WITH_MKLDNN
TEST(Analyzer_resnet50, compare_mkldnn) { compare(true /* use_mkldnn */); }
#endif

}  // namespace analysis
}  // namespace inference
}  // namespace paddle
<|endoftext|>


<commit_before>/*
Copyright (c) 2009 Sony Pictures Imageworks, et al.
All Rights Reserved.

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

#include <cmath>

#include "oslops.h"
#include "oslexec_pvt.h"

#ifdef OSL_NAMESPACE
namespace OSL_NAMESPACE {
#endif

namespace OSL {
namespace pvt {

class HairDiffuseClosure : public BSDFClosure {
    Vec3 m_T;
public:
    CLOSURE_CTOR (HairDiffuseClosure) : BSDFClosure(Both, Labels::DIFFUSE)
    {
        CLOSURE_FETCH_ARG (m_T, 1);
    }

    void print_on (std::ostream &out) const
    {
        out << "hair_diffuse ((" << m_T[0] << ", " << m_T[1] << ", " << m_T[2] << "))";
    }

    Color3 eval_reflect (const Vec3 &omega_out, const Vec3 &omega_in, float& pdf) const
    {
        float cos_a = m_T.dot(omega_in);
        float bsdf = sqrtf(std::max(1 - cos_a*cos_a, 0.0f)) * (float) (M_1_PI * M_1_PI);
        pdf = (float) 1 / (4 * M_PI);
        return Color3 (bsdf, bsdf, bsdf);
    }

    Color3 eval_transmit (const Vec3 &omega_out, const Vec3 &omega_in, float& pdf) const
    {
       return eval_reflect(omega_out, omega_in, pdf);
    }

    ustring sample (const Vec3 &Ng,
                 const Vec3 &omega_out, const Vec3 &domega_out_dx, const Vec3 &domega_out_dy,
                 float randu, float randv,
                 Vec3 &omega_in, Vec3 &domega_in_dx, Vec3 &domega_in_dy,
                 float &pdf, Color3 &eval) const
    {
        float Z = 1.0f - randu * 2.0f;
        float sinTheta = sqrtf(1.0 - Z*Z);
        float X = cosf(2*M_PI*randv) * sinTheta;
        float Y = sinf(2*M_PI*randv) * sinTheta;
        Vec3 T, B;
        make_orthonormals (m_T, T, B);
        omega_in = X * T + Y * B + Z * m_T;
        pdf = (float) 1 / (4 * M_PI);

        sinTheta *= (float) (M_1_PI * M_1_PI);
        eval.setValue(sinTheta, sinTheta, sinTheta);

        if (Ng.dot(omega_in) > 0.0f)
            return Labels::REFLECT;
        else
            return Labels::TRANSMIT;
    }
};

class HairSpecularClosure : public BSDFClosure {
    Vec3 m_T;
    float m_offset, m_cos_off, m_sin_off;
    float m_exp;
public:
    CLOSURE_CTOR (HairSpecularClosure) : BSDFClosure(Both, Labels::GLOSSY)
    {
        float roughness;
        // Tangent vector
        CLOSURE_FETCH_ARG (m_T, 1);
        // specular offset
        CLOSURE_FETCH_ARG (m_offset, 2);
        // roughness for the specular as used in spi shaders
        CLOSURE_FETCH_ARG (roughness, 3);
        // copying the exponente they were using before
        m_exp = roughness > std::numeric_limits<float>::min() ? roughness : std::numeric_limits<float>::min();
        m_exp = 4.0f / m_exp;
        m_cos_off = cosf(m_offset);
        m_sin_off = sinf(m_offset);
    }

    void print_on (std::ostream &out) const
    {
        out << "hair_specular ((" << m_T[0] << ", " << m_T[1] << ", " << m_T[2] << "), " << m_offset << ")";
    }

    Color3 eval_reflect (const Vec3 &omega_out, const Vec3 &omega_in, float& pdf) const
    {
        //float angle_i = acosf(m_T.dot(omega_in));
        //float angle_o = M_PI - (acosf(m_T.dot(omega_out)) + m_offset);
        //float cos_diff = cosf(angle_i - angle_o);
        //
        // Optimized version of the above commented code
        float cos_i = m_T.dot(omega_in);
        float cos_o = m_T.dot(omega_out);
        float sin_i = sqrtf (std::max (1 - cos_i*cos_i, 0.0f));
        float sin_o = sqrtf (std::max (1 - cos_o*cos_o, 0.0f));
        float cos_diff = sin_i * sin_o * m_cos_off +
                         sin_i * cos_o * m_sin_off +
                         cos_i * sin_o * m_sin_off -
                         cos_i * cos_o * m_cos_off;
        // TODO: normalization? ha!
        float bsdf = cos_diff > 0.0f ? powf(cos_diff, m_exp) : 0.0f;

        pdf = 0.0f;
        return Color3 (bsdf, bsdf, bsdf);
    }

    Color3 eval_transmit (const Vec3 &omega_out, const Vec3 &omega_in, float& pdf) const
    {
       return eval_reflect(omega_out, omega_in, pdf);
    }

    ustring sample (const Vec3 &Ng,
                 const Vec3 &omega_out, const Vec3 &domega_out_dx, const Vec3 &domega_out_dy,
                 float randu, float randv,
                 Vec3 &omega_in, Vec3 &domega_in_dx, Vec3 &domega_in_dy,
                 float &pdf, Color3 &eval) const
    {
        // TODO: we don't know how to do this, sorry
        pdf = 0.0f;
        return Labels::NONE;
    }
};

DECLOP (OP_hair_diffuse)
{
    closure_op_guts<HairDiffuseClosure, 2> (exec, nargs, args,
            runflags, beginpoint, endpoint);
}

DECLOP (OP_hair_specular)
{
    closure_op_guts<HairSpecularClosure, 4> (exec, nargs, args,
            runflags, beginpoint, endpoint);
}

}; // namespace pvt
}; // namespace OSL
#ifdef OSL_NAMESPACE
}; // end namespace OSL_NAMESPACE
#endif
<commit_msg>Changed hair_specular to take phong like exponent<commit_after>/*
Copyright (c) 2009 Sony Pictures Imageworks, et al.
All Rights Reserved.

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

#include <cmath>

#include "oslops.h"
#include "oslexec_pvt.h"

#ifdef OSL_NAMESPACE
namespace OSL_NAMESPACE {
#endif

namespace OSL {
namespace pvt {

class HairDiffuseClosure : public BSDFClosure {
    Vec3 m_T;
public:
    CLOSURE_CTOR (HairDiffuseClosure) : BSDFClosure(Both, Labels::DIFFUSE)
    {
        CLOSURE_FETCH_ARG (m_T, 1);
    }

    void print_on (std::ostream &out) const
    {
        out << "hair_diffuse ((" << m_T[0] << ", " << m_T[1] << ", " << m_T[2] << "))";
    }

    Color3 eval_reflect (const Vec3 &omega_out, const Vec3 &omega_in, float& pdf) const
    {
        float cos_a = m_T.dot(omega_in);
        float bsdf = sqrtf(std::max(1 - cos_a*cos_a, 0.0f)) * (float) (M_1_PI * M_1_PI);
        pdf = (float) 1 / (4 * M_PI);
        return Color3 (bsdf, bsdf, bsdf);
    }

    Color3 eval_transmit (const Vec3 &omega_out, const Vec3 &omega_in, float& pdf) const
    {
       return eval_reflect(omega_out, omega_in, pdf);
    }

    ustring sample (const Vec3 &Ng,
                 const Vec3 &omega_out, const Vec3 &domega_out_dx, const Vec3 &domega_out_dy,
                 float randu, float randv,
                 Vec3 &omega_in, Vec3 &domega_in_dx, Vec3 &domega_in_dy,
                 float &pdf, Color3 &eval) const
    {
        float Z = 1.0f - randu * 2.0f;
        float sinTheta = sqrtf(1.0 - Z*Z);
        float X = cosf(2*M_PI*randv) * sinTheta;
        float Y = sinf(2*M_PI*randv) * sinTheta;
        Vec3 T, B;
        make_orthonormals (m_T, T, B);
        omega_in = X * T + Y * B + Z * m_T;
        pdf = (float) 1 / (4 * M_PI);

        sinTheta *= (float) (M_1_PI * M_1_PI);
        eval.setValue(sinTheta, sinTheta, sinTheta);

        if (Ng.dot(omega_in) > 0.0f)
            return Labels::REFLECT;
        else
            return Labels::TRANSMIT;
    }
};

class HairSpecularClosure : public BSDFClosure {
    Vec3 m_T;
    float m_offset, m_cos_off, m_sin_off;
    float m_exp;
public:
    CLOSURE_CTOR (HairSpecularClosure) : BSDFClosure(Both, Labels::GLOSSY)
    {
        // Tangent vector
        CLOSURE_FETCH_ARG (m_T, 1);
        // specular offset
        CLOSURE_FETCH_ARG (m_offset, 2);
        // roughness for the specular as used in spi shaders
        CLOSURE_FETCH_ARG (m_exp, 3);
        m_cos_off = cosf(m_offset);
        m_sin_off = sinf(m_offset);
    }

    void print_on (std::ostream &out) const
    {
        out << "hair_specular ((" << m_T[0] << ", " << m_T[1] << ", " << m_T[2] << "), " << m_offset << ")";
    }

    Color3 eval_reflect (const Vec3 &omega_out, const Vec3 &omega_in, float& pdf) const
    {
        //float angle_i = acosf(m_T.dot(omega_in));
        //float angle_o = M_PI - (acosf(m_T.dot(omega_out)) + m_offset);
        //float cos_diff = cosf(angle_i - angle_o);
        //
        // Optimized version of the above commented code
        float cos_i = m_T.dot(omega_in);
        float cos_o = m_T.dot(omega_out);
        float sin_i = sqrtf (std::max (1 - cos_i*cos_i, 0.0f));
        float sin_o = sqrtf (std::max (1 - cos_o*cos_o, 0.0f));
        float cos_diff = sin_i * sin_o * m_cos_off +
                         sin_i * cos_o * m_sin_off +
                         cos_i * sin_o * m_sin_off -
                         cos_i * cos_o * m_cos_off;
        // TODO: normalization? ha!
        float bsdf = cos_diff > 0.0f ? powf(cos_diff, m_exp) : 0.0f;

        pdf = 0.0f;
        return Color3 (bsdf, bsdf, bsdf);
    }

    Color3 eval_transmit (const Vec3 &omega_out, const Vec3 &omega_in, float& pdf) const
    {
       return eval_reflect(omega_out, omega_in, pdf);
    }

    ustring sample (const Vec3 &Ng,
                 const Vec3 &omega_out, const Vec3 &domega_out_dx, const Vec3 &domega_out_dy,
                 float randu, float randv,
                 Vec3 &omega_in, Vec3 &domega_in_dx, Vec3 &domega_in_dy,
                 float &pdf, Color3 &eval) const
    {
        // TODO: we don't know how to do this, sorry
        pdf = 0.0f;
        return Labels::NONE;
    }
};

DECLOP (OP_hair_diffuse)
{
    closure_op_guts<HairDiffuseClosure, 2> (exec, nargs, args,
            runflags, beginpoint, endpoint);
}

DECLOP (OP_hair_specular)
{
    closure_op_guts<HairSpecularClosure, 4> (exec, nargs, args,
            runflags, beginpoint, endpoint);
}

}; // namespace pvt
}; // namespace OSL
#ifdef OSL_NAMESPACE
}; // end namespace OSL_NAMESPACE
#endif
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkDynamicLoader.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkDynamicLoader.h"

#include "vtkDebugLeaks.h"

vtkCxxRevisionMacro(vtkDynamicLoader, "1.24");

//-----------------------------------------------------------------------------
// Needed when we don't use the vtkStandardNewMacro.
vtkInstantiatorNewMacro(vtkDynamicLoader);

//-----------------------------------------------------------------------------
vtkDynamicLoader* vtkDynamicLoader::New()
{
#ifdef VTK_DEBUG_LEAKS
  vtkDebugLeaks::ConstructClass("vtkDynamicLoader");
#endif
  return new vtkDynamicLoader;
}

// ----------------------------------------------------------------------------
vtkLibHandle vtkDynamicLoader::OpenLibrary(const char* libname )
{
  return vtksys::DynamicLoader::OpenLibrary(libname);
}

// ----------------------------------------------------------------------------
int vtkDynamicLoader::CloseLibrary(vtkLibHandle lib)
{
  return vtksys::DynamicLoader::CloseLibrary(lib);
}

// ----------------------------------------------------------------------------
//vtkSymbolPointer
void*
vtkDynamicLoader::GetSymbolAddress(vtkLibHandle lib, const char* sym)
{
  return reinterpret_cast<void*>(vtksys::DynamicLoader::GetSymbolAddress(lib, sym));
}

// ----------------------------------------------------------------------------
const char* vtkDynamicLoader::LibPrefix()
{
  return vtksys::DynamicLoader::LibPrefix();
}

// ----------------------------------------------------------------------------
const char* vtkDynamicLoader::LibExtension()
{
  return vtksys::DynamicLoader::LibExtension();
}

// ----------------------------------------------------------------------------
const char* vtkDynamicLoader::LastError()
{
  return vtksys::DynamicLoader::LastError();
}

<commit_msg>COMP:Even a reinterpret_cast does not work on this one with some gcc. Revert it back to C-style cast.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkDynamicLoader.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkDynamicLoader.h"

#include "vtkDebugLeaks.h"

vtkCxxRevisionMacro(vtkDynamicLoader, "1.25");

//-----------------------------------------------------------------------------
// Needed when we don't use the vtkStandardNewMacro.
vtkInstantiatorNewMacro(vtkDynamicLoader);

//-----------------------------------------------------------------------------
vtkDynamicLoader* vtkDynamicLoader::New()
{
#ifdef VTK_DEBUG_LEAKS
  vtkDebugLeaks::ConstructClass("vtkDynamicLoader");
#endif
  return new vtkDynamicLoader;
}

// ----------------------------------------------------------------------------
vtkLibHandle vtkDynamicLoader::OpenLibrary(const char* libname )
{
  return vtksys::DynamicLoader::OpenLibrary(libname);
}

// ----------------------------------------------------------------------------
int vtkDynamicLoader::CloseLibrary(vtkLibHandle lib)
{
  return vtksys::DynamicLoader::CloseLibrary(lib);
}

// ----------------------------------------------------------------------------
//vtkSymbolPointer
void*
vtkDynamicLoader::GetSymbolAddress(vtkLibHandle lib, const char* sym)
{
  return (void *)(vtksys::DynamicLoader::GetSymbolAddress(lib, sym));
}

// ----------------------------------------------------------------------------
const char* vtkDynamicLoader::LibPrefix()
{
  return vtksys::DynamicLoader::LibPrefix();
}

// ----------------------------------------------------------------------------
const char* vtkDynamicLoader::LibExtension()
{
  return vtksys::DynamicLoader::LibExtension();
}

// ----------------------------------------------------------------------------
const char* vtkDynamicLoader::LastError()
{
  return vtksys::DynamicLoader::LastError();
}

<|endoftext|>


<commit_before>#include <rai/node/openclwork.hpp>

#include <dlfcn.h>

namespace
{
class opencl_initializer
{
public:
	opencl_initializer ()
	{
		opencl_library = dlopen ("libOpenCL.so", RTLD_NOW);
		if (opencl_library != nullptr)
		{
			clGetPlatformIDs = reinterpret_cast <decltype (clGetPlatformIDs)> (dlsym (opencl_library, "clGetPlatformIDs"));
		}
	}
	~opencl_initializer ()
	{
		dlclose (opencl_library);
	}
	void * opencl_library;
	cl_int (* clGetPlatformIDs) (cl_uint, cl_platform_id *, cl_uint *);
	cl_int (* clGetDeviceIDs) (cl_platform_id, cl_device_type, cl_uint, cl_device_id *, cl_uint *);
	static opencl_initializer initializer;
};
}

opencl_initializer opencl_initializer::initializer;

cl_int clGetPlatformIDs (cl_uint num_entries, cl_platform_id * platforms, cl_uint * num_platforms)
{
	cl_int result;
	if (opencl_initializer::initializer.opencl_library != nullptr)
	{
		result = opencl_initializer::initializer.clGetPlatformIDs (num_entries, platforms, num_platforms);
	}
	else
	{
		result = CL_SUCCESS;
		*num_platforms = 0;
	}
	return result;
}

cl_int clGetDeviceIDs (cl_platform_id platform, cl_device_type device_type, cl_uint num_entries, cl_device_id * devices, cl_uint * num_devices)
{
	return clGetDeviceIDs (platform, device_type, num_entries, devices, num_devices);
}
<commit_msg>Adding needed opencl wrappers.<commit_after>#include <rai/node/openclwork.hpp>

#include <dlfcn.h>

namespace
{
class opencl_initializer
{
public:
	opencl_initializer ()
	{
		opencl_library = dlopen ("libOpenCL.so", RTLD_NOW);
		if (opencl_library != nullptr)
		{
			clGetPlatformIDs = reinterpret_cast <decltype (clGetPlatformIDs)> (dlsym (opencl_library, "clGetPlatformIDs"));
		}
	}
	~opencl_initializer ()
	{
		dlclose (opencl_library);
	}
	void * opencl_library;
	cl_int (* clGetPlatformIDs) (cl_uint, cl_platform_id *, cl_uint *);
	cl_int (* clGetPlatformInfo) (cl_platform_id, cl_platform_info, size_t, void *, size_t *);
	cl_int (* clGetDeviceIDs) (cl_platform_id, cl_device_type, cl_uint, cl_device_id *, cl_uint *);
	cl_int (* clGetDeviceInfo) (cl_device_id, cl_device_info, size_t, void *, size_t *);
	cl_context (* clCreateContext) (cl_context_properties const *, cl_uint, cl_device_id const *, void (*)(const char *, const void *, size_t, void *), void *, cl_int *);
	cl_command_queue (* clCreateCommandQueue) (cl_context, cl_device_id, cl_command_queue_properties, cl_int *);
	cl_mem (* clCreateBuffer) (cl_context, cl_mem_flags, size_t, void *, cl_int *);
	cl_program (* clCreateProgramWithSource) (cl_context, cl_uint, char const **, size_t const *, cl_int *);
	cl_int (* clBuildProgram) (cl_program, cl_uint, cl_device_id const *, char const *, void (*)(cl_program, void *), void *);
	cl_kernel (* clCreateKernel) (cl_program, char const *, cl_int *);
	cl_int (* clSetKernelArg) (cl_kernel, cl_uint, size_t, void const *);
	cl_int (* clReleaseKernel) (cl_kernel);
	cl_int (* clReleaseProgram) (cl_program);
	cl_int (* clReleaseContext) (cl_context);
	cl_int (* clEnqueueWriteBuffer) (cl_command_queue, cl_mem, cl_bool, size_t, size_t, void const *, cl_uint, cl_event const *, cl_event *);
	cl_int (* clEnqueueNDRangeKernel) (cl_command_queue, cl_kernel, cl_uint, size_t const *, size_t const *, size_t const *, cl_uint, cl_event const *, cl_event *);
	cl_int (* clEnqueueReadBuffer) (cl_command_queue, cl_mem, cl_bool, size_t, size_t, void *, cl_uint, cl_event const *, cl_event *);
	cl_int (* clFinish) (cl_command_queue);
	static opencl_initializer initializer;
};
}

opencl_initializer opencl_initializer::initializer;

cl_int clGetPlatformIDs (cl_uint num_entries, cl_platform_id * platforms, cl_uint * num_platforms)
{
	cl_int result;
	if (opencl_initializer::initializer.opencl_library != nullptr)
	{
		result = opencl_initializer::initializer.clGetPlatformIDs (num_entries, platforms, num_platforms);
	}
	else
	{
		result = CL_SUCCESS;
		*num_platforms = 0;
	}
	return result;
}

cl_int clGetPlatformInfo (cl_platform_id platform, cl_platform_info param_name, size_t param_value_size, void * param_value, size_t * param_value_size_ret)
{
	return opencl_initializer::initializer::clGetPlatformInfo (platform, param_name, param_value_size, param_value, param_value_size_ret);
}

cl_int clGetDeviceIDs (cl_platform_id platform, cl_device_type device_type, cl_uint num_entries, cl_device_id * devices, cl_uint * num_devices)
{
	return opencl_initializer::initializer::clGetDeviceIDs (platform, device_type, num_entries, devices, num_devices);
}

cl_int clGetDeviceInfo (cl_device_id device, cl_device_info param_name, size_t param_value_size, void * param_value, size_t * param_value_size_ret)
{
	return opencl_initializer::initializer::clGetDeviceInfo (device, param_name, param_value_size, param_value, param_value_size_ret);
}

cl_context clCreateContext (cl_context_properties const * properties, cl_uint num_devices, cl_device_id const * devices, void (* pfn_notify)(const char *, const void *, size_t, void *), void * user_data, cl_int * errcode_ret)
{
	return opencl_initializer::initializer::clCreateContext (properties, num_devices, devices, pfn_notify, user_data, errorcode_ret);
}

cl_command_queue clCreateCommandQueue (cl_context context, cl_device_id device, cl_command_queue_properties properties, cl_int * errcode_ret)
{
	return opencl_initializer::initializer::clCreateCommandQueue (context, device, properties, errorcode_ret);
}

cl_mem clCreateBuffer (cl_context context, cl_mem_flags flags, size_t size, void * host_ptr, cl_int * errcode_ret)
{
	return opencl_initializer::initializer::clCreateBuffer (context, flags, size, host_ptr, errorcode_ret);
}

cl_program clCreateProgramWithSource (cl_context context, cl_uint count, char const ** strings, size_t const * lengths, cl_int * errcode_ret)
{
	return opencl_initializer::initializer::clCreateProgramWithSource (context, count, strings, lengths, errorcode_ret);
}

cl_int clBuildProgram (cl_program program, cl_uint num_devices, cl_device_id const * device_list, char const * options, void (*pfn_notify) (cl_program , void *), void * user_data)
{
	return opencl_initializer::initializer::clBuildProgram (program, num_devices, device_list, options, pfn_notify, user_data);
}

cl_kernel clCreateKernel (cl_program program, char const * kernel_name, cl_int * errcode_ret)
{
	return opencl_initializer::initializer::clCreateKernel (program, kernel_name, errorcode_ret);
}

cl_int clSetKernelArg (cl_kernel kernel, cl_uint arg_index, size_t arg_size, void const * arg_value)
{
	return opencl_initializer::initializer::clSetKernelArg (kernel, arg_index, arg_size, arg_value);
}

cl_int clReleaseKernel (cl_kernel kernel)
{
	return opencl_initializer::initializer::clReleaseKernel (kernel);
}

cl_int clReleaseProgram (cl_program program)
{
	return opencl_initializer::initializer::clReleaseProgram (program);
}

cl_int clReleaseContext (cl_context context)
{
	return opencl_initializer::initializer::clReleaseContext (context);
}

cl_int clEnqueueWriteBuffer (cl_command_queue command_queue, cl_mem buffer, cl_bool blocking_write, size_t offset, size_t size, void const * ptr, cl_uint num_events_in_wait_list, cl_event const * event_wait_list,cl_event * event)
{
	return opencl_initializer::initializer::clEnqueueWriteBuffer (command_queue, buffer, blocking_write, offset, size, ptr, num_events_in_wait_list, event_wait_list, event);
}

cl_int clEnqueueNDRangeKernel (cl_command_queue command_queue, cl_kernel kernel, cl_uint work_dim, size_t const * global_work_offset, size_t const * global_work_size, size_t const * local_work_size, cl_uint num_events_in_wait_list, cl_event const * event_wait_list, cl_event * event)
{
	return opencl_initializer::initializer::clEnqueueNDRangeKernel (command_queue, kernel, work_dim, global_work_offset, global_work_size, local_work_size, num_events_in_wait_list, event_wait_list, event);
}

cl_int clEnqueueReadBuffer (cl_command_queue command_queue, cl_mem buffer, cl_bool blocking_read, size_t offset, size_t size, void * ptr, cl_uint num_events_in_wait_list, cl_event const * event_wait_list, cl_event *event)
{
	return opencl_initializer::initializer::clEnqueueReadBuffer (command_queue, buffer, blocking_read, offset, size, ptr, num_events_in_wait_list, event_wait_list, event);
}

cl_int clFinish (cl_command_queue command_queue)
{
	return opencl_initializer::initializer::clFinish (command_queue);
}<|endoftext|>