text:
/*************************************************************************/
/*  physics_joint.cpp                                                    */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md)    */
/*                                                                       */
/* 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 "physics_joint.h"

void Joint::_update_joint(bool p_only_free) {

	if (joint.is_valid()) {
		if (ba.is_valid() && bb.is_valid())
			PhysicsServer::get_singleton()->body_remove_collision_exception(ba, bb);

		PhysicsServer::get_singleton()->free(joint);
		joint = RID();
		ba = RID();
		bb = RID();
	}

	if (p_only_free || !is_inside_tree())
		return;

	Node *node_a = has_node(get_node_a()) ? get_node(get_node_a()) : (Node *)NULL;
	Node *node_b = has_node(get_node_b()) ? get_node(get_node_b()) : (Node *)NULL;

	if (!node_a || !node_b)
		return;

	PhysicsBody *body_a = Object::cast_to<PhysicsBody>(node_a);
	PhysicsBody *body_b = Object::cast_to<PhysicsBody>(node_b);

	if (!body_a || !body_b)
		return;

	if (!body_a) {
		SWAP(body_a, body_b);
	}

	joint = _configure_joint(body_a, body_b);

	if (!joint.is_valid())
		return;

	PhysicsServer::get_singleton()->joint_set_solver_priority(joint, solver_priority);

	ba = body_a->get_rid();
	bb = body_b->get_rid();

	if (exclude_from_collision)
		PhysicsServer::get_singleton()->body_add_collision_exception(body_a->get_rid(), body_b->get_rid());
}

void Joint::set_node_a(const NodePath &p_node_a) {

	if (a == p_node_a)
		return;

	a = p_node_a;
	_update_joint();
}

NodePath Joint::get_node_a() const {

	return a;
}

void Joint::set_node_b(const NodePath &p_node_b) {

	if (b == p_node_b)
		return;
	b = p_node_b;
	_update_joint();
}
NodePath Joint::get_node_b() const {

	return b;
}

void Joint::set_solver_priority(int p_priority) {

	solver_priority = p_priority;
	if (joint.is_valid())
		PhysicsServer::get_singleton()->joint_set_solver_priority(joint, solver_priority);
}

int Joint::get_solver_priority() const {

	return solver_priority;
}

void Joint::_notification(int p_what) {

	switch (p_what) {

		case NOTIFICATION_READY: {
			_update_joint();
		} break;
		case NOTIFICATION_EXIT_TREE: {
			if (joint.is_valid()) {
				_update_joint(true);
			}
		} break;
	}
}

void Joint::set_exclude_nodes_from_collision(bool p_enable) {

	if (exclude_from_collision == p_enable)
		return;
	exclude_from_collision = p_enable;
	_update_joint();
}

bool Joint::get_exclude_nodes_from_collision() const {

	return exclude_from_collision;
}

void Joint::_bind_methods() {

	ClassDB::bind_method(D_METHOD("set_node_a", "node"), &Joint::set_node_a);
	ClassDB::bind_method(D_METHOD("get_node_a"), &Joint::get_node_a);

	ClassDB::bind_method(D_METHOD("set_node_b", "node"), &Joint::set_node_b);
	ClassDB::bind_method(D_METHOD("get_node_b"), &Joint::get_node_b);

	ClassDB::bind_method(D_METHOD("set_solver_priority", "priority"), &Joint::set_solver_priority);
	ClassDB::bind_method(D_METHOD("get_solver_priority"), &Joint::get_solver_priority);

	ClassDB::bind_method(D_METHOD("set_exclude_nodes_from_collision", "enable"), &Joint::set_exclude_nodes_from_collision);
	ClassDB::bind_method(D_METHOD("get_exclude_nodes_from_collision"), &Joint::get_exclude_nodes_from_collision);

	ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "nodes/node_a"), "set_node_a", "get_node_a");
	ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "nodes/node_b"), "set_node_b", "get_node_b");
	ADD_PROPERTY(PropertyInfo(Variant::INT, "solver/priority", PROPERTY_HINT_RANGE, "1,8,1"), "set_solver_priority", "get_solver_priority");

	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collision/exclude_nodes"), "set_exclude_nodes_from_collision", "get_exclude_nodes_from_collision");
}

Joint::Joint() {

	exclude_from_collision = true;
	solver_priority = 1;
	set_notify_transform(true);
}

///////////////////////////////////

void PinJoint::_bind_methods() {

	ClassDB::bind_method(D_METHOD("set_param", "param", "value"), &PinJoint::set_param);
	ClassDB::bind_method(D_METHOD("get_param", "param"), &PinJoint::get_param);

	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "params/bias", PROPERTY_HINT_RANGE, "0.01,0.99,0.01"), "set_param", "get_param", PARAM_BIAS);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "params/damping", PROPERTY_HINT_RANGE, "0.01,8.0,0.01"), "set_param", "get_param", PARAM_DAMPING);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "params/impulse_clamp", PROPERTY_HINT_RANGE, "0.0,64.0,0.01"), "set_param", "get_param", PARAM_IMPULSE_CLAMP);

	BIND_ENUM_CONSTANT(PARAM_BIAS);
	BIND_ENUM_CONSTANT(PARAM_DAMPING);
	BIND_ENUM_CONSTANT(PARAM_IMPULSE_CLAMP);
}

void PinJoint::set_param(Param p_param, float p_value) {

	ERR_FAIL_INDEX(p_param, 3);
	params[p_param] = p_value;
	if (get_joint().is_valid())
		PhysicsServer::get_singleton()->pin_joint_set_param(get_joint(), PhysicsServer::PinJointParam(p_param), p_value);
}
float PinJoint::get_param(Param p_param) const {

	ERR_FAIL_INDEX_V(p_param, 3, 0);
	return params[p_param];
}

RID PinJoint::_configure_joint(PhysicsBody *body_a, PhysicsBody *body_b) {

	Vector3 pinpos = get_global_transform().origin;
	Vector3 local_a = body_a->get_global_transform().affine_inverse().xform(pinpos);
	Vector3 local_b;

	if (body_b)
		local_b = body_b->get_global_transform().affine_inverse().xform(pinpos);
	else
		local_b = pinpos;

	RID j = PhysicsServer::get_singleton()->joint_create_pin(body_a->get_rid(), local_a, body_b ? body_b->get_rid() : RID(), local_b);
	for (int i = 0; i < 3; i++) {
		PhysicsServer::get_singleton()->pin_joint_set_param(j, PhysicsServer::PinJointParam(i), params[i]);
	}
	return j;
}

PinJoint::PinJoint() {

	params[PARAM_BIAS] = 0.3;
	params[PARAM_DAMPING] = 1;
	params[PARAM_IMPULSE_CLAMP] = 0;
}

/////////////////////////////////////////////////

///////////////////////////////////

void HingeJoint::_set_upper_limit(float p_limit) {

	set_param(PARAM_LIMIT_UPPER, Math::deg2rad(p_limit));
}

float HingeJoint::_get_upper_limit() const {

	return Math::rad2deg(get_param(PARAM_LIMIT_UPPER));
}

void HingeJoint::_set_lower_limit(float p_limit) {

	set_param(PARAM_LIMIT_LOWER, Math::deg2rad(p_limit));
}

float HingeJoint::_get_lower_limit() const {

	return Math::rad2deg(get_param(PARAM_LIMIT_LOWER));
}

void HingeJoint::_bind_methods() {

	ClassDB::bind_method(D_METHOD("set_param", "param", "value"), &HingeJoint::set_param);
	ClassDB::bind_method(D_METHOD("get_param", "param"), &HingeJoint::get_param);

	ClassDB::bind_method(D_METHOD("set_flag", "flag", "enabled"), &HingeJoint::set_flag);
	ClassDB::bind_method(D_METHOD("get_flag", "flag"), &HingeJoint::get_flag);

	ClassDB::bind_method(D_METHOD("_set_upper_limit", "upper_limit"), &HingeJoint::_set_upper_limit);
	ClassDB::bind_method(D_METHOD("_get_upper_limit"), &HingeJoint::_get_upper_limit);

	ClassDB::bind_method(D_METHOD("_set_lower_limit", "lower_limit"), &HingeJoint::_set_lower_limit);
	ClassDB::bind_method(D_METHOD("_get_lower_limit"), &HingeJoint::_get_lower_limit);

	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "params/bias", PROPERTY_HINT_RANGE, "0.01,0.99,0.01"), "set_param", "get_param", PARAM_BIAS);

	ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "angular_limit/enable"), "set_flag", "get_flag", FLAG_USE_LIMIT);
	ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_limit/upper", PROPERTY_HINT_RANGE, "-180,180,0.1"), "_set_upper_limit", "_get_upper_limit");
	ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_limit/lower", PROPERTY_HINT_RANGE, "-180,180,0.1"), "_set_lower_limit", "_get_lower_limit");
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit/bias", PROPERTY_HINT_RANGE, "0.01,0.99,0.01"), "set_param", "get_param", PARAM_LIMIT_BIAS);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit/softness", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param", "get_param", PARAM_LIMIT_SOFTNESS);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit/relaxation", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param", "get_param", PARAM_LIMIT_RELAXATION);

	ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "motor/enable"), "set_flag", "get_flag", FLAG_ENABLE_MOTOR);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "motor/target_velocity", PROPERTY_HINT_RANGE, "0.01,4096,0.01"), "set_param", "get_param", PARAM_MOTOR_TARGET_VELOCITY);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "motor/max_impulse", PROPERTY_HINT_RANGE, "0.01,1024,0.01"), "set_param", "get_param", PARAM_MOTOR_MAX_IMPULSE);

	BIND_ENUM_CONSTANT(PARAM_BIAS);
	BIND_ENUM_CONSTANT(PARAM_LIMIT_UPPER);
	BIND_ENUM_CONSTANT(PARAM_LIMIT_LOWER);
	BIND_ENUM_CONSTANT(PARAM_LIMIT_BIAS);
	BIND_ENUM_CONSTANT(PARAM_LIMIT_SOFTNESS);
	BIND_ENUM_CONSTANT(PARAM_LIMIT_RELAXATION);
	BIND_ENUM_CONSTANT(PARAM_MOTOR_TARGET_VELOCITY);
	BIND_ENUM_CONSTANT(PARAM_MOTOR_MAX_IMPULSE);
	BIND_ENUM_CONSTANT(PARAM_MAX);

	BIND_ENUM_CONSTANT(FLAG_USE_LIMIT);
	BIND_ENUM_CONSTANT(FLAG_ENABLE_MOTOR);
	BIND_ENUM_CONSTANT(FLAG_MAX);
}

void HingeJoint::set_param(Param p_param, float p_value) {

	ERR_FAIL_INDEX(p_param, PARAM_MAX);
	params[p_param] = p_value;
	if (get_joint().is_valid())
		PhysicsServer::get_singleton()->hinge_joint_set_param(get_joint(), PhysicsServer::HingeJointParam(p_param), p_value);

	update_gizmo();
}
float HingeJoint::get_param(Param p_param) const {

	ERR_FAIL_INDEX_V(p_param, PARAM_MAX, 0);
	return params[p_param];
}

void HingeJoint::set_flag(Flag p_flag, bool p_value) {

	ERR_FAIL_INDEX(p_flag, FLAG_MAX);
	flags[p_flag] = p_value;
	if (get_joint().is_valid())
		PhysicsServer::get_singleton()->hinge_joint_set_flag(get_joint(), PhysicsServer::HingeJointFlag(p_flag), p_value);

	update_gizmo();
}
bool HingeJoint::get_flag(Flag p_flag) const {

	ERR_FAIL_INDEX_V(p_flag, FLAG_MAX, false);
	return flags[p_flag];
}

RID HingeJoint::_configure_joint(PhysicsBody *body_a, PhysicsBody *body_b) {

	Transform gt = get_global_transform();
	Transform ainv = body_a->get_global_transform().affine_inverse();

	Transform local_a = ainv * gt;
	local_a.orthonormalize();
	Transform local_b = gt;

	if (body_b) {
		Transform binv = body_b->get_global_transform().affine_inverse();
		local_b = binv * gt;
	}

	local_b.orthonormalize();

	RID j = PhysicsServer::get_singleton()->joint_create_hinge(body_a->get_rid(), local_a, body_b ? body_b->get_rid() : RID(), local_b);
	for (int i = 0; i < PARAM_MAX; i++) {
		PhysicsServer::get_singleton()->hinge_joint_set_param(j, PhysicsServer::HingeJointParam(i), params[i]);
	}
	for (int i = 0; i < FLAG_MAX; i++) {
		set_flag(Flag(i), flags[i]);
		PhysicsServer::get_singleton()->hinge_joint_set_flag(j, PhysicsServer::HingeJointFlag(i), flags[i]);
	}
	return j;
}

HingeJoint::HingeJoint() {

	params[PARAM_BIAS] = 0.3;
	params[PARAM_LIMIT_UPPER] = Math_PI * 0.5;
	params[PARAM_LIMIT_LOWER] = -Math_PI * 0.5;
	params[PARAM_LIMIT_BIAS] = 0.3;
	params[PARAM_LIMIT_SOFTNESS] = 0.9;
	params[PARAM_LIMIT_RELAXATION] = 1.0;
	params[PARAM_MOTOR_TARGET_VELOCITY] = 1;
	params[PARAM_MOTOR_MAX_IMPULSE] = 1;

	flags[FLAG_USE_LIMIT] = false;
	flags[FLAG_ENABLE_MOTOR] = false;
}

/////////////////////////////////////////////////

//////////////////////////////////

void SliderJoint::_set_upper_limit_angular(float p_limit_angular) {

	set_param(PARAM_ANGULAR_LIMIT_UPPER, Math::deg2rad(p_limit_angular));
}

float SliderJoint::_get_upper_limit_angular() const {

	return Math::rad2deg(get_param(PARAM_ANGULAR_LIMIT_UPPER));
}

void SliderJoint::_set_lower_limit_angular(float p_limit_angular) {

	set_param(PARAM_ANGULAR_LIMIT_LOWER, Math::deg2rad(p_limit_angular));
}

float SliderJoint::_get_lower_limit_angular() const {

	return Math::rad2deg(get_param(PARAM_ANGULAR_LIMIT_LOWER));
}

void SliderJoint::_bind_methods() {

	ClassDB::bind_method(D_METHOD("set_param", "param", "value"), &SliderJoint::set_param);
	ClassDB::bind_method(D_METHOD("get_param", "param"), &SliderJoint::get_param);

	ClassDB::bind_method(D_METHOD("_set_upper_limit_angular", "upper_limit_angular"), &SliderJoint::_set_upper_limit_angular);
	ClassDB::bind_method(D_METHOD("_get_upper_limit_angular"), &SliderJoint::_get_upper_limit_angular);

	ClassDB::bind_method(D_METHOD("_set_lower_limit_angular", "lower_limit_angular"), &SliderJoint::_set_lower_limit_angular);
	ClassDB::bind_method(D_METHOD("_get_lower_limit_angular"), &SliderJoint::_get_lower_limit_angular);

	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit/upper_distance", PROPERTY_HINT_RANGE, "-1024,1024,0.01"), "set_param", "get_param", PARAM_LINEAR_LIMIT_UPPER);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit/lower_distance", PROPERTY_HINT_RANGE, "-1024,1024,0.01"), "set_param", "get_param", PARAM_LINEAR_LIMIT_LOWER);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit/softness", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_LIMIT_SOFTNESS);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit/restitution", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_LIMIT_RESTITUTION);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit/damping", PROPERTY_HINT_RANGE, "0,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_LIMIT_DAMPING);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_motion/softness", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_MOTION_SOFTNESS);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_motion/restitution", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_MOTION_RESTITUTION);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_motion/damping", PROPERTY_HINT_RANGE, "0,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_MOTION_DAMPING);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_ortho/softness", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_ORTHOGONAL_SOFTNESS);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_ortho/restitution", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_ORTHOGONAL_RESTITUTION);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_ortho/damping", PROPERTY_HINT_RANGE, "0,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_ORTHOGONAL_DAMPING);

	ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_limit/upper_angle", PROPERTY_HINT_RANGE, "-180,180,0.1"), "_set_upper_limit_angular", "_get_upper_limit_angular");
	ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_limit/lower_angle", PROPERTY_HINT_RANGE, "-180,180,0.1"), "_set_lower_limit_angular", "_get_lower_limit_angular");
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit/softness", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_LIMIT_SOFTNESS);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit/restitution", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_LIMIT_RESTITUTION);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit/damping", PROPERTY_HINT_RANGE, "0,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_LIMIT_DAMPING);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_motion/softness", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_MOTION_SOFTNESS);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_motion/restitution", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_MOTION_RESTITUTION);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_motion/damping", PROPERTY_HINT_RANGE, "0,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_MOTION_DAMPING);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_ortho/softness", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_ORTHOGONAL_SOFTNESS);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_ortho/restitution", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_ORTHOGONAL_RESTITUTION);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_ortho/damping", PROPERTY_HINT_RANGE, "0,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_ORTHOGONAL_DAMPING);

	BIND_ENUM_CONSTANT(PARAM_LINEAR_LIMIT_UPPER);
	BIND_ENUM_CONSTANT(PARAM_LINEAR_LIMIT_LOWER);
	BIND_ENUM_CONSTANT(PARAM_LINEAR_LIMIT_SOFTNESS);
	BIND_ENUM_CONSTANT(PARAM_LINEAR_LIMIT_RESTITUTION);
	BIND_ENUM_CONSTANT(PARAM_LINEAR_LIMIT_DAMPING);
	BIND_ENUM_CONSTANT(PARAM_LINEAR_MOTION_SOFTNESS);
	BIND_ENUM_CONSTANT(PARAM_LINEAR_MOTION_RESTITUTION);
	BIND_ENUM_CONSTANT(PARAM_LINEAR_MOTION_DAMPING);
	BIND_ENUM_CONSTANT(PARAM_LINEAR_ORTHOGONAL_SOFTNESS);
	BIND_ENUM_CONSTANT(PARAM_LINEAR_ORTHOGONAL_RESTITUTION);
	BIND_ENUM_CONSTANT(PARAM_LINEAR_ORTHOGONAL_DAMPING);

	BIND_ENUM_CONSTANT(PARAM_ANGULAR_LIMIT_UPPER);
	BIND_ENUM_CONSTANT(PARAM_ANGULAR_LIMIT_LOWER);
	BIND_ENUM_CONSTANT(PARAM_ANGULAR_LIMIT_SOFTNESS);
	BIND_ENUM_CONSTANT(PARAM_ANGULAR_LIMIT_RESTITUTION);
	BIND_ENUM_CONSTANT(PARAM_ANGULAR_LIMIT_DAMPING);
	BIND_ENUM_CONSTANT(PARAM_ANGULAR_MOTION_SOFTNESS);
	BIND_ENUM_CONSTANT(PARAM_ANGULAR_MOTION_RESTITUTION);
	BIND_ENUM_CONSTANT(PARAM_ANGULAR_MOTION_DAMPING);
	BIND_ENUM_CONSTANT(PARAM_ANGULAR_ORTHOGONAL_SOFTNESS);
	BIND_ENUM_CONSTANT(PARAM_ANGULAR_ORTHOGONAL_RESTITUTION);
	BIND_ENUM_CONSTANT(PARAM_ANGULAR_ORTHOGONAL_DAMPING);

	BIND_ENUM_CONSTANT(PARAM_MAX);
}

void SliderJoint::set_param(Param p_param, float p_value) {

	ERR_FAIL_INDEX(p_param, PARAM_MAX);
	params[p_param] = p_value;
	if (get_joint().is_valid())
		PhysicsServer::get_singleton()->slider_joint_set_param(get_joint(), PhysicsServer::SliderJointParam(p_param), p_value);
	update_gizmo();
}
float SliderJoint::get_param(Param p_param) const {

	ERR_FAIL_INDEX_V(p_param, PARAM_MAX, 0);
	return params[p_param];
}

RID SliderJoint::_configure_joint(PhysicsBody *body_a, PhysicsBody *body_b) {

	Transform gt = get_global_transform();
	Transform ainv = body_a->get_global_transform().affine_inverse();

	Transform local_a = ainv * gt;
	local_a.orthonormalize();
	Transform local_b = gt;

	if (body_b) {
		Transform binv = body_b->get_global_transform().affine_inverse();
		local_b = binv * gt;
	}

	local_b.orthonormalize();

	RID j = PhysicsServer::get_singleton()->joint_create_slider(body_a->get_rid(), local_a, body_b ? body_b->get_rid() : RID(), local_b);
	for (int i = 0; i < PARAM_MAX; i++) {
		PhysicsServer::get_singleton()->slider_joint_set_param(j, PhysicsServer::SliderJointParam(i), params[i]);
	}

	return j;
}

SliderJoint::SliderJoint() {

	params[PARAM_LINEAR_LIMIT_UPPER] = 1.0;
	params[PARAM_LINEAR_LIMIT_LOWER] = -1.0;
	params[PARAM_LINEAR_LIMIT_SOFTNESS] = 1.0;
	params[PARAM_LINEAR_LIMIT_RESTITUTION] = 0.7;
	params[PARAM_LINEAR_LIMIT_DAMPING] = 1.0;
	params[PARAM_LINEAR_MOTION_SOFTNESS] = 1.0;
	params[PARAM_LINEAR_MOTION_RESTITUTION] = 0.7;
	params[PARAM_LINEAR_MOTION_DAMPING] = 0; //1.0;
	params[PARAM_LINEAR_ORTHOGONAL_SOFTNESS] = 1.0;
	params[PARAM_LINEAR_ORTHOGONAL_RESTITUTION] = 0.7;
	params[PARAM_LINEAR_ORTHOGONAL_DAMPING] = 1.0;

	params[PARAM_ANGULAR_LIMIT_UPPER] = 0;
	params[PARAM_ANGULAR_LIMIT_LOWER] = 0;
	params[PARAM_ANGULAR_LIMIT_SOFTNESS] = 1.0;
	params[PARAM_ANGULAR_LIMIT_RESTITUTION] = 0.7;
	params[PARAM_ANGULAR_LIMIT_DAMPING] = 0; //1.0;
	params[PARAM_ANGULAR_MOTION_SOFTNESS] = 1.0;
	params[PARAM_ANGULAR_MOTION_RESTITUTION] = 0.7;
	params[PARAM_ANGULAR_MOTION_DAMPING] = 1.0;
	params[PARAM_ANGULAR_ORTHOGONAL_SOFTNESS] = 1.0;
	params[PARAM_ANGULAR_ORTHOGONAL_RESTITUTION] = 0.7;
	params[PARAM_ANGULAR_ORTHOGONAL_DAMPING] = 1.0;
}

//////////////////////////////////

void ConeTwistJoint::_set_swing_span(float p_limit_angular) {

	set_param(PARAM_SWING_SPAN, Math::deg2rad(p_limit_angular));
}

float ConeTwistJoint::_get_swing_span() const {

	return Math::rad2deg(get_param(PARAM_SWING_SPAN));
}

void ConeTwistJoint::_set_twist_span(float p_limit_angular) {

	set_param(PARAM_TWIST_SPAN, Math::deg2rad(p_limit_angular));
}

float ConeTwistJoint::_get_twist_span() const {

	return Math::rad2deg(get_param(PARAM_TWIST_SPAN));
}

void ConeTwistJoint::_bind_methods() {

	ClassDB::bind_method(D_METHOD("set_param", "param", "value"), &ConeTwistJoint::set_param);
	ClassDB::bind_method(D_METHOD("get_param", "param"), &ConeTwistJoint::get_param);

	ClassDB::bind_method(D_METHOD("_set_swing_span", "swing_span"), &ConeTwistJoint::_set_swing_span);
	ClassDB::bind_method(D_METHOD("_get_swing_span"), &ConeTwistJoint::_get_swing_span);

	ClassDB::bind_method(D_METHOD("_set_twist_span", "twist_span"), &ConeTwistJoint::_set_twist_span);
	ClassDB::bind_method(D_METHOD("_get_twist_span"), &ConeTwistJoint::_get_twist_span);

	ADD_PROPERTY(PropertyInfo(Variant::REAL, "swing_span", PROPERTY_HINT_RANGE, "-180,180,0.1"), "_set_swing_span", "_get_swing_span");
	ADD_PROPERTY(PropertyInfo(Variant::REAL, "twist_span", PROPERTY_HINT_RANGE, "-40000,40000,0.1"), "_set_twist_span", "_get_twist_span");

	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "bias", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_BIAS);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "softness", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_SOFTNESS);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "relaxation", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_RELAXATION);

	BIND_ENUM_CONSTANT(PARAM_SWING_SPAN);
	BIND_ENUM_CONSTANT(PARAM_TWIST_SPAN);
	BIND_ENUM_CONSTANT(PARAM_BIAS);
	BIND_ENUM_CONSTANT(PARAM_SOFTNESS);
	BIND_ENUM_CONSTANT(PARAM_RELAXATION);
	BIND_ENUM_CONSTANT(PARAM_MAX);
}

void ConeTwistJoint::set_param(Param p_param, float p_value) {

	ERR_FAIL_INDEX(p_param, PARAM_MAX);
	params[p_param] = p_value;
	if (get_joint().is_valid())
		PhysicsServer::get_singleton()->cone_twist_joint_set_param(get_joint(), PhysicsServer::ConeTwistJointParam(p_param), p_value);

	update_gizmo();
}
float ConeTwistJoint::get_param(Param p_param) const {

	ERR_FAIL_INDEX_V(p_param, PARAM_MAX, 0);
	return params[p_param];
}

RID ConeTwistJoint::_configure_joint(PhysicsBody *body_a, PhysicsBody *body_b) {

	Transform gt = get_global_transform();
	//Vector3 cone_twistpos = gt.origin;
	//Vector3 cone_twistdir = gt.basis.get_axis(2);

	Transform ainv = body_a->get_global_transform().affine_inverse();

	Transform local_a = ainv * gt;
	local_a.orthonormalize();
	Transform local_b = gt;

	if (body_b) {
		Transform binv = body_b->get_global_transform().affine_inverse();
		local_b = binv * gt;
	}

	local_b.orthonormalize();

	RID j = PhysicsServer::get_singleton()->joint_create_cone_twist(body_a->get_rid(), local_a, body_b ? body_b->get_rid() : RID(), local_b);
	for (int i = 0; i < PARAM_MAX; i++) {
		PhysicsServer::get_singleton()->cone_twist_joint_set_param(j, PhysicsServer::ConeTwistJointParam(i), params[i]);
	}

	return j;
}

ConeTwistJoint::ConeTwistJoint() {

	params[PARAM_SWING_SPAN] = Math_PI * 0.25;
	params[PARAM_TWIST_SPAN] = Math_PI;
	params[PARAM_BIAS] = 0.3;
	params[PARAM_SOFTNESS] = 0.8;
	params[PARAM_RELAXATION] = 1.0;
}

/////////////////////////////////////////////////////////////////////

void Generic6DOFJoint::_set_angular_hi_limit_x(float p_limit_angular) {

	set_param_x(PARAM_ANGULAR_UPPER_LIMIT, Math::deg2rad(p_limit_angular));
}

float Generic6DOFJoint::_get_angular_hi_limit_x() const {

	return Math::rad2deg(get_param_x(PARAM_ANGULAR_UPPER_LIMIT));
}

void Generic6DOFJoint::_set_angular_lo_limit_x(float p_limit_angular) {

	set_param_x(PARAM_ANGULAR_LOWER_LIMIT, Math::deg2rad(p_limit_angular));
}

float Generic6DOFJoint::_get_angular_lo_limit_x() const {

	return Math::rad2deg(get_param_x(PARAM_ANGULAR_LOWER_LIMIT));
}

void Generic6DOFJoint::_set_angular_hi_limit_y(float p_limit_angular) {

	set_param_y(PARAM_ANGULAR_UPPER_LIMIT, Math::deg2rad(p_limit_angular));
}

float Generic6DOFJoint::_get_angular_hi_limit_y() const {

	return Math::rad2deg(get_param_y(PARAM_ANGULAR_UPPER_LIMIT));
}

void Generic6DOFJoint::_set_angular_lo_limit_y(float p_limit_angular) {

	set_param_y(PARAM_ANGULAR_LOWER_LIMIT, Math::deg2rad(p_limit_angular));
}

float Generic6DOFJoint::_get_angular_lo_limit_y() const {

	return Math::rad2deg(get_param_y(PARAM_ANGULAR_LOWER_LIMIT));
}

void Generic6DOFJoint::_set_angular_hi_limit_z(float p_limit_angular) {

	set_param_z(PARAM_ANGULAR_UPPER_LIMIT, Math::deg2rad(p_limit_angular));
}

float Generic6DOFJoint::_get_angular_hi_limit_z() const {

	return Math::rad2deg(get_param_z(PARAM_ANGULAR_UPPER_LIMIT));
}

void Generic6DOFJoint::_set_angular_lo_limit_z(float p_limit_angular) {

	set_param_z(PARAM_ANGULAR_LOWER_LIMIT, Math::deg2rad(p_limit_angular));
}

float Generic6DOFJoint::_get_angular_lo_limit_z() const {

	return Math::rad2deg(get_param_z(PARAM_ANGULAR_LOWER_LIMIT));
}

void Generic6DOFJoint::_bind_methods() {

	ClassDB::bind_method(D_METHOD("_set_angular_hi_limit_x", "angle"), &Generic6DOFJoint::_set_angular_hi_limit_x);
	ClassDB::bind_method(D_METHOD("_get_angular_hi_limit_x"), &Generic6DOFJoint::_get_angular_hi_limit_x);

	ClassDB::bind_method(D_METHOD("_set_angular_lo_limit_x", "angle"), &Generic6DOFJoint::_set_angular_lo_limit_x);
	ClassDB::bind_method(D_METHOD("_get_angular_lo_limit_x"), &Generic6DOFJoint::_get_angular_lo_limit_x);

	ClassDB::bind_method(D_METHOD("_set_angular_hi_limit_y", "angle"), &Generic6DOFJoint::_set_angular_hi_limit_y);
	ClassDB::bind_method(D_METHOD("_get_angular_hi_limit_y"), &Generic6DOFJoint::_get_angular_hi_limit_y);

	ClassDB::bind_method(D_METHOD("_set_angular_lo_limit_y", "angle"), &Generic6DOFJoint::_set_angular_lo_limit_y);
	ClassDB::bind_method(D_METHOD("_get_angular_lo_limit_y"), &Generic6DOFJoint::_get_angular_lo_limit_y);

	ClassDB::bind_method(D_METHOD("_set_angular_hi_limit_z", "angle"), &Generic6DOFJoint::_set_angular_hi_limit_z);
	ClassDB::bind_method(D_METHOD("_get_angular_hi_limit_z"), &Generic6DOFJoint::_get_angular_hi_limit_z);

	ClassDB::bind_method(D_METHOD("_set_angular_lo_limit_z", "angle"), &Generic6DOFJoint::_set_angular_lo_limit_z);
	ClassDB::bind_method(D_METHOD("_get_angular_lo_limit_z"), &Generic6DOFJoint::_get_angular_lo_limit_z);

	ClassDB::bind_method(D_METHOD("set_param_x", "param", "value"), &Generic6DOFJoint::set_param_x);
	ClassDB::bind_method(D_METHOD("get_param_x", "param"), &Generic6DOFJoint::get_param_x);

	ClassDB::bind_method(D_METHOD("set_param_y", "param", "value"), &Generic6DOFJoint::set_param_y);
	ClassDB::bind_method(D_METHOD("get_param_y", "param"), &Generic6DOFJoint::get_param_y);

	ClassDB::bind_method(D_METHOD("set_param_z", "param", "value"), &Generic6DOFJoint::set_param_z);
	ClassDB::bind_method(D_METHOD("get_param_z", "param"), &Generic6DOFJoint::get_param_z);

	ClassDB::bind_method(D_METHOD("set_flag_x", "flag", "value"), &Generic6DOFJoint::set_flag_x);
	ClassDB::bind_method(D_METHOD("get_flag_x", "flag"), &Generic6DOFJoint::get_flag_x);

	ClassDB::bind_method(D_METHOD("set_flag_y", "flag", "value"), &Generic6DOFJoint::set_flag_y);
	ClassDB::bind_method(D_METHOD("get_flag_y", "flag"), &Generic6DOFJoint::get_flag_y);

	ClassDB::bind_method(D_METHOD("set_flag_z", "flag", "value"), &Generic6DOFJoint::set_flag_z);
	ClassDB::bind_method(D_METHOD("get_flag_z", "flag"), &Generic6DOFJoint::get_flag_z);

	ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "linear_limit_x/enabled"), "set_flag_x", "get_flag_x", FLAG_ENABLE_LINEAR_LIMIT);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_x/upper_distance"), "set_param_x", "get_param_x", PARAM_LINEAR_UPPER_LIMIT);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_x/lower_distance"), "set_param_x", "get_param_x", PARAM_LINEAR_LOWER_LIMIT);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_x/softness", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_x", "get_param_x", PARAM_LINEAR_LIMIT_SOFTNESS);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_x/restitution", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_x", "get_param_x", PARAM_LINEAR_RESTITUTION);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_x/damping", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_x", "get_param_x", PARAM_LINEAR_DAMPING);
	ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "angular_limit_x/enabled"), "set_flag_x", "get_flag_x", FLAG_ENABLE_ANGULAR_LIMIT);
	ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_limit_x/upper_angle", PROPERTY_HINT_RANGE, "-180,180,0.01"), "_set_angular_hi_limit_x", "_get_angular_hi_limit_x");
	ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_limit_x/lower_angle", PROPERTY_HINT_RANGE, "-180,180,0.01"), "_set_angular_lo_limit_x", "_get_angular_lo_limit_x");
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_x/softness", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_x", "get_param_x", PARAM_ANGULAR_LIMIT_SOFTNESS);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_x/restitution", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_x", "get_param_x", PARAM_ANGULAR_RESTITUTION);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_x/damping", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_x", "get_param_x", PARAM_ANGULAR_DAMPING);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_x/force_limit"), "set_param_x", "get_param_x", PARAM_ANGULAR_FORCE_LIMIT);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_x/erp"), "set_param_x", "get_param_x", PARAM_ANGULAR_ERP);
	ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "angular_motor_x/enabled"), "set_flag_x", "get_flag_x", FLAG_ENABLE_MOTOR);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_motor_x/target_velocity"), "set_param_x", "get_param_x", PARAM_ANGULAR_MOTOR_TARGET_VELOCITY);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_motor_x/force_limit"), "set_param_x", "get_param_x", PARAM_ANGULAR_MOTOR_FORCE_LIMIT);

	ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "linear_limit_y/enabled"), "set_flag_y", "get_flag_y", FLAG_ENABLE_LINEAR_LIMIT);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_y/upper_distance"), "set_param_y", "get_param_y", PARAM_LINEAR_UPPER_LIMIT);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_y/lower_distance"), "set_param_y", "get_param_y", PARAM_LINEAR_LOWER_LIMIT);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_y/softness", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_y", "get_param_y", PARAM_LINEAR_LIMIT_SOFTNESS);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_y/restitution", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_y", "get_param_y", PARAM_LINEAR_RESTITUTION);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_y/damping", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_y", "get_param_y", PARAM_LINEAR_DAMPING);
	ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "angular_limit_y/enabled"), "set_flag_y", "get_flag_y", FLAG_ENABLE_ANGULAR_LIMIT);
	ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_limit_y/upper_angle", PROPERTY_HINT_RANGE, "-180,180,0.01"), "_set_angular_hi_limit_y", "_get_angular_hi_limit_y");
	ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_limit_y/lower_angle", PROPERTY_HINT_RANGE, "-180,180,0.01"), "_set_angular_lo_limit_y", "_get_angular_lo_limit_y");
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_y/softness", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_y", "get_param_y", PARAM_ANGULAR_LIMIT_SOFTNESS);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_y/restitution", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_y", "get_param_y", PARAM_ANGULAR_RESTITUTION);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_y/damping", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_y", "get_param_y", PARAM_ANGULAR_DAMPING);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_y/force_limit"), "set_param_y", "get_param_y", PARAM_ANGULAR_FORCE_LIMIT);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_y/erp"), "set_param_y", "get_param_y", PARAM_ANGULAR_ERP);
	ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "angular_motor_y/enabled"), "set_flag_y", "get_flag_y", FLAG_ENABLE_MOTOR);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_motor_y/target_velocity"), "set_param_y", "get_param_y", PARAM_ANGULAR_MOTOR_TARGET_VELOCITY);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_motor_y/force_limit"), "set_param_y", "get_param_y", PARAM_ANGULAR_MOTOR_FORCE_LIMIT);

	ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "linear_limit_z/enabled"), "set_flag_z", "get_flag_z", FLAG_ENABLE_LINEAR_LIMIT);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_z/upper_distance"), "set_param_z", "get_param_z", PARAM_LINEAR_UPPER_LIMIT);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_z/lower_distance"), "set_param_z", "get_param_z", PARAM_LINEAR_LOWER_LIMIT);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_z/softness", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_z", "get_param_z", PARAM_LINEAR_LIMIT_SOFTNESS);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_z/restitution", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_z", "get_param_z", PARAM_LINEAR_RESTITUTION);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_z/damping", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_z", "get_param_z", PARAM_LINEAR_DAMPING);
	ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "angular_limit_z/enabled"), "set_flag_z", "get_flag_z", FLAG_ENABLE_ANGULAR_LIMIT);
	ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_limit_z/upper_angle", PROPERTY_HINT_RANGE, "-180,180,0.01"), "_set_angular_hi_limit_z", "_get_angular_hi_limit_z");
	ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_limit_z/lower_angle", PROPERTY_HINT_RANGE, "-180,180,0.01"), "_set_angular_lo_limit_z", "_get_angular_lo_limit_z");
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_z/softness", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_z", "get_param_z", PARAM_ANGULAR_LIMIT_SOFTNESS);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_z/restitution", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_z", "get_param_z", PARAM_ANGULAR_RESTITUTION);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_z/damping", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_z", "get_param_z", PARAM_ANGULAR_DAMPING);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_z/force_limit"), "set_param_z", "get_param_z", PARAM_ANGULAR_FORCE_LIMIT);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_z/erp"), "set_param_z", "get_param_z", PARAM_ANGULAR_ERP);
	ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "angular_motor_z/enabled"), "set_flag_z", "get_flag_z", FLAG_ENABLE_MOTOR);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_motor_z/target_velocity"), "set_param_z", "get_param_z", PARAM_ANGULAR_MOTOR_TARGET_VELOCITY);
	ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_motor_z/force_limit"), "set_param_z", "get_param_z", PARAM_ANGULAR_MOTOR_FORCE_LIMIT);

	BIND_ENUM_CONSTANT(PARAM_LINEAR_LOWER_LIMIT);
	BIND_ENUM_CONSTANT(PARAM_LINEAR_UPPER_LIMIT);
	BIND_ENUM_CONSTANT(PARAM_LINEAR_LIMIT_SOFTNESS);
	BIND_ENUM_CONSTANT(PARAM_LINEAR_RESTITUTION);
	BIND_ENUM_CONSTANT(PARAM_LINEAR_DAMPING);
	BIND_ENUM_CONSTANT(PARAM_ANGULAR_LOWER_LIMIT);
	BIND_ENUM_CONSTANT(PARAM_ANGULAR_UPPER_LIMIT);
	BIND_ENUM_CONSTANT(PARAM_ANGULAR_LIMIT_SOFTNESS);
	BIND_ENUM_CONSTANT(PARAM_ANGULAR_DAMPING);
	BIND_ENUM_CONSTANT(PARAM_ANGULAR_RESTITUTION);
	BIND_ENUM_CONSTANT(PARAM_ANGULAR_FORCE_LIMIT);
	BIND_ENUM_CONSTANT(PARAM_ANGULAR_ERP);
	BIND_ENUM_CONSTANT(PARAM_ANGULAR_MOTOR_TARGET_VELOCITY);
	BIND_ENUM_CONSTANT(PARAM_ANGULAR_MOTOR_FORCE_LIMIT);
	BIND_ENUM_CONSTANT(PARAM_MAX);

	BIND_ENUM_CONSTANT(FLAG_ENABLE_LINEAR_LIMIT);
	BIND_ENUM_CONSTANT(FLAG_ENABLE_ANGULAR_LIMIT);
	BIND_ENUM_CONSTANT(FLAG_ENABLE_MOTOR);
	BIND_ENUM_CONSTANT(FLAG_MAX);
}

void Generic6DOFJoint::set_param_x(Param p_param, float p_value) {

	ERR_FAIL_INDEX(p_param, PARAM_MAX);
	params_x[p_param] = p_value;
	if (get_joint().is_valid())
		PhysicsServer::get_singleton()->generic_6dof_joint_set_param(get_joint(), Vector3::AXIS_X, PhysicsServer::G6DOFJointAxisParam(p_param), p_value);

	update_gizmo();
}
float Generic6DOFJoint::get_param_x(Param p_param) const {

	ERR_FAIL_INDEX_V(p_param, PARAM_MAX, 0);
	return params_x[p_param];
}

void Generic6DOFJoint::set_param_y(Param p_param, float p_value) {

	ERR_FAIL_INDEX(p_param, PARAM_MAX);
	params_y[p_param] = p_value;
	if (get_joint().is_valid())
		PhysicsServer::get_singleton()->generic_6dof_joint_set_param(get_joint(), Vector3::AXIS_Y, PhysicsServer::G6DOFJointAxisParam(p_param), p_value);
	update_gizmo();
}
float Generic6DOFJoint::get_param_y(Param p_param) const {

	ERR_FAIL_INDEX_V(p_param, PARAM_MAX, 0);
	return params_y[p_param];
}

void Generic6DOFJoint::set_param_z(Param p_param, float p_value) {

	ERR_FAIL_INDEX(p_param, PARAM_MAX);
	params_z[p_param] = p_value;
	if (get_joint().is_valid())
		PhysicsServer::get_singleton()->generic_6dof_joint_set_param(get_joint(), Vector3::AXIS_Z, PhysicsServer::G6DOFJointAxisParam(p_param), p_value);
	update_gizmo();
}
float Generic6DOFJoint::get_param_z(Param p_param) const {

	ERR_FAIL_INDEX_V(p_param, PARAM_MAX, 0);
	return params_z[p_param];
}

void Generic6DOFJoint::set_flag_x(Flag p_flag, bool p_enabled) {

	ERR_FAIL_INDEX(p_flag, FLAG_MAX);
	flags_x[p_flag] = p_enabled;
	if (get_joint().is_valid())
		PhysicsServer::get_singleton()->generic_6dof_joint_set_flag(get_joint(), Vector3::AXIS_X, PhysicsServer::G6DOFJointAxisFlag(p_flag), p_enabled);
	update_gizmo();
}
bool Generic6DOFJoint::get_flag_x(Flag p_flag) const {

	ERR_FAIL_INDEX_V(p_flag, FLAG_MAX, false);
	return flags_x[p_flag];
}

void Generic6DOFJoint::set_flag_y(Flag p_flag, bool p_enabled) {

	ERR_FAIL_INDEX(p_flag, FLAG_MAX);
	flags_y[p_flag] = p_enabled;
	if (get_joint().is_valid())
		PhysicsServer::get_singleton()->generic_6dof_joint_set_flag(get_joint(), Vector3::AXIS_Y, PhysicsServer::G6DOFJointAxisFlag(p_flag), p_enabled);
	update_gizmo();
}
bool Generic6DOFJoint::get_flag_y(Flag p_flag) const {

	ERR_FAIL_INDEX_V(p_flag, FLAG_MAX, false);
	return flags_y[p_flag];
}

void Generic6DOFJoint::set_flag_z(Flag p_flag, bool p_enabled) {

	ERR_FAIL_INDEX(p_flag, FLAG_MAX);
	flags_z[p_flag] = p_enabled;
	if (get_joint().is_valid())
		PhysicsServer::get_singleton()->generic_6dof_joint_set_flag(get_joint(), Vector3::AXIS_Z, PhysicsServer::G6DOFJointAxisFlag(p_flag), p_enabled);
	update_gizmo();
}
bool Generic6DOFJoint::get_flag_z(Flag p_flag) const {

	ERR_FAIL_INDEX_V(p_flag, FLAG_MAX, false);
	return flags_z[p_flag];
}

RID Generic6DOFJoint::_configure_joint(PhysicsBody *body_a, PhysicsBody *body_b) {

	Transform gt = get_global_transform();
	//Vector3 cone_twistpos = gt.origin;
	//Vector3 cone_twistdir = gt.basis.get_axis(2);

	Transform ainv = body_a->get_global_transform().affine_inverse();

	Transform local_a = ainv * gt;
	local_a.orthonormalize();
	Transform local_b = gt;

	if (body_b) {
		Transform binv = body_b->get_global_transform().affine_inverse();
		local_b = binv * gt;
	}

	local_b.orthonormalize();

	RID j = PhysicsServer::get_singleton()->joint_create_generic_6dof(body_a->get_rid(), local_a, body_b ? body_b->get_rid() : RID(), local_b);
	for (int i = 0; i < PARAM_MAX; i++) {
		PhysicsServer::get_singleton()->generic_6dof_joint_set_param(j, Vector3::AXIS_X, PhysicsServer::G6DOFJointAxisParam(i), params_x[i]);
		PhysicsServer::get_singleton()->generic_6dof_joint_set_param(j, Vector3::AXIS_Y, PhysicsServer::G6DOFJointAxisParam(i), params_y[i]);
		PhysicsServer::get_singleton()->generic_6dof_joint_set_param(j, Vector3::AXIS_Z, PhysicsServer::G6DOFJointAxisParam(i), params_z[i]);
	}
	for (int i = 0; i < FLAG_MAX; i++) {
		PhysicsServer::get_singleton()->generic_6dof_joint_set_flag(j, Vector3::AXIS_X, PhysicsServer::G6DOFJointAxisFlag(i), flags_x[i]);
		PhysicsServer::get_singleton()->generic_6dof_joint_set_flag(j, Vector3::AXIS_Y, PhysicsServer::G6DOFJointAxisFlag(i), flags_y[i]);
		PhysicsServer::get_singleton()->generic_6dof_joint_set_flag(j, Vector3::AXIS_Z, PhysicsServer::G6DOFJointAxisFlag(i), flags_z[i]);
	}

	return j;
}

Generic6DOFJoint::Generic6DOFJoint() {

	set_param_x(PARAM_LINEAR_LOWER_LIMIT, 0);
	set_param_x(PARAM_LINEAR_UPPER_LIMIT, 0);
	set_param_x(PARAM_LINEAR_LIMIT_SOFTNESS, 0.7);
	set_param_x(PARAM_LINEAR_RESTITUTION, 0.5);
	set_param_x(PARAM_LINEAR_DAMPING, 1.0);
	set_param_x(PARAM_ANGULAR_LOWER_LIMIT, 0);
	set_param_x(PARAM_ANGULAR_UPPER_LIMIT, 0);
	set_param_x(PARAM_ANGULAR_LIMIT_SOFTNESS, 0.5f);
	set_param_x(PARAM_ANGULAR_DAMPING, 1.0f);
	set_param_x(PARAM_ANGULAR_RESTITUTION, 0);
	set_param_x(PARAM_ANGULAR_FORCE_LIMIT, 0);
	set_param_x(PARAM_ANGULAR_ERP, 0.5);
	set_param_x(PARAM_ANGULAR_MOTOR_TARGET_VELOCITY, 0);
	set_param_x(PARAM_ANGULAR_MOTOR_FORCE_LIMIT, 300);

	set_flag_x(FLAG_ENABLE_ANGULAR_LIMIT, true);
	set_flag_x(FLAG_ENABLE_LINEAR_LIMIT, true);
	set_flag_x(FLAG_ENABLE_MOTOR, false);

	set_param_y(PARAM_LINEAR_LOWER_LIMIT, 0);
	set_param_y(PARAM_LINEAR_UPPER_LIMIT, 0);
	set_param_y(PARAM_LINEAR_LIMIT_SOFTNESS, 0.7);
	set_param_y(PARAM_LINEAR_RESTITUTION, 0.5);
	set_param_y(PARAM_LINEAR_DAMPING, 1.0);
	set_param_y(PARAM_ANGULAR_LOWER_LIMIT, 0);
	set_param_y(PARAM_ANGULAR_UPPER_LIMIT, 0);
	set_param_y(PARAM_ANGULAR_LIMIT_SOFTNESS, 0.5f);
	set_param_y(PARAM_ANGULAR_DAMPING, 1.0f);
	set_param_y(PARAM_ANGULAR_RESTITUTION, 0);
	set_param_y(PARAM_ANGULAR_FORCE_LIMIT, 0);
	set_param_y(PARAM_ANGULAR_ERP, 0.5);
	set_param_y(PARAM_ANGULAR_MOTOR_TARGET_VELOCITY, 0);
	set_param_y(PARAM_ANGULAR_MOTOR_FORCE_LIMIT, 300);

	set_flag_y(FLAG_ENABLE_ANGULAR_LIMIT, true);
	set_flag_y(FLAG_ENABLE_LINEAR_LIMIT, true);
	set_flag_y(FLAG_ENABLE_MOTOR, false);

	set_param_z(PARAM_LINEAR_LOWER_LIMIT, 0);
	set_param_z(PARAM_LINEAR_UPPER_LIMIT, 0);
	set_param_z(PARAM_LINEAR_LIMIT_SOFTNESS, 0.7);
	set_param_z(PARAM_LINEAR_RESTITUTION, 0.5);
	set_param_z(PARAM_LINEAR_DAMPING, 1.0);
	set_param_z(PARAM_ANGULAR_LOWER_LIMIT, 0);
	set_param_z(PARAM_ANGULAR_UPPER_LIMIT, 0);
	set_param_z(PARAM_ANGULAR_LIMIT_SOFTNESS, 0.5f);
	set_param_z(PARAM_ANGULAR_DAMPING, 1.0f);
	set_param_z(PARAM_ANGULAR_RESTITUTION, 0);
	set_param_z(PARAM_ANGULAR_FORCE_LIMIT, 0);
	set_param_z(PARAM_ANGULAR_ERP, 0.5);
	set_param_z(PARAM_ANGULAR_MOTOR_TARGET_VELOCITY, 0);
	set_param_z(PARAM_ANGULAR_MOTOR_FORCE_LIMIT, 300);

	set_flag_z(FLAG_ENABLE_ANGULAR_LIMIT, true);
	set_flag_z(FLAG_ENABLE_LINEAR_LIMIT, true);
	set_flag_z(FLAG_ENABLE_MOTOR, false);
}


text:
class BLEUTERCombinationScorer : public SentenceScorer {
 public:
  BLEUTERCombinationScorer(const std::vector<std::vector<WordID> >& refs);
  ~BLEUTERCombinationScorer();
  Score* ScoreCandidate(const std::vector<WordID>& hyp) const;
  static Score* ScoreFromString(const std::string& in);
 private:
  SentenceScorer* bleu_;
  SentenceScorer* ter_;
};

#endif

redpajama_set_name: RedPajamaGithub


text:
package com.amazonaws.services.chime.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.chime.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * VideoArtifactsConfigurationMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class VideoArtifactsConfigurationMarshaller {

    private static final MarshallingInfo<String> STATE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("State").build();
    private static final MarshallingInfo<String> MUXTYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("MuxType").build();

    private static final VideoArtifactsConfigurationMarshaller instance = new VideoArtifactsConfigurationMarshaller();

    public static VideoArtifactsConfigurationMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(VideoArtifactsConfiguration videoArtifactsConfiguration, ProtocolMarshaller protocolMarshaller) {

        if (videoArtifactsConfiguration == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(videoArtifactsConfiguration.getState(), STATE_BINDING);
            protocolMarshaller.marshall(videoArtifactsConfiguration.getMuxType(), MUXTYPE_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
"""
This module finds diffusion paths through a structure based on a given potential field.
If you use PathFinder algorithm for your research, please consider citing the following work:
    Ziqin Rong, Daniil Kitchaev, Pieremanuele Canepa, Wenxuan Huang, Gerbrand Ceder,
    The Journal of Chemical Physics 145 (7), 074112
"""

from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import

import numpy as np
import numpy.linalg as la
import scipy.signal
import scipy.stats
from scipy.interpolate import interp1d
import math
import six

from abc import ABCMeta, abstractmethod

from pymatgen.core.structure import Structure
from pymatgen.core.lattice import Lattice
from pymatgen.core.sites import *
from pymatgen.core.periodic_table import *
from pymatgen.io.vasp.inputs import Poscar
from pymatgen.io.vasp.outputs import VolumetricData, Chgcar

__author__ = "Daniil Kitchaev"
__version__ = "1.0"
__maintainer__ = "Daniil Kitchaev, Ziqin Rong"
__email__ = "dkitch@mit.edu, rongzq08@mit.edu"
__status__ = "Development"
__date__ = "March 17, 2015"

class NEBPathfinder:
    def __init__(self, start_struct, end_struct, relax_sites, v, n_images=20):
        """
        General pathfinder for interpolating between two structures, where the interpolating path is calculated with
        the elastic band method with respect to the given static potential for sites whose indices are given in
        relax_sites, and is linear otherwise.
        :param start_struct, end_struct - Endpoint structures to interpolate between
        :param relax_sites - List of site indices whose interpolation paths should be relaxed
        :param v - Static potential field to use for the elastic band relaxation
        :param n_images - Number of interpolation images to generate
        """
        self.__s1 = start_struct
        self.__s2 = end_struct
        self.__relax_sites = relax_sites
        self.__v = v
        self.__n_images = n_images
        self.__images = None
        self.interpolate()

    def interpolate(self):
        """
        Finds a set of n_images from self.s1 to self.s2, where all sites except for the ones given in relax_sites,
        the interpolation is linear (as in pymatgen.core.structure.interpolate), and for the site indices given
        in relax_sites, the path is relaxed by the elastic band method within the static potential V.
        :param relax_sites: List of site indices for which the interpolation path needs to be relaxed
        :param v: static potential to use for relaxing the interpolation path
        :param n_images: number of images to generate along the interpolation path
        """
        images = self.__s1.interpolate(self.__s2, nimages=self.__n_images, interpolate_lattices=False)
        for site_i in self.__relax_sites:
            start_f = images[0].sites[site_i].frac_coords
            end_f = images[-1].sites[site_i].frac_coords

            path = NEBPathfinder.string_relax(NEBPathfinder.__f2d(start_f, self.__v),
                                              NEBPathfinder.__f2d(end_f, self.__v),
                                              self.__v, n_images=(self.__n_images+1),
                                                                    dr=[self.__s1.lattice.a/self.__v.shape[0],
                                                                        self.__s1.lattice.b/self.__v.shape[1],
                                                                        self.__s1.lattice.c/self.__v.shape[2]])
            for image_i, image in enumerate(images):
                image.translate_sites(site_i,
                                      NEBPathfinder.__d2f(path[image_i], self.__v) - image.sites[site_i].frac_coords,
                                      frac_coords=True, to_unit_cell=True)
        self.__images = images

    @property
    def images(self):
        """
        Returns a list of structures interpolating between the start and endpoint structures.
        """
        return self.__images

    def plot_images(self, outfile):
        """
        Generates a POSCAR with the calculated diffusion path with respect to the first endpoint.
        :param outfile: Output file for the POSCAR
        """
        sum_struct = self.__images[0].sites
        for image in self.__images:
            for site_i in self.__relax_sites:
                sum_struct.append(PeriodicSite(image.sites[site_i].specie, image.sites[site_i].frac_coords,
                                               self.__images[0].lattice, to_unit_cell=True, coords_are_cartesian=False))
        sum_struct = Structure.from_sites(sum_struct, validate_proximity=False)
        p = Poscar(sum_struct)
        p.write_file(outfile)

    @staticmethod
    def string_relax(start, end, V, n_images=25, dr=None, h=3.0, k=0.17, min_iter=100, max_iter=10000, max_tol=5e-6):
        """
        Implements path relaxation via the elastic band method. In general, the method is to define a path by a set of
        points (images) connected with bands with some elasticity constant k. The images then relax along the forces
        found in the potential field V, counterbalanced by the elastic response of the elastic band. In general the
        endpoints of the band can be allowed to relax also to their local minima, but in this calculation they are kept
        fixed.
        :param start, end - Endpoints of the path calculation given in discrete coordinates with respect to the grid in V
        :param V - potential field through which to calculate the path
        :param n_images - number of images used to define the path. In general anywhere from 20 to 40 seems to be good.
        :param dr - Conversion ratio from discrete coordinates to real coordinates for each of the three coordinate vectors
        :param h - Step size for the relaxation. h = 0.1 works reliably, but is slow. h=10 diverges with large gradients
                    but for the types of gradients seen in CHGCARs, works pretty reliably
        :param k - Elastic constant for the band (in real units, not discrete)
        :param min_iter, max_iter - Number of optimization steps the string will take before exiting (even if unconverged)
        :param max_tol - Convergence threshold such that if the string moves by less than max_tol in a step, and at least
                        min_iter steps have passed, the algorithm will terminate. Depends strongly on the size of the
                        gradients in V, but 5e-6 works reasonably well for CHGCARs

        """
        #
        # This code is based on the MATLAB example provided by
        # Prof. Eric Vanden-Eijnden of NYU
        # (http://www.cims.nyu.edu/~eve2/main.htm)
        #

        print("Getting path from {} to {} (coords wrt V grid)".format(start, end))
        # Set parameters
        if not dr:
            dr = np.array([1.0/V.shape[0], 1.0/V.shape[1], 1.0/V.shape[2]])
        else:
            dr = np.array(dr, dtype=float)
        keff = k * dr * n_images
        h0 = h

        # Initialize string
        g1 = np.linspace(0, 1, n_images)
        s0 = start
        s1 = end
        s = np.array([g * (s1-s0) for g in g1]) + s0
        ds = s - np.roll(s,1,axis=0)
        ds[0] = (ds[0] - ds[0])
        ls = np.cumsum(la.norm(ds, axis=1))
        ls = ls/ls[-1]
        fi = interp1d(ls,s,axis=0)
        s = fi(g1)

        # Evaluate initial distances (for elastic equilibrium)
        ds0_plus = s - np.roll(s,1,axis=0)
        ds0_minus =  s - np.roll(s,-1,axis=0)
        ds0_plus[0] = (ds0_plus[0] - ds0_plus[0])
        ds0_minus[-1] = (ds0_minus[-1] - ds0_minus[-1])

        # Evolve string
        for step in range(0, max_iter):
            if step > min_iter:
                h = h0 * np.exp(-2.0 * (step - min_iter)/max_iter) # Gradually decay step size to prevent oscillations
            else:
                h = h0
            # Calculate forces acting on string
            dV = np.gradient(V)
            d = V.shape
            s0 = s
            edV = np.array([[dV[0][int(pt[0])%d[0]][int(pt[1])%d[1]][int(pt[2])%d[2]] / dr[0],
                             dV[1][int(pt[0])%d[0]][int(pt[1])%d[1]][int(pt[2])%d[2]] / dr[0],
                             dV[2][int(pt[0])%d[0]][int(pt[1])%d[1]][int(pt[2])%d[2]] / dr[0]] for pt in s])
            #if(step % 100 == 0):
            #    print(edV)

            # Update according to force due to potential and string elasticity
            ds_plus = s - np.roll(s,1,axis=0)
            ds_minus =  s - np.roll(s,-1,axis=0)
            ds_plus[0] = (ds_plus[0] - ds_plus[0])
            ds_minus[-1] = (ds_minus[-1] - ds_minus[-1])
            Fpot = edV
            Fel = keff * (la.norm(ds_plus) - la.norm(ds0_plus)) * (ds_plus / la.norm(ds_plus))
            Fel += keff * (la.norm(ds_minus) - la.norm(ds0_minus)) * (ds_minus / la.norm(ds_minus))
            s = s - h * (Fpot + Fel)

            # Fix endpoints
            s[0] = s0[0]
            s[-1] = s0[-1]

            # Reparametrize string
            ds = s - np.roll(s,1,axis=0)
            ds[0] = (ds[0] - ds[0])
            ls = np.cumsum(la.norm(ds, axis=1))
            ls = ls/ls[-1]
            fi = interp1d(ls,s,axis=0)
            s = fi(g1)

            tol = la.norm((s-s0) * dr) / n_images / h

            if (tol > 1e10):
                raise ValueError("Pathfinding failed, path diverged! Consider reducing h to avoid divergence.")

            if (step > min_iter and tol < max_tol):
                print("Converged at step {}".format(step))
                break

            if (step % 100 == 0):
                print ("Step {} - ds = {}".format(step, tol))
        return s

    @staticmethod
    def __f2d(frac_coords, v):
        """
        Converts fractional coordinates to discrete coordinates with respect to the grid size of v
        """
        #frac_coords = frac_coords % 1
        return np.array([int(frac_coords[0]*v.shape[0]),
                         int(frac_coords[1]*v.shape[1]),
                         int(frac_coords[2]*v.shape[2])])

    @staticmethod
    def __d2f(disc_coords, v):
        """
        Converts a point given in discrete coordinates withe respect to the grid in v to fractional coordinates.
        """
        return np.array([disc_coords[0]/v.shape[0],
                         disc_coords[1]/v.shape[1],
                         disc_coords[2]/v.shape[2]])

class StaticPotential(six.with_metaclass(ABCMeta)):
    """
    Defines a general static potential for diffusion calculations. Implements grid-rescaling and smearing for the
    potential grid. Also provides a function to normalize the potential from 0 to 1 (recommended).
    """
    def __init__(self, struct, pot):
        self.__v = pot
        self.__s = struct

    def get_v(self):
        """
        Returns the potential
        """
        return self.__v

    def normalize(self):
        """
        Sets the potential range 0 to 1.
        """
        self.__v = self.__v - np.amin(self.__v)
        self.__v = self.__v / np.amax(self.__v)

    def rescale_field(self, new_dim):
        """
        Changes the discretization of the potential field by linear interpolation. This is necessary if the potential field
        obtained from DFT is strangely skewed, or is too fine or coarse. Obeys periodic boundary conditions at the edges of
        the cell. Alternatively useful for mixing potentials that originally are on different grids.

        :param new_dim: tuple giving the numpy shape of the new grid
        """
        v_dim = self.__v.shape
        padded_v = np.lib.pad(self.__v, ((0,1), (0,1), (0,1)), mode='wrap')
        ogrid_list = np.array([list(c) for c in list(np.ndindex(v_dim[0]+1, v_dim[1]+1, v_dim[2]+1))])
        v_ogrid = padded_v.reshape(((v_dim[0]+1) * (v_dim[1]+1) * (v_dim[2]+1), -1))
        ngrid_a, ngrid_b, ngrid_c = np.mgrid[0 : v_dim[0] : v_dim[0]/new_dim[0],
                                             0 : v_dim[1] : v_dim[1]/new_dim[1],
                                             0 : v_dim[2] : v_dim[2]/new_dim[2]]

        v_ngrid = scipy.interpolate.griddata(ogrid_list, v_ogrid, (ngrid_a, ngrid_b, ngrid_c), method='linear').reshape((new_dim[0], new_dim[1], new_dim[2]))
        self.__v = v_ngrid

    def gaussian_smear(self, r):
        """
        Applies an isotropic Gaussian smear of width (standard deviation) r to the potential field. This is necessary to
        avoid finding paths through narrow minima or nodes that may exist in the field (although any potential or
        charge distribution generated from GGA should be relatively smooth anyway). The smearing obeys periodic
        boundary conditions at the edges of the cell.

        :param r - Smearing width in cartesian coordinates, in the same units as the structure lattice vectors
        """
        # Since scaling factor in fractional coords is not isotropic, have to have different radii in 3 directions
        a_lat = self.__s.lattice.a
        b_lat = self.__s.lattice.b
        c_lat = self.__s.lattice.c

        # Conversion factors for discretization of v
        v_dim = self.__v.shape
        r_frac = (r / a_lat, r / b_lat, r / c_lat)
        r_disc = (int(math.ceil(r_frac[0] * v_dim[0])), int(math.ceil(r_frac[1] * v_dim[1])),
                  int(math.ceil(r_frac[2] * v_dim[2])))

        # Apply smearing
        # Gaussian filter
        gauss_dist = np.zeros((r_disc[0] * 4 + 1, r_disc[1] * 4 + 1, r_disc[2] * 4 + 1))
        for g_a in np.arange(-2.0 * r_disc[0], 2.0 * r_disc[0] + 1, 1.0):
            for g_b in np.arange(-2.0 * r_disc[1], 2.0 * r_disc[1] + 1, 1.0):
                for g_c in np.arange(-2.0 * r_disc[2], 2.0 * r_disc[2] + 1, 1.0):
                    g = np.array([g_a / v_dim[0], g_b / v_dim[1], g_c / v_dim[2]]).T
                    gauss_dist[int(g_a + r_disc[0])][int(g_b + r_disc[1])][int(g_c + r_disc[2])] = la.norm(np.dot(self.__s.lattice.matrix, g))/r
        gauss = scipy.stats.norm.pdf(gauss_dist)
        gauss = gauss/np.sum(gauss, dtype=float)
        padded_v = np.pad(self.__v, ((r_disc[0], r_disc[0]), (r_disc[1], r_disc[1]), (r_disc[2], r_disc[2])), mode='wrap')
        smeared_v = scipy.signal.convolve(padded_v, gauss, mode='valid')
        self.__v = smeared_v

class ChgcarPotential(StaticPotential):
    '''
    Implements a potential field based on the charge density output from VASP.
    '''
    def __init__(self, chgcar, smear=False, normalize=True):
        """
        :param chgcar: Chgcar object based on a VASP run of the structure of interest (Chgcar.from_file("CHGCAR"))
        :param smear: Whether or not to apply a Gaussian smearing to the potential
        :param normalize: Whether or not to normalize the potential to range from 0 to 1
        """
        v = chgcar.data['total']
        v = v / (v.shape[0] * v.shape[1] * v.shape[2])
        StaticPotential.__init__(self, chgcar.structure, v)
        if smear:
            self.gaussian_smear(2.0)
        if normalize:
            self.normalize()

class FreeVolumePotential(StaticPotential):
    '''
    Implements a potential field based on geometric distances from atoms in the structure - basically, the potential
    is lower at points farther away from any atoms in the structure.
    '''
    def __init__(self, struct, dim, smear=False, normalize=True):
        """
        :param struct: Unit cell on which to base the potential
        :param dim: Grid size for the potential
        :param smear: Whether or not to apply a Gaussian smearing to the potential
        :param normalize: Whether or not to normalize the potential to range from 0 to 1
        """
        self.__s = struct
        v = FreeVolumePotential.__add_gaussians(struct, dim)
        StaticPotential.__init__(self, struct, v)
        if smear:
            self.gaussian_smear(2.0)
        if normalize:
            self.normalize()

    @staticmethod
    def __add_gaussians(s, dim, r=1.5):
        gauss_dist = np.zeros(dim)
        for a_d in np.arange(0.0, dim[0], 1.0):
            for b_d in np.arange(0.0, dim[1], 1.0):
                for c_d in np.arange(0.0, dim[2], 1.0):
                    coords_f = np.array([a_d / dim[0], b_d / dim[1], c_d / dim[2]])
                    d_f = sorted(s.get_sites_in_sphere(coords_f, s.lattice.a), key=lambda x:x[1])[0][1]
                    #print(d_f)
                    gauss_dist[int(a_d)][int(b_d)][int(c_d)] = d_f / r
        v = scipy.stats.norm.pdf(gauss_dist)
        return v

class MixedPotential(StaticPotential):
    '''
    Implements a potential that is a weighted sum of some other potentials
    '''
    def __init__(self, potentials, coefficients, smear=False, normalize=True):
        """
        :param potentials: List of objects extending the StaticPotential superclass
        :param coefficients: Mixing weights for the elements of the potentials list
        :param smear: Whether or not to apply a Gaussian smearing to the potential
        :param normalize: Whether or not to normalize the potential to range from 0 to 1
        """
        v = potentials[0].get_v() * coefficients[0]
        s = potentials[0].__s
        for i in range(1, len(potentials)):
            v += potentials[i].get_v() * coefficients[i]
        StaticPotential.__init__(self, s, v)
        if smear:
            self.gaussian_smear(2.0)
        if normalize:
            self.normalize()


text:
cd "$(dirname "${BASH_SOURCE[0]}")" \
    && . "../../utils.sh"

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

print_in_purple "\n   Trackpad\n\n"

execute "defaults write com.apple.driver.AppleBluetoothMultitouch.trackpad Clicking -bool true && \
         defaults write com.apple.AppleMultitouchTrackpad Clicking -int 1 && \
         defaults write -g com.apple.mouse.tapBehavior -int 1 && \
         defaults -currentHost write -g com.apple.mouse.tapBehavior -int 1" \
    "Ative 'Tap to click'"

execute "defaults write com.apple.driver.AppleBluetoothMultitouch.trackpad TrackpadRightClick -bool true && \
         defaults write com.apple.AppleMultitouchTrackpad TrackpadRightClick -int 1 && \
         defaults -currentHost write -g com.apple.trackpad.enableSecondaryClick -bool true && \
         defaults write com.apple.driver.AppleBluetoothMultitouch.trackpad TrackpadCornerSecondaryClick -int 0 && \
         defaults write com.apple.AppleMultitouchTrackpad TrackpadCornerSecondaryClick -int 0 && \
         defaults -currentHost write -g com.apple.trackpad.trackpadCornerClickBehavior -int 0" \
    "Mapeie 'click or tap with two fingers' para clique secundário"


text:
var should = require('should');
var support = require('./support/client-server');
var jayson = require(__dirname + '/..');
var connect = require('connect');

describe('jayson middleware', function() {

  var server, client, context = {};

  beforeEach(function(done) {
    server = context.server = connect.createServer();
    server.use(connect.json({reviver: support.options.reviver}));
    server.use(jayson.server(support.methods, support.options).middleware());
    server = server.listen(3000, done);
  });

  beforeEach(function() {
    client = context.client = jayson.client.http({
      reviver: support.options.reviver,
      replacer: support.options.replacer,
      host: 'localhost',
      port: 3000
    });
  });

  afterEach(function() {
    if(server) server.close();
  });

  it('should be able to receive a success-method from a client', support.clientRequest(context));

  it('should be able to receive an error-method from a client', support.clientError(context));

  it('should support reviving and replacing', support.clientReviveReplace(context));

  it('should be able to handle a notification', support.clientNotification(context));

  it('should be able to handle a batch request', support.clientBatch(context));

});


text:
FactoryGirl.define do
	factory :admin do
		password 'foobar123'
		password_confirmation { |u| u.password }
		email 'admin@local.com'
		name 'administrator'
		identification '1094891516'
		phone '3113412790'
	end
end


text:
A sample Snake appplication!

Kind of tribute to the old Nokia 3310...


text:
#include "Panel.h"

Panel::Panel()
{
	CtrlLayout(*this);
	CtrlLayout(editopt);
	CtrlLayout(lookopt);
	CtrlLayout(colsopt);
	CtrlLayout(numsopt);

	opts.Add(lookopt, "Look");
	opts.Add(editopt, "Edit");
	opts.Add(colsopt, "Colors");
	opts.Add(numsopt, "Numbers");

	lookopt.indicator         <<= THISBACK1(LookOptions, 0);
	lookopt.hgrid             <<= THISBACK1(LookOptions, 1);
	lookopt.vgrid             <<= THISBACK1(LookOptions, 2);
	lookopt.resizing_cols     <<= THISBACK1(LookOptions, 3);
	lookopt.resizing_rows     <<= THISBACK1(LookOptions, 4);
	lookopt.live_cursor       <<= THISBACK1(LookOptions, 5);
	lookopt.resize_paint_mode <<= THISBACK1(LookOptions, 6);
	lookopt.resize_col_mode   <<= THISBACK1(LookOptions, 7);
	lookopt.resize_row_mode   <<= THISBACK1(LookOptions, 8);
	lookopt.moving_cols       <<= THISBACK1(LookOptions, 9);
	lookopt.moving_rows       <<= THISBACK1(LookOptions, 10);
	lookopt.full_col_resizing <<= THISBACK1(LookOptions, 11);
	lookopt.full_row_resizing <<= THISBACK1(LookOptions, 12);
	lookopt.repaint           <<= THISBACK1(LookOptions, 13);
	lookopt.disable           <<= THISBACK1(LookOptions, 14);
	lookopt.chameleon         <<= THISBACK1(LookOptions, 15);
	lookopt.draw_focus        <<= THISBACK1(LookOptions, 16);

	editopt.multiline         <<= THISBACK1(EditOptions, 0);
	editopt.select_row        <<= THISBACK1(EditOptions, 1);
	editopt.sorting           <<= THISBACK1(EditOptions, 2);
	editopt.multisort         <<= THISBACK1(EditOptions, 3);
	editopt.tab_changes_row   <<= THISBACK1(EditOptions, 4);
	editopt.tab_adds_row      <<= THISBACK1(EditOptions, 5);
	editopt.edit_mode         <<= THISBACK1(EditOptions, 6);
	editopt.one_click_edit    <<= THISBACK1(EditOptions, 7);
	editopt.enter_like_tab    <<= THISBACK1(EditOptions, 8);

	colsopt.theme.Add(-1, "Flat");
	colsopt.theme.Add(0, "Cairo");
	colsopt.theme.Add(1, "Gray");
	colsopt.theme.Add(2, "Plastik");
	colsopt.theme.Add(3, "Lipstik");
	colsopt.theme.Add(4, "Alloy");
	colsopt.theme.Add(5, "Unknown 01");
	colsopt.theme.Add(6, "Default");

	lookopt.resize_paint_mode.Add(0, "Line");
	lookopt.resize_paint_mode.Add(1, "Line + Fixed");
	lookopt.resize_paint_mode.Add(2, "Fixed + NonFixed");

	lookopt.resize_col_mode.Add(0, "Absolute");
	lookopt.resize_col_mode.Add(1, "Proportional");

	lookopt.resize_row_mode.Add(0, "Absolute");
	lookopt.resize_row_mode.Add(1, "Proportional");

	colsopt.theme             <<= THISBACK1(ColorsOptions, 0);
	colsopt.odd_color         <<= THISBACK1(ColorsOptions, 1);
	colsopt.even_color        <<= THISBACK1(ColorsOptions, 2);
	colsopt.odd_even_mode     <<= THISBACK1(ColorsOptions, 3);
	colsopt.grid_color        <<= THISBACK1(ColorsOptions, 4);
	colsopt.focus_color       <<= THISBACK1(ColorsOptions, 5);
	colsopt.live_color        <<= THISBACK1(ColorsOptions, 6);

	colsopt.odd_color.NoRampWheel();
	colsopt.even_color.NoRampWheel();
	colsopt.grid_color.NoRampWheel().NotNull();
	colsopt.focus_color.NoRampWheel();
	colsopt.live_color.NoRampWheel();

	numsopt.total_cols        <<= THISBACK1(Actions, 0);
	numsopt.total_rows        <<= THISBACK1(Actions, 1);
	numsopt.fixed_cols        <<= THISBACK1(Actions, 2);
	numsopt.fixed_rows        <<= THISBACK1(Actions, 3);

	numsopt.total_cols.Disable();

	clear_grid                <<= THISBACK1(Actions, 4);
	reset_grid                <<= THISBACK1(Actions, 5);

	#ifndef flagDEBUG
	debug.Hide();
	level.Hide();
	#else
	clear                     <<= THISBACK1(Actions, 400);
	debug                     <<= THISBACK1(Actions, 401);
	level                     <<= THISBACK1(Actions, 402);
	#endif

	level.Add(0, "All")
	     .Add(1, "1")
	     .Add(2, "2")
	     .Add(3, "3");

	level <<= 0;

	dlog = &log0;
}

void Panel::Init(GridCtrl& g)
{
	grid = &g;

	numsopt.total_cols        <<= grid->total_cols;
	numsopt.total_rows        <<= grid->total_rows;
	numsopt.fixed_cols        <<= grid->fixed_cols;
	numsopt.fixed_rows        <<= grid->fixed_rows;

	lookopt.indicator         <<= grid->indicator;
	lookopt.hgrid             <<= grid->horz_grid;
	lookopt.vgrid             <<= grid->vert_grid;
	lookopt.resizing_cols     <<= grid->resizing_cols;
	lookopt.resizing_rows     <<= grid->resizing_rows;
	lookopt.live_cursor       <<= grid->live_cursor;
	lookopt.moving_cols       <<= grid->moving_cols;
	lookopt.moving_rows       <<= grid->moving_rows;
	lookopt.full_col_resizing <<= grid->full_col_resizing;
	lookopt.full_row_resizing <<= grid->full_row_resizing;
	lookopt.disable           <<= !grid->IsEnabled();
	lookopt.chameleon         <<= grid->chameleon;
	lookopt.draw_focus        <<= grid->draw_focus;

	editopt.multiline         <<= grid->multi_select;
	editopt.select_row        <<= grid->select_row;
	editopt.sorting           <<= grid->sorting;
	editopt.multisort         <<= grid->sorting_multicol;
	editopt.tab_changes_row   <<= grid->tab_changes_row;
	editopt.tab_adds_row      <<= grid->tab_adds_row;
	editopt.edit_mode           = grid->edit_mode;
	editopt.one_click_edit    <<= grid->one_click_edit;

	lookopt.resize_paint_mode <<= grid->resize_paint_mode;
	lookopt.resize_col_mode   <<= grid->resize_col_mode;
	lookopt.resize_row_mode   <<= grid->resize_row_mode;

	colsopt.theme             <<= grid->display->theme;

	colsopt.odd_even_mode     <<= grid->coloring_mode;
	colsopt.odd_color         <<= grid->bg_odd;
	colsopt.even_color        <<= grid->bg_even;
	colsopt.grid_color        <<= grid->fg_grid;
	colsopt.focus_color       <<= grid->bg_focus;
	colsopt.live_color        <<= grid->bg_live;
}

void Panel::LookOptions(int n)
{
	switch(n)
	{
		case 0:	 grid->Indicator(lookopt.indicator);                          break;
		case 1:	 grid->HorzGrid(lookopt.hgrid);                               break;
		case 2:	 grid->VertGrid(lookopt.vgrid);                               break;
		case 3:	 grid->ResizingCols(lookopt.resizing_cols);			          break;
		case 4:	 grid->ResizingRows(lookopt.resizing_rows);			          break;
		case 5:  grid->LiveCursor(lookopt.live_cursor);				          break;
		case 6:	 grid->ResizePaintMode(lookopt.resize_paint_mode.GetIndex()); break;
		case 7:	 grid->ResizeColMode(lookopt.resize_col_mode.GetIndex());     break;
		case 8:  grid->ResizeRowMode(lookopt.resize_row_mode.GetIndex());     break;
		case 9:  grid->MovingCols(lookopt.moving_cols);                       break;
		case 10: grid->MovingRows(lookopt.moving_rows);                       break;
		case 11: grid->FullColResizing(lookopt.full_col_resizing);            break;
		case 12: grid->FullRowResizing(lookopt.full_row_resizing);            break;
		case 13:
			#ifdef flagDEBUG
			Ctrl::ShowRepaint((int) lookopt.repaint ? 20 : 0);
			#endif
			break;

		case 14: grid->Enable(!lookopt.disable);	                          break;
		case 15: grid->Chameleon(lookopt.chameleon);                          break;
		case 16: grid->DrawFocus(lookopt.draw_focus);                         break;
	}
	grid->Repaint();
}

void Panel::ColorsOptions(int n)
{
	switch(n)
	{
		case 0: grid->GetDisplay().SetTheme(~colsopt.theme);                  break;
		case 1: grid->OddColor(SColorText, ~colsopt.odd_color);               break;
		case 2: grid->EvenColor(SColorText, ~colsopt.even_color);             break;
		case 3: grid->ColoringMode(colsopt.odd_even_mode);                    break;
		case 4: grid->GridColor(~colsopt.grid_color);                         break;
		case 5: grid->FocusColor(SColorText, ~colsopt.focus_color);           break;
		case 6: grid->LiveColor(SColorText, ~colsopt.live_color);             break;
	}
	grid->Repaint();
}

void Panel::EditOptions(int n)
{
	switch(n)
	{
		case 0:	grid->MultiSelect(editopt.multiline);                         break;
		case 1:	grid->SelectRow(editopt.select_row);                          break;
		case 2:	grid->Sorting(editopt.sorting);                               break;
		case 3:	grid->MultiSorting(editopt.multisort);                        break;
		case 4:	grid->TabChangesRow(editopt.tab_changes_row);                 break;
		case 5:	grid->TabAddsRow(editopt.tab_adds_row);		                  break;
		case 6: grid->EditMode(editopt.edit_mode);                            break;
		case 7: grid->OneClickEdit(editopt.one_click_edit);                   break;
		case 8: grid->EnterLikeTab(editopt.enter_like_tab);                   break;
	}
	grid->Repaint();
}

void Panel::Actions(int n)
{
	switch(n)
	{
		case 0:
		{
			/*
			int cnt = grid->GetColumnCount();
			if(cnt < numsopt.total_cols)
				grid->AddColumn(numsopt.total_cols - cnt);
			else
				grid->RemoveColumn(cnt - numsopt.total_cols);
			*/
			break;
		}
		case 1:
		{
			int cnt = grid->total_rows;
			if(cnt < numsopt.total_rows)
				grid->Append(numsopt.total_rows - cnt);
			else
				grid->RemoveLast(cnt - numsopt.total_rows);
			break;
		}
		case 2: grid->SetFixedCols(numsopt.fixed_cols); break;
		case 3:	grid->SetFixedRows(numsopt.fixed_rows); break;

		case 4:
			grid->Clear();
			grid->RefreshTop();
			break;
		case 5:
			grid->Reset();
			break;
		case 400:
			log0.Clear();
			break;
		case 401:
			grid->Debug(0);
			break;
		case 402:
			dlev = ~level;
			break;
		case 403:
			grid->ReSort();
			break;
		case 666:
			Close();
	}
	grid->Repaint();
}


text:
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;

namespace Data.Models.Mapping
{
    public class vStoreWithContactMap : EntityTypeConfiguration<vStoreWithContact>
    {
        public vStoreWithContactMap()
        {
            // Primary Key
            this.HasKey(t => new { t.BusinessEntityID, t.Name, t.ContactType, t.FirstName, t.LastName, t.EmailPromotion });

            // Properties
            this.Property(t => t.BusinessEntityID)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

            this.Property(t => t.Name)
                .IsRequired()
                .HasMaxLength(50);

            this.Property(t => t.ContactType)
                .IsRequired()
                .HasMaxLength(50);

            this.Property(t => t.Title)
                .HasMaxLength(8);

            this.Property(t => t.FirstName)
                .IsRequired()
                .HasMaxLength(50);

            this.Property(t => t.MiddleName)
                .HasMaxLength(50);

            this.Property(t => t.LastName)
                .IsRequired()
                .HasMaxLength(50);

            this.Property(t => t.Suffix)
                .HasMaxLength(10);

            this.Property(t => t.PhoneNumber)
                .HasMaxLength(25);

            this.Property(t => t.PhoneNumberType)
                .HasMaxLength(50);

            this.Property(t => t.EmailAddress)
                .HasMaxLength(50);

            this.Property(t => t.EmailPromotion)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

            // Table & Column Mappings
            this.ToTable("vStoreWithContacts", "Sales");
            this.Property(t => t.BusinessEntityID).HasColumnName("BusinessEntityID");
            this.Property(t => t.Name).HasColumnName("Name");
            this.Property(t => t.ContactType).HasColumnName("ContactType");
            this.Property(t => t.Title).HasColumnName("Title");
            this.Property(t => t.FirstName).HasColumnName("FirstName");
            this.Property(t => t.MiddleName).HasColumnName("MiddleName");
            this.Property(t => t.LastName).HasColumnName("LastName");
            this.Property(t => t.Suffix).HasColumnName("Suffix");
            this.Property(t => t.PhoneNumber).HasColumnName("PhoneNumber");
            this.Property(t => t.PhoneNumberType).HasColumnName("PhoneNumberType");
            this.Property(t => t.EmailAddress).HasColumnName("EmailAddress");
            this.Property(t => t.EmailPromotion).HasColumnName("EmailPromotion");
        }
    }
}


text:
// $Id: msp430hardware.h,v 1.31 2008/03/13 14:55:47 vlahan Exp $

// @author Vlado Handziski <handzisk@tkn.tu-berlin.de>
// @author Joe Polastre <polastre@cs.berkeley.edu>
// @author Cory Sharp <cssharp@eecs.berkeley.edu>

#ifndef _H_msp430hardware_h
#define _H_msp430hardware_h

#include <io.h>
#include <signal.h>
#include "msp430regtypes.h"

// define platform constants that can be changed for different compilers
// these are all msp430-gcc specific (add as necessary)

#ifdef __msp430_headers_adc10_h
#define __msp430_have_adc10
#endif

#ifdef __msp430_headers_adc12_h
#define __msp430_have_adc12
#endif

// backwards compatibility to older versions of the header files
#ifdef __MSP430_HAS_I2C__
#define __msp430_have_usart0_with_i2c
#endif

// assign a default DEFAULT_BAUDRATE
#ifndef DEFAULT_BAUDRATE
#define DEFAULT_BAUDRATE 57600
#endif

// CPU memory-mapped register access will cause nesc to issue race condition
// warnings.  Race conditions are a significant conern when accessing CPU
// memory-mapped registers, because they can change even while interrupts
// are disabled.  This means that the standard nesc tools for resolving race
// conditions, atomic statements that disable interrupt handling, do not
// resolve CPU register race conditions.  So, CPU registers access must be
// treated seriously and carefully.

// The macro MSP430REG_NORACE allows individual modules to internally
// redeclare CPU registers as norace, eliminating nesc's race condition
// warnings for their access.  This macro should only be used after the
// specific CPU register use has been verified safe and correct.  Example
// use:
//
//    module MyLowLevelModule
//    {
//      // ...
//    }
//    implementation
//    {
//      MSP430REG_NORACE(TACCTL0);
//      // ...
//    }

#undef norace

#define MSP430REG_NORACE_EXPAND(type,name,addr) \
norace static volatile type name asm(#addr)

#define MSP430REG_NORACE3(type,name,addr) \
MSP430REG_NORACE_EXPAND(type,name,addr)

// MSP430REG_NORACE and MSP430REG_NORACE2 presume naming conventions among
// type, name, and addr, which are defined in the local header
// msp430regtypes.h and mspgcc's header io.h and its children.

#define MSP430REG_NORACE2(rename,name) \
MSP430REG_NORACE3(TYPE_##name,rename,name##_)

#define MSP430REG_NORACE(name) \
MSP430REG_NORACE3(TYPE_##name,name,name##_)

// Avoid the type-punned pointer warnings from gcc 3.3, which are warning about
// creating potentially broken object code.  Union casts are the appropriate work
// around.  Unfortunately, they require a function definiton.
#define DEFINE_UNION_CAST(func_name,to_type,from_type) \
to_type func_name(from_type x) { union {from_type f; to_type t;} c = {f:x}; return c.t; }

// redefine ugly defines from msp-gcc
#ifndef DONT_REDEFINE_SR_FLAGS
#undef C
#undef Z
#undef N
#undef V
#undef GIE
#undef CPUOFF
#undef OSCOFF
#undef SCG0
#undef SCG1
#undef LPM0_bits
#undef LPM1_bits
#undef LPM2_bits
#undef LPM3_bits
#undef LPM4_bits
#define SR_C       0x0001
#define SR_Z       0x0002
#define SR_N       0x0004
#define SR_V       0x0100
#define SR_GIE     0x0008
#define SR_CPUOFF  0x0010
#define SR_OSCOFF  0x0020
#define SR_SCG0    0x0040
#define SR_SCG1    0x0080
#define LPM0_bits           SR_CPUOFF
#define LPM1_bits           SR_SCG0+SR_CPUOFF
#define LPM2_bits           SR_SCG1+SR_CPUOFF
#define LPM3_bits           SR_SCG1+SR_SCG0+SR_CPUOFF
#define LPM4_bits           SR_SCG1+SR_SCG0+SR_OSCOFF+SR_CPUOFF
#endif//DONT_REDEFINE_SR_FLAGS

#ifdef interrupt
#undef interrupt
#endif

#ifdef wakeup
#undef wakeup
#endif

#ifdef signal
#undef signal
#endif

// I2CBusy flag is not defined by current MSP430-GCC
#ifdef __msp430_have_usart0_with_i2c
#ifndef I2CBUSY
#define I2CBUSY   (0x01 << 5)
#endif
MSP430REG_NORACE2(U0CTLnr,U0CTL);
MSP430REG_NORACE2(I2CTCTLnr,I2CTCTL);
MSP430REG_NORACE2(I2CDCTLnr,I2CDCTL);
#endif

// The signal attribute has opposite meaning in msp430-gcc than in avr-gcc
#define TOSH_SIGNAL(signame) \
void sig_##signame() __attribute__((interrupt (signame), wakeup, C))

// TOSH_INTERRUPT allows nested interrupts
#define TOSH_INTERRUPT(signame) \
void isr_##signame() __attribute__((interrupt (signame), signal, wakeup, C))

inline void TOSH_wait(void)
{
  nop(); nop();
}

#define TOSH_CYCLE_TIME_NS 250

inline void TOSH_wait_250ns(void)
{
  // 4 MHz clock == 1 cycle per 250 ns
  nop();
}

inline void TOSH_uwait(uint16_t u)
{
  uint16_t i;
  if (u < 500)
    for (i=2; i < u; i++) {
      asm volatile("nop\n\t"
                   "nop\n\t"
                   "nop\n\t"
                   "nop\n\t"
                   ::);
    }
  else
    for (i=0; i < u; i++) {
      asm volatile("nop\n\t"
                   "nop\n\t"
                   "nop\n\t"
                   "nop\n\t"
                   ::);
    }

}

void __nesc_disable_interrupt()
{
  dint();
  nop();
}

void __nesc_enable_interrupt()
{
  eint();
}

bool are_interrupts_enabled()
{
  return ((READ_SR & SR_GIE) != 0);
}

typedef bool __nesc_atomic_t;

__nesc_atomic_t __nesc_atomic_start(void);
void __nesc_atomic_end(__nesc_atomic_t oldSreg);

#ifndef NESC_BUILD_BINARY

__nesc_atomic_t __nesc_atomic_start(void)
{
  __nesc_atomic_t result = are_interrupts_enabled();
  __nesc_disable_interrupt();
  return result;
}

void __nesc_atomic_end( __nesc_atomic_t reenable_interrupts )
{
  if( reenable_interrupts )
    __nesc_enable_interrupt();
}

#endif

//Variable to keep track if Low Power Modes shoud not be used
norace bool LPMode_disabled = FALSE;

void LPMode_enable() {
  LPMode_disabled = FALSE;
}

void LPMode_disable() {
  LPMode_disabled = TRUE;
}

inline void __nesc_atomic_sleep() {
  // The LPM we can go down to depends on the clocks used. We never go
  // below LPM3, so ACLK is always enabled, also TimerB clock source
  // is assumed to be ACLK.
  // We check MSP430's TimerA, USART0/1, ADC12 peripheral modules if they
  // use MCLK or SMCLK and switch to the lowest LPM that keeps
  // the required clock(s) running.
  extern uint8_t TOSH_sched_full;
  extern volatile uint8_t TOSH_sched_free;
  uint16_t LPMode_bits = 0;

  if (LPMode_disabled) {
    __nesc_enable_interrupt();
    return;
  }
  else {
    LPMode_bits = LPM3_bits;
    // TimerA, USART0, USART1 check
    if ( (((TACCTL0 & CCIE) || (TACCTL1 & CCIE) || (TACCTL2 & CCIE)) && ((TACTL & TASSEL_3) == TASSEL_2)) ||
         ((ME1 & (UTXE0 | URXE0)) && (U0TCTL & SSEL1)) ||
         ((ME2 & (UTXE1 | URXE1)) && (U1TCTL & SSEL1))

#ifdef __msp430_have_usart0_with_i2c
         // registers end in "nr" to prevent nesC race condition detection
         || ( (U0CTLnr & I2CEN) && (I2CTCTLnr & SSEL1) &&
              (I2CDCTLnr & I2CBUSY) && (U0CTLnr & SYNC) &&
              (U0CTLnr & I2C)
            )
#endif
       )
      LPMode_bits = LPM1_bits;
#ifdef __msp430_have_adc12
    // ADC12 check
    if (ADC12CTL1 & ADC12BUSY){
      if (!(ADC12CTL0 & MSC) && ((TACTL & TASSEL_3) == TASSEL_2))
        LPMode_bits = LPM1_bits; // TimerA for ADC12
      else
        switch (ADC12CTL1 & ADC12SSEL_3){
          case ADC12SSEL_2: LPMode_bits = 0; break;
          case ADC12SSEL_3: LPMode_bits = LPM1_bits; break;
        }
    }
#endif
    LPMode_bits |= SR_GIE;
    __asm__ __volatile__( "bis  %0, r2" : : "m" ((uint16_t)LPMode_bits) );
  }
}

#define SET_FLAG(port, flag) ((port) |= (flag))
#define CLR_FLAG(port, flag) ((port) &= ~(flag))
#define READ_FLAG(port, flag) ((port) & (flag))

// TOSH_ASSIGN_PIN creates functions that are effectively marked as
// "norace".  This means race conditions that result from their use will not
// be detectde by nesc.

#define TOSH_ASSIGN_PIN_HEX(name, port, hex) \
void TOSH_SET_##name##_PIN() { MSP430REG_NORACE2(r,P##port##OUT); r |= hex; } \
void TOSH_CLR_##name##_PIN() { MSP430REG_NORACE2(r,P##port##OUT); r &= ~hex; } \
void TOSH_TOGGLE_##name##_PIN() { MSP430REG_NORACE2(r,P##port##OUT); r ^= hex; } \
uint8_t TOSH_READ_##name##_PIN() { MSP430REG_NORACE2(r,P##port##IN); return (r & hex); } \
void TOSH_MAKE_##name##_OUTPUT() { MSP430REG_NORACE2(r,P##port##DIR); r |= hex; } \
void TOSH_MAKE_##name##_INPUT() { MSP430REG_NORACE2(r,P##port##DIR); r &= ~hex; } \
void TOSH_SEL_##name##_MODFUNC() { MSP430REG_NORACE2(r,P##port##SEL); r |= hex; } \
void TOSH_SEL_##name##_IOFUNC() { MSP430REG_NORACE2(r,P##port##SEL); r &= ~hex; } \
bool TOSH_IS_##name##_MODFUNC() { MSP430REG_NORACE2(r,P##port##SEL); return (r & hex); } \
bool TOSH_IS_##name##_IOFUNC() { MSP430REG_NORACE2(r,P##port##SEL); return (r | ~hex); }

#define TOSH_ASSIGN_PIN(name, port, bit) \
TOSH_ASSIGN_PIN_HEX(name,port,(1<<(bit)))

#include "MSP430GeneralIO.h"

#endif//_H_msp430hardware_h


text:
using std::vector;
using std::fopen;
using std::ftell;
using std::fclose;
using std::printf;

#pragma once
#pragma comment(lib, "xaudio2.lib")

typedef struct {
  uint8_t  s_riff[4];
  uint32_t ul_file_size;
  uint8_t  s_wave[4];
} WAVE_HEAD;

typedef struct {
  uint8_t  s_id[4];
  uint32_t ul_chunk_size;
} WAVE_CHUNK;

typedef struct : WAVE_CHUNK {
  uint16_t un_format_id;
  uint16_t un_channel_count;
  uint32_t ul_sampling_rate;
  uint32_t ul_byte_per_sec;
  uint16_t un_block_size;
  uint16_t un_bit_rate;
} WAVE_FORMAT;

class CWaveLoader {

private:
  WAVEFORMATEX   m_tag_wave_format_ex;
  vector<char>   m_vsz_file_name;
  vector<int8_t> m_vs_sound_data;
  FILE*          m_fp;
  bool           m_is_file_opening;
  unsigned long  m_ul_data_size;

public:
  CWaveLoader();
  CWaveLoader(char* sz_file_name);
  virtual ~CWaveLoader();

public:
  bool LoadWaveData();

private:
  void OpenFile(char* sz_file_name);
  void CloseFile();
  bool CheckWaveHeader();
  bool GetWaveFormat();
  bool GetWaveData();
  void InitializeObjects();
  void DeleteObjects();

public:
  bool           GetFileOpenState() { return m_is_file_opening; }
  vector<int8_t> GetSoundData()     { return m_vs_sound_data; }
  WAVEFORMATEX   GetSoundFormat()   { return m_tag_wave_format_ex; }
};