<commit_before>#include <UtH/Engine/Physics/Rigidbody.hpp>
#include <UtH/Engine/GameObject.hpp>
#include <UtH/Platform/Debug.hpp>

// Helper functions
////////////////////////////////////
b2Vec2 umathToBox2D(const pmath::Vec2& vec);
pmath::Vec2 box2DToUmath(const b2Vec2& vec);
////////////////////////////////////

using namespace uth;

Rigidbody::Rigidbody(PhysicsWorld& world, const COLLIDER_TYPE collider, const std::string& name)
	: Component(name),
	  m_world(world.GetBox2dWorldObject()),
	  m_collider(collider)
{
	defaults();
}

Rigidbody::Rigidbody(PhysicsWorld& world, const COLLIDER_TYPE collider, const pmath::Vec2& size, const std::string& name)
	: Component(name),
	  m_world(world.GetBox2dWorldObject()),
	  m_collider(collider),
	  m_size(size)
{
	defaults();
}

Rigidbody::~Rigidbody()
{
    if (m_body != nullptr && !m_world.expired())
        m_world.lock()->DestroyBody(m_body);
}

// Public

void Rigidbody::Init()
{
	init();
}

void Rigidbody::Update(float)
{
	const float angDegrees = GetAngle();
	parent->transform.SetRotation(angDegrees);

	b2Vec2 pos = m_body->GetPosition();
	pmath::Vec2 tpos(pos.x, pos.y);
	tpos *= PIXELS_PER_METER;
	parent->transform.SetPosition(tpos);
}

// Apply forces

void Rigidbody::ApplyForce(const pmath::Vec2& force)
{
	m_body->ApplyForceToCenter(umathToBox2D(force), true);
}

void Rigidbody::ApplyForce(const pmath::Vec2& force, const pmath::Vec2& point)
{
	b2Vec2 p = umathToBox2D(point / PIXELS_PER_METER) + m_body->GetPosition();
	m_body->ApplyForce(umathToBox2D(force), p, true);
}

void Rigidbody::ApplyImpulse(const pmath::Vec2& impulse)
{
	m_body->ApplyLinearImpulse(umathToBox2D(impulse), m_body->GetPosition(), true);
}

void Rigidbody::ApplyImpulse(const pmath::Vec2& impulse, const pmath::Vec2& point)
{
	b2Vec2 p = umathToBox2D(point / PIXELS_PER_METER) + m_body->GetPosition();
	m_body->ApplyLinearImpulse(umathToBox2D(impulse), p, true);
}

void Rigidbody::ApplyTorque(const float torque)
{
	m_body->ApplyTorque(-torque, true);
}

// Setters/Getters

void Rigidbody::SetVelocity(const pmath::Vec2& velocity)
{
	m_body->SetLinearVelocity(umathToBox2D(velocity));
}

const pmath::Vec2 Rigidbody::GetVelocity() const
{
	return box2DToUmath(m_body->GetLinearVelocity());
}

void Rigidbody::SetAngularVelocity(float velocity)
{
	m_body->SetAngularVelocity(velocity);
}

float Rigidbody::GetAngularVelocity() const
{
	return m_body->GetAngularVelocity();
}

void Rigidbody::SetSize(const pmath::Vec2& size)
{
	SetUnitSize(size / PIXELS_PER_METER);
}

void Rigidbody::SetUnitSize(const pmath::Vec2& size)
{
	// This function is kinda ugly but what can you do

	if(m_body->GetFixtureList()->GetType() != b2Shape::e_polygon)
	{
		WriteWarning("Calling SetSize(vec2 size) on a ball. Size not updated");
		return;
	}

	// Remove original fixture
	m_body->DestroyFixture(m_body->GetFixtureList());

	//WriteLog("x: %f,y: %f\n", size.x, size.y);

	b2PolygonShape box;
	box.SetAsBox(size.x, size.y);
	m_fixtureDef.shape = &box;
	m_body->CreateFixture(&m_fixtureDef);
	m_size = size;
}

void Rigidbody::SetSize(const float radius)
{
	SetUnitSize(radius / PIXELS_PER_METER);
}

void Rigidbody::SetUnitSize(const float radius)
{
	// This might be even more ugly

	if(m_fixtureDef.shape->GetType() != b2Shape::e_circle)
	{
		WriteWarning("Calling SetSize(float radius) on a box. Size not updated");
		return;
	}

	// Remove original fixture
	m_body->DestroyFixture(m_body->GetFixtureList());

	b2CircleShape circle;
	circle.m_radius = radius;
	m_fixtureDef.shape = &circle;
	m_body->CreateFixture(&m_fixtureDef);
	m_size.x = radius*2;
	m_size.y = radius*2;
}

const pmath::Vec2 Rigidbody::GetSize()
{
	return m_size * PIXELS_PER_METER;
}

const pmath::Vec2 Rigidbody::GetUnitSize()
{
	return m_size;
}

void Rigidbody::SetPosition(const pmath::Vec2& position)
{
	b2Vec2 p = umathToBox2D(position / PIXELS_PER_METER);
	m_body->SetTransform(p, m_body->GetAngle());
}

const pmath::Vec2 Rigidbody::GetPosition()
{
	b2Vec2 pos = m_body->GetPosition();
	pos *= PIXELS_PER_METER;
	return box2DToUmath(pos);
}

void Rigidbody::SetAngle(const float angle)
{
	float ang = -angle * static_cast<float>(pmath::pi) / 180.f;
	m_body->SetTransform(m_body->GetPosition(), ang);
}

float Rigidbody::GetAngle() const
{
	return -m_body->GetAngle() * 180.f / static_cast<float>(pmath::pi);
}

void Rigidbody::SetFixedRotation(bool value)
{
	m_body->SetFixedRotation(value);
}

void Rigidbody::SetDensity(float density)
{
	m_body->GetFixtureList()->SetDensity(density);
	m_body->ResetMassData();
}

float Rigidbody::GetDensity() const
{
	return m_body->GetFixtureList()->GetDensity();
}

void Rigidbody::SetFriction(float friction)
{
	m_body->GetFixtureList()->SetFriction(friction);
}

float Rigidbody::GetFriction() const
{
	return m_body->GetFixtureList()->GetFriction();
}

void Rigidbody::SetActive(bool value)
{
	m_body->SetActive(value);
	m_active = value;
}

const bool Rigidbody::IsAwake() const
{
	return m_body->IsAwake();
}

void Rigidbody::SetBullet(bool value)
{
	m_body->SetBullet(value);
}

const bool Rigidbody::IsBullet() const
{
	return m_body->IsBullet();
}

void Rigidbody::SetKinematic(bool value)
{
	value ? m_body->SetType(b2_kinematicBody) : m_body->SetType(b2_dynamicBody);
}

// Private

void Rigidbody::defaults()
{
	m_body = nullptr;
}

void Rigidbody::init()
{
	b2BodyDef bodyDef;
	bodyDef.type = b2_dynamicBody;
	pmath::Vec2 pos = parent->transform.GetPosition();
	pos /= PIXELS_PER_METER;
	bodyDef.position.Set(pos.x, pos.y);

	m_body = m_world.lock()->CreateBody(&bodyDef);
	m_body->SetUserData(parent);

	if(!(m_size.lengthSquared() > 0))
		m_size = parent->transform.GetSize();

	m_size /= PIXELS_PER_METER;

	switch(m_collider)
	{
	case COLLIDER_BOX:
		{
		b2PolygonShape dynamicBox;
		dynamicBox.SetAsBox(m_size.x/2, m_size.y/2);

		m_fixtureDef.shape = &dynamicBox;
		m_fixtureDef.density = 1.0f;
		m_fixtureDef.friction = 0.3f;
		m_body->CreateFixture(&m_fixtureDef);
		}
		break;
	case COLLIDER_BALL:
		{
		b2CircleShape circleShape;
		circleShape.m_radius = m_size.x/2;

		m_fixtureDef.shape = &circleShape;
		m_fixtureDef.density = 1.0f;
		m_fixtureDef.friction = 0.3f;
		m_body->CreateFixture(&m_fixtureDef);
		}
		break;
	default:
		WriteError("Collider type undefined\nThis is probably bad");
		break;
	}
}

void Rigidbody::SetRestitution(float restitution)
{
	m_body->GetFixtureList()->SetRestitution(restitution);
}

float uth::Rigidbody::GetRestitution() const
{
	return m_body->GetFixtureList()->GetRestitution();
}

b2Vec2 umathToBox2D(const pmath::Vec2& vec)
{
	return b2Vec2(vec.x, vec.y);
}

pmath::Vec2 box2DToUmath(const b2Vec2& vec)
{
	return pmath::Vec2(vec.x, vec.y);
}<commit_msg>Rigidbody takes scale into account during init<commit_after>#include <UtH/Engine/Physics/Rigidbody.hpp>
#include <UtH/Engine/GameObject.hpp>
#include <UtH/Platform/Debug.hpp>

// Helper functions
////////////////////////////////////
b2Vec2 umathToBox2D(const pmath::Vec2& vec);
pmath::Vec2 box2DToUmath(const b2Vec2& vec);
////////////////////////////////////

using namespace uth;

Rigidbody::Rigidbody(PhysicsWorld& world, const COLLIDER_TYPE collider, const std::string& name)
	: Component(name),
	  m_world(world.GetBox2dWorldObject()),
	  m_collider(collider)
{
	defaults();
}

Rigidbody::Rigidbody(PhysicsWorld& world, const COLLIDER_TYPE collider, const pmath::Vec2& size, const std::string& name)
	: Component(name),
	  m_world(world.GetBox2dWorldObject()),
	  m_collider(collider),
	  m_size(size)
{
	defaults();
}

Rigidbody::~Rigidbody()
{
    if (m_body != nullptr && !m_world.expired())
        m_world.lock()->DestroyBody(m_body);
}

// Public

void Rigidbody::Init()
{
	init();
}

void Rigidbody::Update(float)
{
	const float angDegrees = GetAngle();
	parent->transform.SetRotation(angDegrees);

	b2Vec2 pos = m_body->GetPosition();
	pmath::Vec2 tpos(pos.x, pos.y);
	tpos *= PIXELS_PER_METER;
	parent->transform.SetPosition(tpos);
}

// Apply forces

void Rigidbody::ApplyForce(const pmath::Vec2& force)
{
	m_body->ApplyForceToCenter(umathToBox2D(force), true);
}

void Rigidbody::ApplyForce(const pmath::Vec2& force, const pmath::Vec2& point)
{
	b2Vec2 p = umathToBox2D(point / PIXELS_PER_METER) + m_body->GetPosition();
	m_body->ApplyForce(umathToBox2D(force), p, true);
}

void Rigidbody::ApplyImpulse(const pmath::Vec2& impulse)
{
	m_body->ApplyLinearImpulse(umathToBox2D(impulse), m_body->GetPosition(), true);
}

void Rigidbody::ApplyImpulse(const pmath::Vec2& impulse, const pmath::Vec2& point)
{
	b2Vec2 p = umathToBox2D(point / PIXELS_PER_METER) + m_body->GetPosition();
	m_body->ApplyLinearImpulse(umathToBox2D(impulse), p, true);
}

void Rigidbody::ApplyTorque(const float torque)
{
	m_body->ApplyTorque(-torque, true);
}

// Setters/Getters

void Rigidbody::SetVelocity(const pmath::Vec2& velocity)
{
	m_body->SetLinearVelocity(umathToBox2D(velocity));
}

const pmath::Vec2 Rigidbody::GetVelocity() const
{
	return box2DToUmath(m_body->GetLinearVelocity());
}

void Rigidbody::SetAngularVelocity(float velocity)
{
	m_body->SetAngularVelocity(velocity);
}

float Rigidbody::GetAngularVelocity() const
{
	return m_body->GetAngularVelocity();
}

void Rigidbody::SetSize(const pmath::Vec2& size)
{
	SetUnitSize(size / PIXELS_PER_METER);
}

void Rigidbody::SetUnitSize(const pmath::Vec2& size)
{
	// This function is kinda ugly but what can you do

	if(m_body->GetFixtureList()->GetType() != b2Shape::e_polygon)
	{
		WriteWarning("Calling SetSize(vec2 size) on a ball. Size not updated");
		return;
	}

	// Remove original fixture
	m_body->DestroyFixture(m_body->GetFixtureList());

	//WriteLog("x: %f,y: %f\n", size.x, size.y);

	b2PolygonShape box;
	box.SetAsBox(size.x, size.y);
	m_fixtureDef.shape = &box;
	m_body->CreateFixture(&m_fixtureDef);
	m_size = size;
}

void Rigidbody::SetSize(const float radius)
{
	SetUnitSize(radius / PIXELS_PER_METER);
}

void Rigidbody::SetUnitSize(const float radius)
{
	// This might be even more ugly

	if(m_fixtureDef.shape->GetType() != b2Shape::e_circle)
	{
		WriteWarning("Calling SetSize(float radius) on a box. Size not updated");
		return;
	}

	// Remove original fixture
	m_body->DestroyFixture(m_body->GetFixtureList());

	b2CircleShape circle;
	circle.m_radius = radius;
	m_fixtureDef.shape = &circle;
	m_body->CreateFixture(&m_fixtureDef);
	m_size.x = radius*2;
	m_size.y = radius*2;
}

const pmath::Vec2 Rigidbody::GetSize()
{
	return m_size * PIXELS_PER_METER;
}

const pmath::Vec2 Rigidbody::GetUnitSize()
{
	return m_size;
}

void Rigidbody::SetPosition(const pmath::Vec2& position)
{
	b2Vec2 p = umathToBox2D(position / PIXELS_PER_METER);
	m_body->SetTransform(p, m_body->GetAngle());
}

const pmath::Vec2 Rigidbody::GetPosition()
{
	b2Vec2 pos = m_body->GetPosition();
	pos *= PIXELS_PER_METER;
	return box2DToUmath(pos);
}

void Rigidbody::SetAngle(const float angle)
{
	float ang = -angle * static_cast<float>(pmath::pi) / 180.f;
	m_body->SetTransform(m_body->GetPosition(), ang);
}

float Rigidbody::GetAngle() const
{
	return -m_body->GetAngle() * 180.f / static_cast<float>(pmath::pi);
}

void Rigidbody::SetFixedRotation(bool value)
{
	m_body->SetFixedRotation(value);
}

void Rigidbody::SetDensity(float density)
{
	m_body->GetFixtureList()->SetDensity(density);
	m_body->ResetMassData();
}

float Rigidbody::GetDensity() const
{
	return m_body->GetFixtureList()->GetDensity();
}

void Rigidbody::SetFriction(float friction)
{
	m_body->GetFixtureList()->SetFriction(friction);
}

float Rigidbody::GetFriction() const
{
	return m_body->GetFixtureList()->GetFriction();
}

void Rigidbody::SetActive(bool value)
{
	m_body->SetActive(value);
	m_active = value;
}

const bool Rigidbody::IsAwake() const
{
	return m_body->IsAwake();
}

void Rigidbody::SetBullet(bool value)
{
	m_body->SetBullet(value);
}

const bool Rigidbody::IsBullet() const
{
	return m_body->IsBullet();
}

void Rigidbody::SetKinematic(bool value)
{
	value ? m_body->SetType(b2_kinematicBody) : m_body->SetType(b2_dynamicBody);
}

// Private

void Rigidbody::defaults()
{
	m_body = nullptr;
}

void Rigidbody::init()
{
	b2BodyDef bodyDef;
	bodyDef.type = b2_dynamicBody;
	pmath::Vec2 pos = parent->transform.GetPosition();
	pos /= PIXELS_PER_METER;
	bodyDef.position.Set(pos.x, pos.y);

	m_body = m_world.lock()->CreateBody(&bodyDef);
	m_body->SetUserData(parent);

    if (!(m_size.lengthSquared() > 0))
    {
        m_size = parent->transform.GetSize();
        m_size.scale(parent->transform.GetScale());
    }

	m_size /= PIXELS_PER_METER;

	switch(m_collider)
	{
	case COLLIDER_BOX:
		{
		b2PolygonShape dynamicBox;
		dynamicBox.SetAsBox(m_size.x/2, m_size.y/2);

		m_fixtureDef.shape = &dynamicBox;
		m_fixtureDef.density = 1.0f;
		m_fixtureDef.friction = 0.3f;
		m_body->CreateFixture(&m_fixtureDef);
		}
		break;
	case COLLIDER_BALL:
		{
		b2CircleShape circleShape;
		circleShape.m_radius = m_size.x/2;

		m_fixtureDef.shape = &circleShape;
		m_fixtureDef.density = 1.0f;
		m_fixtureDef.friction = 0.3f;
		m_body->CreateFixture(&m_fixtureDef);
		}
		break;
	default:
		WriteError("Collider type undefined\nThis is probably bad");
		break;
	}
}

void Rigidbody::SetRestitution(float restitution)
{
	m_body->GetFixtureList()->SetRestitution(restitution);
}

float uth::Rigidbody::GetRestitution() const
{
	return m_body->GetFixtureList()->GetRestitution();
}

b2Vec2 umathToBox2D(const pmath::Vec2& vec)
{
	return b2Vec2(vec.x, vec.y);
}

pmath::Vec2 box2DToUmath(const b2Vec2& vec)
{
	return pmath::Vec2(vec.x, vec.y);
}<|endoftext|>


<commit_before>#include "sample/view/mrt_view.h"

#include "basic/obj/basic_camera.h"
#include "basic/obj/basic_light.h"
#include "basic/obj/simple_object.h"
#include "basic/mgr/basic_light_mgr.h"
#include "basic/mgr/basic_texture_mgr.h"
#include "basic/mgr/basic_shader_mgr.h"

using namespace std;

#define MRT_WIDTH 480
#define MRT_HEIGHT 688

#define SH_MRT "sh_mrt"
#define SH_DRAW "sh_draw"

class MrtRenderer : public BasicRenderer {
private:
	GLuint mMrtFbo;
	GLuint mRenderBuffer;

public:

	MrtRenderer() :
			mMrtFbo(0),
			mRenderBuffer(0)
	{}

	virtual ~MrtRenderer() {}

	void InitFbo(GLuint* texIds) {
		GLenum none = GL_NONE;
		glGenRenderbuffers(1, &mRenderBuffer);
		check_gl_error("glGenRenderbuffers");
		glBindRenderbuffer(GL_RENDERBUFFER, mRenderBuffer);
		check_gl_error("glBindRenderbuffer");
		glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, MRT_WIDTH, MRT_HEIGHT);
		check_gl_error("glRenderbufferStorage");

		glGenFramebuffers(1, &mMrtFbo);
		check_gl_error("glGenFramebuffers");

		glBindFramebuffer(GL_FRAMEBUFFER, mMrtFbo);
		check_gl_error("glBindFramebuffer");

		glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, mRenderBuffer);

		for(unsigned int i=0; i<4 ;i++) {
			glBindTexture(GL_TEXTURE_2D, texIds[i]);
			glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER,
								   GL_COLOR_ATTACHMENT0 + i,
								GL_TEXTURE_2D, texIds[i], 0);
			glBindTexture(GL_TEXTURE_2D, 0);
			check_gl_error("glFramebufferTexture2D");

		}
		LOGI("texid [%d, %d, %d, %d]", texIds[0],texIds[1],texIds[2],texIds[3]);

		GLenum DrawBuffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 };
		glDrawBuffers(4, DrawBuffers);

		// Check FBO is ready to draw
		if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
			LOGE("FrameBufferObject is not complete!");
		}

		glBindRenderbuffer(GL_RENDERBUFFER, 0);
		glBindFramebuffer(GL_FRAMEBUFFER, 0);

	}

	virtual void RenderFrame() {
		ComputeTick();

		glBindFramebuffer(GL_FRAMEBUFFER, mMrtFbo);
		glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
		Shader_Mgr.DrawObjects(SH_MRT);

		glBindFramebuffer(GL_FRAMEBUFFER, 0);
		glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
		glDisable(GL_CULL_FACE);
		Shader_Mgr.DrawObjects(SH_DRAW);
		glEnable(GL_CULL_FACE);

	}

};

MrtView::MrtView(void *data) : SampleView(data, false) {
	mViewRenderer = new MrtRenderer();

}

void MrtView::OnInit() {
	string mrt_vs = File_Loader.ReadFileToString("shader/view_mrt/mrt.vs");
	string mrt_fs = File_Loader.ReadFileToString("shader/view_mrt/mrt.fs");
	string draw_vs = File_Loader.ReadFileToString("shader/view_mrt/draw.vs");
	string draw_fs = File_Loader.ReadFileToString("shader/view_mrt/draw.fs");

	BasicMap<MaterialObj_U_Elem> mo_uniforms;
	mo_uniforms.mList[MTL_U_MAT_WORLD] = "worldMat";
	mo_uniforms.mList[MTL_U_CAMERA_VIEW] = "viewMat";
	mo_uniforms.mList[MTL_U_CAMERA_PROJ] = "projMat";
	mo_uniforms.mList[MTL_U_CAMERA_POS] = "eyePos";
	mo_uniforms.mList[MTL_U_MAT_SHINESS] = "materialSh";

	BasicMap<PointLt_U_Elem> lt_uniforms;
	lt_uniforms.mList[U_PL_DIFFUSE] = "sourceDiff";
	lt_uniforms.mList[U_PL_AMBIENT] = "sourceAmbi";
	lt_uniforms.mList[U_PL_SPECULAR] = "sourceSpec";
	lt_uniforms.mList[U_PL_POS] = "lightPos";

	mViewRenderer->GetNewObject(MATERIAL_OBJ, "chess", mo_uniforms)
			->ImportObj("obj3d/chess_tri", 2.0f)
			->AttachShader(mrt_vs, mrt_fs, SH_MRT)
			->AttachLight(POINT_LT, "point_light_1", lt_uniforms);

	Light_Mgr.GetLight("point_light_1")->mPosition = glm::vec3(0, 5.0f, 0);

	mViewRenderer->OffAutoRotate();

	mViewRenderer->GetCamera()->SetEye(glm::vec3(-15, 15, 15));

	TexProp texDiff(TEX_2D_PTR);
	texDiff.SetData("tex_diff", MRT_WIDTH, MRT_HEIGHT, GL_RGB, GL_RGB8, GL_UNSIGNED_BYTE);
	texDiff.SetPointer(nullptr);
	texDiff.SetFilter();

	TexProp texDraw(TEX_2D_PTR);
	texDraw.SetData("tex_draw", MRT_WIDTH, MRT_HEIGHT, GL_RGB, GL_RGB8, GL_UNSIGNED_BYTE);
	texDraw.SetPointer(nullptr);
	texDraw.SetFilter();

	TexProp texAmbi(TEX_2D_PTR);
	texAmbi.SetData("tex_ambi", MRT_WIDTH, MRT_HEIGHT, GL_RGB, GL_RGB8, GL_UNSIGNED_BYTE);
	texAmbi.SetPointer(nullptr);
	texAmbi.SetFilter();

	TexProp texAttn(TEX_2D_PTR);
	texAttn.SetData("tex_attn", MRT_WIDTH, MRT_HEIGHT, GL_RGB, GL_RGB8, GL_UNSIGNED_BYTE);
	texAttn.SetPointer(nullptr);
	texAttn.SetFilter();

	BasicObject *obj;

	obj = mViewRenderer->GetNewObject(SIMPLE_OBJ, "diff", mo_uniforms)
			->AttachShader(draw_vs, draw_fs, SH_DRAW)
			->AttachTexture(texDiff, "s_tex");
	dynamic_cast<SimpleObject *>(obj)->Init(glm::vec2(0));

	obj = mViewRenderer->GetNewObject(SIMPLE_OBJ, "spec", mo_uniforms)
			->AttachShader(draw_vs, draw_fs, SH_DRAW)
			->AttachTexture(texDraw, "s_tex");
	dynamic_cast<SimpleObject *>(obj)->Init(glm::vec2(-1.0, 0));
	obj = mViewRenderer->GetNewObject(SIMPLE_OBJ, "ambi", mo_uniforms)
			->AttachShader(draw_vs, draw_fs, SH_DRAW)
			->AttachTexture(texAmbi, "s_tex");
	dynamic_cast<SimpleObject *>(obj)->Init(glm::vec2(0, -1.0));
	obj = mViewRenderer->GetNewObject(SIMPLE_OBJ, "attn", mo_uniforms)
			->AttachShader(draw_vs, draw_fs, SH_DRAW)
			->AttachTexture(texAttn, "s_tex");
	dynamic_cast<SimpleObject *>(obj)->Init(glm::vec2(-1.0, -1.0));

	GLuint texIds[4];
	texIds[0] = Texture_Mgr.GetTextureId("tex_diff");
	texIds[1] = Texture_Mgr.GetTextureId("tex_draw");
	texIds[2] = Texture_Mgr.GetTextureId("tex_ambi");
	texIds[3] = Texture_Mgr.GetTextureId("tex_attn");
	LOGI("texid [%d, %d, %d, %d]", texIds[0],texIds[1],texIds[2],texIds[3]);

	mViewRenderer->SetCurrShader(SH_DRAW);

	dynamic_cast<MrtRenderer *>(mViewRenderer)->InitFbo(texIds);

}

<commit_msg>resolve resolution issue<commit_after>#include "sample/view/mrt_view.h"

#include "basic/mgr/basic_light_mgr.h"
#include "basic/mgr/basic_texture_mgr.h"
#include "basic/mgr/basic_shader_mgr.h"

#include "basic/obj/basic_camera.h"
#include "basic/obj/basic_light.h"
#include "basic/obj/simple_object.h"

using namespace std;

#define SH_MRT "sh_mrt"
#define SH_DRAW "sh_draw"

class MrtRenderer : public BasicRenderer {
private:
	GLuint mMrtFbo;
	GLuint mRenderBuffer;

public:
	MrtRenderer() :
			mMrtFbo(0),
			mRenderBuffer(0), BasicRenderer() {}

	virtual ~MrtRenderer() {}

	void InitFbo(GLuint* texIds) {
		GLenum none = GL_NONE;
		glGenRenderbuffers(1, &mRenderBuffer);
		check_gl_error("glGenRenderbuffers");
		glBindRenderbuffer(GL_RENDERBUFFER, mRenderBuffer);
		check_gl_error("glBindRenderbuffer");
		glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, mWidth, mHeight);
		check_gl_error("glRenderbufferStorage");

		glGenFramebuffers(1, &mMrtFbo);
		check_gl_error("glGenFramebuffers");

		glBindFramebuffer(GL_FRAMEBUFFER, mMrtFbo);
		check_gl_error("glBindFramebuffer");

		glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, mRenderBuffer);

		for(unsigned int i=0; i<4 ;i++) {
			glBindTexture(GL_TEXTURE_2D, texIds[i]);
			glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER,
								   GL_COLOR_ATTACHMENT0 + i,
								GL_TEXTURE_2D, texIds[i], 0);
			glBindTexture(GL_TEXTURE_2D, 0);
			check_gl_error("glFramebufferTexture2D");

		}
		LOGI("texid [%d, %d, %d, %d]", texIds[0],texIds[1],texIds[2],texIds[3]);

		GLenum DrawBuffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 };
		glDrawBuffers(4, DrawBuffers);

		// Check FBO is ready to draw
		if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
			LOGE("FrameBufferObject is not complete!");
		}

		glBindRenderbuffer(GL_RENDERBUFFER, 0);
		glBindFramebuffer(GL_FRAMEBUFFER, 0);

	}

	virtual void RenderFrame() {
		ComputeTick();

		glBindFramebuffer(GL_FRAMEBUFFER, mMrtFbo);
		glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
		Shader_Mgr.DrawObjects(SH_MRT);

		glBindFramebuffer(GL_FRAMEBUFFER, 0);
		glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
		glDisable(GL_CULL_FACE);
		Shader_Mgr.DrawObjects(SH_DRAW);
		glEnable(GL_CULL_FACE);

	}

};

MrtView::MrtView(void *data) : SampleView(data, false) {
	mViewRenderer = new MrtRenderer();

}

void MrtView::OnInit() {
	string mrt_vs = File_Loader.ReadFileToString("shader/view_mrt/mrt.vs");
	string mrt_fs = File_Loader.ReadFileToString("shader/view_mrt/mrt.fs");
	string draw_vs = File_Loader.ReadFileToString("shader/view_mrt/draw.vs");
	string draw_fs = File_Loader.ReadFileToString("shader/view_mrt/draw.fs");

	BasicMap<MaterialObj_U_Elem> mo_uniforms;
	mo_uniforms.mList[MTL_U_MAT_WORLD] = "worldMat";
	mo_uniforms.mList[MTL_U_CAMERA_VIEW] = "viewMat";
	mo_uniforms.mList[MTL_U_CAMERA_PROJ] = "projMat";
	mo_uniforms.mList[MTL_U_CAMERA_POS] = "eyePos";
	mo_uniforms.mList[MTL_U_MAT_SHINESS] = "materialSh";

	BasicMap<PointLt_U_Elem> lt_uniforms;
	lt_uniforms.mList[U_PL_DIFFUSE] = "sourceDiff";
	lt_uniforms.mList[U_PL_AMBIENT] = "sourceAmbi";
	lt_uniforms.mList[U_PL_SPECULAR] = "sourceSpec";
	lt_uniforms.mList[U_PL_POS] = "lightPos";

	mViewRenderer->GetNewObject(MATERIAL_OBJ, "chess", mo_uniforms)
			->ImportObj("obj3d/chess_tri", 2.0f)
			->AttachShader(mrt_vs, mrt_fs, SH_MRT)
			->AttachLight(POINT_LT, "point_light_1", lt_uniforms);

	Light_Mgr.GetLight("point_light_1")->mPosition = glm::vec3(0, 5.0f, 0);

	mViewRenderer->OffAutoRotate();

	mViewRenderer->GetCamera()->SetEye(glm::vec3(-15, 15, 15));

	int w = mViewRenderer->GetWidth();
	int h = mViewRenderer->GetHeight();
	TexProp texDiff(TEX_2D_PTR);
	texDiff.SetData("tex_diff", w, h, GL_RGB, GL_RGB8, GL_UNSIGNED_BYTE);
	texDiff.SetPointer(nullptr);
	texDiff.SetFilter();

	TexProp texDraw(TEX_2D_PTR);
	texDraw.SetData("tex_draw", w, h, GL_RGB, GL_RGB8, GL_UNSIGNED_BYTE);
	texDraw.SetPointer(nullptr);
	texDraw.SetFilter();

	TexProp texAmbi(TEX_2D_PTR);
	texAmbi.SetData("tex_ambi", w, h, GL_RGB, GL_RGB8, GL_UNSIGNED_BYTE);
	texAmbi.SetPointer(nullptr);
	texAmbi.SetFilter();

	TexProp texAttn(TEX_2D_PTR);
	texAttn.SetData("tex_attn", w, h, GL_RGB, GL_RGB8, GL_UNSIGNED_BYTE);
	texAttn.SetPointer(nullptr);
	texAttn.SetFilter();

	BasicObject *obj;

	obj = mViewRenderer->GetNewObject(SIMPLE_OBJ, "diff", mo_uniforms)
			->AttachShader(draw_vs, draw_fs, SH_DRAW)
			->AttachTexture(texDiff, "s_tex");
	dynamic_cast<SimpleObject *>(obj)->Init(glm::vec2(0));

	obj = mViewRenderer->GetNewObject(SIMPLE_OBJ, "spec", mo_uniforms)
			->AttachShader(draw_vs, draw_fs, SH_DRAW)
			->AttachTexture(texDraw, "s_tex");
	dynamic_cast<SimpleObject *>(obj)->Init(glm::vec2(-1.0, 0));
	obj = mViewRenderer->GetNewObject(SIMPLE_OBJ, "ambi", mo_uniforms)
			->AttachShader(draw_vs, draw_fs, SH_DRAW)
			->AttachTexture(texAmbi, "s_tex");
	dynamic_cast<SimpleObject *>(obj)->Init(glm::vec2(0, -1.0));
	obj = mViewRenderer->GetNewObject(SIMPLE_OBJ, "attn", mo_uniforms)
			->AttachShader(draw_vs, draw_fs, SH_DRAW)
			->AttachTexture(texAttn, "s_tex");
	dynamic_cast<SimpleObject *>(obj)->Init(glm::vec2(-1.0, -1.0));

	GLuint texIds[4];
	texIds[0] = Texture_Mgr.GetTextureId("tex_diff");
	texIds[1] = Texture_Mgr.GetTextureId("tex_draw");
	texIds[2] = Texture_Mgr.GetTextureId("tex_ambi");
	texIds[3] = Texture_Mgr.GetTextureId("tex_attn");
	LOGI("texid [%d, %d, %d, %d]", texIds[0],texIds[1],texIds[2],texIds[3]);

	mViewRenderer->SetCurrShader(SH_DRAW);

	dynamic_cast<MrtRenderer *>(mViewRenderer)->InitFbo(texIds);

}

<|endoftext|>


<commit_before>#include <fstream>
#include "Simbody.h"
#include "Exception.h"
#include "FileAdapter.h"
#include "TimeSeriesTable.h"
#include "XsensDataReader.h"

namespace OpenSim {

XsensDataReader* XsensDataReader::clone() const {
    return new XsensDataReader{*this};
}

DataAdapter::OutputTables
XsensDataReader::extendRead(const std::string& folderName) const {

    std::vector<std::ifstream*> imuStreams;
    std::vector<std::string> labels;
    // files specified by prefix + file name exist
    double dataRate = SimTK::NaN;
    int packetCounterIndex = -1;
    int accIndex = -1;
    int gyroIndex = -1;
    int magIndex = -1;
    int rotationsIndex = -1;

    int n_imus = _settings.getProperty_ExperimentalSensors().size();
    int last_size = 1024;
    // Will read data into pre-allocated Matrices in-memory rather than appendRow
    // on the fly to avoid the overhead of
    SimTK::Matrix_<SimTK::Quaternion> rotationsData{ last_size, n_imus };
    SimTK::Matrix_<SimTK::Vec3> linearAccelerationData{ last_size, n_imus };
    SimTK::Matrix_<SimTK::Vec3> magneticHeadingData{ last_size, n_imus };
    SimTK::Matrix_<SimTK::Vec3> angularVelocityData{ last_size, n_imus };
    std::vector<double> times;
    times.resize(last_size);

    std::string prefix = _settings.get_trial_prefix();
    for (int index = 0; index < n_imus; ++index) {
        std::string prefix = _settings.get_trial_prefix();
        const ExperimentalSensor& nextItem = _settings.get_ExperimentalSensors(index);
        auto fileName = folderName + prefix + nextItem.getName() +".txt";
        auto* nextStream = new std::ifstream{ fileName };
        OPENSIM_THROW_IF(!nextStream->good(),
            FileDoesNotExist,
            fileName);
        // Add imu name to labels
        labels.push_back(nextItem.get_name_in_model());
        // Add corresponding stream to imuStreams
        imuStreams.push_back(nextStream);

        // Skip lines to get to data
        std::string line;
        int labels_line_number = 5; // Undocumented, just found empirically in Xsens output files
        for (int j = 0; j <= labels_line_number; j++) {
            std::getline(*nextStream, line);
            if (j == 1 && SimTK::isNaN(dataRate)) { // Extract Data rate from line 1
                std::vector<std::string> tokens = FileAdapter::tokenize(line, ", ");
                // find Update Rate: and parse into dataRate
                if (tokens.size() < 4) continue;
                if (tokens[1] == "Update" && tokens[2] == "Rate:") {
                    dataRate = std::stod(tokens[3]);
                }
            }
            if (j == labels_line_number) { // Find indices for PacketCounter, Acc_{X,Y,Z}, Gyr_{X,Y,Z}, Mag_{X,Y,Z} on line 5
                std::vector<std::string> tokens = FileAdapter::tokenize(line, "\t");
                if (packetCounterIndex == -1) packetCounterIndex = find_index(tokens, "PacketCounter");
                if (accIndex == -1) accIndex = find_index(tokens, "Acc_X");
                if (gyroIndex == -1) gyroIndex = find_index(tokens, "Gyr_X");
                if (magIndex == -1) magIndex = find_index(tokens, "Mag_X");
                if (rotationsIndex == -1) rotationsIndex = find_index(tokens, "Mat[1][1]");
            }
        }
    }
    // internally keep track of what data was found in input files
    bool foundLinearAccelerationData = (accIndex != -1);
    bool foundMagneticHeadingData = (magIndex != -1);
    bool foundAngularVelocityData = (gyroIndex != -1);

    // If no Orientation data is available or dataRate can't be deduced we'll abort completely
    OPENSIM_THROW_IF((rotationsIndex == -1 || SimTK::isNaN(dataRate)),
        TableMissingHeader);

    // For all tables, will create row, stitch values from different files then append,time and timestep
    // are based on the first file
    bool done = false;
    double time = 0.0;
    double timeIncrement = 1 / dataRate;
    int rowNumber = 0;
    while (!done){
        // Make vectors one per table
        TimeSeriesTableQuaternion::RowVector
            orientation_row_vector{ n_imus, SimTK::Quaternion() };
        TimeSeriesTableVec3::RowVector
            accel_row_vector{ n_imus, SimTK::Vec3(SimTK::NaN) };
        TimeSeriesTableVec3::RowVector
            magneto_row_vector{ n_imus, SimTK::Vec3(SimTK::NaN) };
        TimeSeriesTableVec3::RowVector
            gyro_row_vector{ n_imus, SimTK::Vec3(SimTK::NaN) };
        // Cycle through the filles collating values
        int imu_index = 0;
        for (std::vector<std::ifstream*>::iterator it = imuStreams.begin();
            it != imuStreams.end();
            ++it, ++imu_index) {
            std::ifstream* nextStream = *it;
            // parse gyro info from imuStream
            std::vector<std::string> nextRow = FileAdapter::getNextLine(*nextStream, "\t\r");
            if (nextRow.empty()) {
                done = true;
                break;
            }
            if (foundLinearAccelerationData)
                accel_row_vector[imu_index] = SimTK::Vec3(std::stod(nextRow[accIndex]),
                    std::stod(nextRow[accIndex + 1]), std::stod(nextRow[accIndex + 2]));
            if (foundMagneticHeadingData)
                magneto_row_vector[imu_index] = SimTK::Vec3(std::stod(nextRow[magIndex]),
                    std::stod(nextRow[magIndex + 1]), std::stod(nextRow[magIndex + 2]));
            if (foundAngularVelocityData)
                gyro_row_vector[imu_index] = SimTK::Vec3(std::stod(nextRow[gyroIndex]),
                    std::stod(nextRow[gyroIndex + 1]), std::stod(nextRow[gyroIndex + 2]));
            // Create Mat33 then convert into Quaternion
            SimTK::Mat33 imu_matrix{ SimTK::NaN };
            int matrix_entry_index = 0;
            for (int mcol = 0; mcol < 3; mcol++) {
                for (int mrow = 0; mrow < 3; mrow++) {
                    imu_matrix[mrow][mcol] = std::stod(nextRow[rotationsIndex + matrix_entry_index]);
                    matrix_entry_index++;
                }
            }
            // Convert imu_matrix to Quaternion
            SimTK::Rotation imu_rotation{ imu_matrix };
            orientation_row_vector[imu_index] = imu_rotation.convertRotationToQuaternion();
        }
        if (done)
            break;
        // append to the tables
        times[rowNumber] = time;
        if (foundLinearAccelerationData)
            linearAccelerationData[rowNumber] =  accel_row_vector;
        if (foundMagneticHeadingData)
            magneticHeadingData[rowNumber] = magneto_row_vector;
        if (foundAngularVelocityData)
            angularVelocityData[rowNumber] = gyro_row_vector;
        rotationsData[rowNumber] = orientation_row_vector;
        time += timeIncrement;
        rowNumber++;
        if (std::remainder(rowNumber, last_size) == 0) {
            // resize all Data/Matrices, double the size  while keeping data
            int newSize = last_size*2;
            times.resize(newSize);
            // Repeat for Data matrices in use
            if (foundLinearAccelerationData) linearAccelerationData.resizeKeep(newSize, n_imus);
            if (foundMagneticHeadingData) magneticHeadingData.resizeKeep(newSize, n_imus);
            if (foundAngularVelocityData) angularVelocityData.resizeKeep(newSize, n_imus);
            rotationsData.resizeKeep(newSize, n_imus);
            last_size = newSize;
        }
    }
    // Trim Matrices in use to actual data and move into tables
    times.resize(rowNumber);
    // Repeat for Data matrices in use and create Tables from them or size 0 for empty
    linearAccelerationData.resizeKeep(foundLinearAccelerationData? rowNumber : 0,
        n_imus);
    magneticHeadingData.resizeKeep(foundMagneticHeadingData? rowNumber : 0,
            n_imus);
    angularVelocityData.resizeKeep(foundAngularVelocityData? rowNumber :0,
        n_imus);
    rotationsData.resizeKeep(rowNumber, n_imus);

    // Now create the tables from matrices
    // Create 4 tables for Rotations, LinearAccelerations, AngularVelocity, MagneticHeading
    // Tables could be empty if data is not present in file(s)
    DataAdapter::OutputTables tables = createTablesFromMatrices(dataRate, labels, times,
        rotationsData, linearAccelerationData, magneticHeadingData, angularVelocityData);
    return tables;
}

int XsensDataReader::find_index(std::vector<std::string>& tokens, const std::string& keyToMatch) {
    int returnIndex = -1;
    std::vector<std::string>::iterator it = std::find(tokens.begin(), tokens.end(), keyToMatch);
    if (it != tokens.end())
        returnIndex = static_cast<int>(std::distance(tokens.begin(), it));
    return returnIndex;
}

}
<commit_msg>Replace line couting to find labels by looking for PacketCounter to indicate line of 'labels' in xsens exported .txt files<commit_after>#include <fstream>
#include "Simbody.h"
#include "Exception.h"
#include "FileAdapter.h"
#include "TimeSeriesTable.h"
#include "XsensDataReader.h"

namespace OpenSim {

XsensDataReader* XsensDataReader::clone() const {
    return new XsensDataReader{*this};
}

DataAdapter::OutputTables
XsensDataReader::extendRead(const std::string& folderName) const {

    std::vector<std::ifstream*> imuStreams;
    std::vector<std::string> labels;
    // files specified by prefix + file name exist
    double dataRate = SimTK::NaN;
    int packetCounterIndex = -1;
    int accIndex = -1;
    int gyroIndex = -1;
    int magIndex = -1;
    int rotationsIndex = -1;

    int n_imus = _settings.getProperty_ExperimentalSensors().size();
    int last_size = 1024;
    // Will read data into pre-allocated Matrices in-memory rather than appendRow
    // on the fly to avoid the overhead of
    SimTK::Matrix_<SimTK::Quaternion> rotationsData{ last_size, n_imus };
    SimTK::Matrix_<SimTK::Vec3> linearAccelerationData{ last_size, n_imus };
    SimTK::Matrix_<SimTK::Vec3> magneticHeadingData{ last_size, n_imus };
    SimTK::Matrix_<SimTK::Vec3> angularVelocityData{ last_size, n_imus };
    std::vector<double> times;
    times.resize(last_size);

    std::string prefix = _settings.get_trial_prefix();
    for (int index = 0; index < n_imus; ++index) {
        std::string prefix = _settings.get_trial_prefix();
        const ExperimentalSensor& nextItem = _settings.get_ExperimentalSensors(index);
        auto fileName = folderName + prefix + nextItem.getName() +".txt";
        auto* nextStream = new std::ifstream{ fileName };
        OPENSIM_THROW_IF(!nextStream->good(),
            FileDoesNotExist,
            fileName);
        // Add imu name to labels
        labels.push_back(nextItem.get_name_in_model());
        // Add corresponding stream to imuStreams
        imuStreams.push_back(nextStream);

        // Skip lines to get to data
        std::string line;
        bool labelsFound = false;
        packetCounterIndex = -1; // Force moving file pointer to beginning of data for each stream
        for (int j = 0; !labelsFound; j++) {
            std::getline(*nextStream, line);
            if (j == 1 && SimTK::isNaN(dataRate)) { // Extract Data rate from line 1
                std::vector<std::string> tokens = FileAdapter::tokenize(line, ", ");
                // find Update Rate: and parse into dataRate
                if (tokens.size() < 4) continue;
                if (tokens[1] == "Update" && tokens[2] == "Rate:") {
                    dataRate = std::stod(tokens[3]);
                }
            }
            if (!labelsFound) { // Find indices for PacketCounter, Acc_{X,Y,Z}, Gyr_{X,Y,Z}, Mag_{X,Y,Z} on line 5
                std::vector<std::string> tokens = FileAdapter::tokenize(line, "\t");
                if (packetCounterIndex == -1) packetCounterIndex = find_index(tokens, "PacketCounter");
                if (packetCounterIndex == -1) {
                    // Could be comment, skip over
                    continue;
                }
                else {
                    labelsFound = true;
                    if (accIndex == -1) accIndex = find_index(tokens, "Acc_X");
                    if (gyroIndex == -1) gyroIndex = find_index(tokens, "Gyr_X");
                    if (magIndex == -1) magIndex = find_index(tokens, "Mag_X");
                    if (rotationsIndex == -1) rotationsIndex = find_index(tokens, "Mat[1][1]");
                }
            }
        }
    }
    // internally keep track of what data was found in input files
    bool foundLinearAccelerationData = (accIndex != -1);
    bool foundMagneticHeadingData = (magIndex != -1);
    bool foundAngularVelocityData = (gyroIndex != -1);

    // If no Orientation data is available or dataRate can't be deduced we'll abort completely
    OPENSIM_THROW_IF((rotationsIndex == -1 || SimTK::isNaN(dataRate)),
        TableMissingHeader);

    // For all tables, will create row, stitch values from different files then append,time and timestep
    // are based on the first file
    bool done = false;
    double time = 0.0;
    double timeIncrement = 1 / dataRate;
    int rowNumber = 0;
    while (!done){
        // Make vectors one per table
        TimeSeriesTableQuaternion::RowVector
            orientation_row_vector{ n_imus, SimTK::Quaternion() };
        TimeSeriesTableVec3::RowVector
            accel_row_vector{ n_imus, SimTK::Vec3(SimTK::NaN) };
        TimeSeriesTableVec3::RowVector
            magneto_row_vector{ n_imus, SimTK::Vec3(SimTK::NaN) };
        TimeSeriesTableVec3::RowVector
            gyro_row_vector{ n_imus, SimTK::Vec3(SimTK::NaN) };
        // Cycle through the filles collating values
        int imu_index = 0;
        for (std::vector<std::ifstream*>::iterator it = imuStreams.begin();
            it != imuStreams.end();
            ++it, ++imu_index) {
            std::ifstream* nextStream = *it;
            // parse gyro info from imuStream
            std::vector<std::string> nextRow = FileAdapter::getNextLine(*nextStream, "\t\r");
            if (nextRow.empty()) {
                done = true;
                break;
            }
            if (foundLinearAccelerationData)
                accel_row_vector[imu_index] = SimTK::Vec3(std::stod(nextRow[accIndex]),
                    std::stod(nextRow[accIndex + 1]), std::stod(nextRow[accIndex + 2]));
            if (foundMagneticHeadingData)
                magneto_row_vector[imu_index] = SimTK::Vec3(std::stod(nextRow[magIndex]),
                    std::stod(nextRow[magIndex + 1]), std::stod(nextRow[magIndex + 2]));
            if (foundAngularVelocityData)
                gyro_row_vector[imu_index] = SimTK::Vec3(std::stod(nextRow[gyroIndex]),
                    std::stod(nextRow[gyroIndex + 1]), std::stod(nextRow[gyroIndex + 2]));
            // Create Mat33 then convert into Quaternion
            SimTK::Mat33 imu_matrix{ SimTK::NaN };
            int matrix_entry_index = 0;
            for (int mcol = 0; mcol < 3; mcol++) {
                for (int mrow = 0; mrow < 3; mrow++) {
                    imu_matrix[mrow][mcol] = std::stod(nextRow[rotationsIndex + matrix_entry_index]);
                    matrix_entry_index++;
                }
            }
            // Convert imu_matrix to Quaternion
            SimTK::Rotation imu_rotation{ imu_matrix };
            orientation_row_vector[imu_index] = imu_rotation.convertRotationToQuaternion();
        }
        if (done)
            break;
        // append to the tables
        times[rowNumber] = time;
        if (foundLinearAccelerationData)
            linearAccelerationData[rowNumber] =  accel_row_vector;
        if (foundMagneticHeadingData)
            magneticHeadingData[rowNumber] = magneto_row_vector;
        if (foundAngularVelocityData)
            angularVelocityData[rowNumber] = gyro_row_vector;
        rotationsData[rowNumber] = orientation_row_vector;
        time += timeIncrement;
        rowNumber++;
        if (std::remainder(rowNumber, last_size) == 0) {
            // resize all Data/Matrices, double the size  while keeping data
            int newSize = last_size*2;
            times.resize(newSize);
            // Repeat for Data matrices in use
            if (foundLinearAccelerationData) linearAccelerationData.resizeKeep(newSize, n_imus);
            if (foundMagneticHeadingData) magneticHeadingData.resizeKeep(newSize, n_imus);
            if (foundAngularVelocityData) angularVelocityData.resizeKeep(newSize, n_imus);
            rotationsData.resizeKeep(newSize, n_imus);
            last_size = newSize;
        }
    }
    // Trim Matrices in use to actual data and move into tables
    times.resize(rowNumber);
    // Repeat for Data matrices in use and create Tables from them or size 0 for empty
    linearAccelerationData.resizeKeep(foundLinearAccelerationData? rowNumber : 0,
        n_imus);
    magneticHeadingData.resizeKeep(foundMagneticHeadingData? rowNumber : 0,
            n_imus);
    angularVelocityData.resizeKeep(foundAngularVelocityData? rowNumber :0,
        n_imus);
    rotationsData.resizeKeep(rowNumber, n_imus);

    // Now create the tables from matrices
    // Create 4 tables for Rotations, LinearAccelerations, AngularVelocity, MagneticHeading
    // Tables could be empty if data is not present in file(s)
    DataAdapter::OutputTables tables = createTablesFromMatrices(dataRate, labels, times,
        rotationsData, linearAccelerationData, magneticHeadingData, angularVelocityData);
    return tables;
}

int XsensDataReader::find_index(std::vector<std::string>& tokens, const std::string& keyToMatch) {
    int returnIndex = -1;
    std::vector<std::string>::iterator it = std::find(tokens.begin(), tokens.end(), keyToMatch);
    if (it != tokens.end())
        returnIndex = static_cast<int>(std::distance(tokens.begin(), it));
    return returnIndex;
}

}
<|endoftext|>


<commit_before>#include <fstream>
#include "Simbody.h"
#include "Exception.h"
#include "FileAdapter.h"
#include "TimeSeriesTable.h"
#include "XsensDataReader.h"

namespace OpenSim {

const std::string XsensDataReader::Orientations{ "orientations" };
const std::string XsensDataReader::LinearAccelerations{ "linear_accelerations" };
const std::string XsensDataReader::MagneticHeading{ "magnetic_heading" };
const std::string XsensDataReader::AngularVelocity{ "angular_velocity" };

XsensDataReader* XsensDataReader::clone() const {
    return new XsensDataReader{*this};
}

DataAdapter::OutputTables
XsensDataReader::extendRead(const std::string& folderName) const {

    std::vector<std::ifstream*> imuStreams;
    std::vector<std::string> labels;
    // files specified by prefix + file name exist
    double dataRate = SimTK::NaN;
    int packetCounterIndex = -1;
    int accIndex = -1;
    int gyroIndex = -1;
    int magIndex = -1;
    int rotationsIndex = -1;

    int n_imus = _settings.getProperty_ExperimentalSensors().size();
    int last_size = 1024;
    // Will read data into pre-allocated Matrices in-memory rather than appendRow
    // on the fly to avoid the overhead of
    SimTK::Matrix_<SimTK::Quaternion> rotationsData{ last_size, n_imus };
    SimTK::Matrix_<SimTK::Vec3> linearAccelerationData{ last_size, n_imus };
    SimTK::Matrix_<SimTK::Vec3> magneticHeadingData{ last_size, n_imus };
    SimTK::Matrix_<SimTK::Vec3> angularVelocityData{ last_size, n_imus };
    std::vector<double> times;
    times.resize(last_size);

    std::string prefix = _settings.get_trial_prefix();
    for (int index = 0; index < n_imus; ++index) {
        std::string prefix = _settings.get_trial_prefix();
        const ExperimentalSensor& nextItem = _settings.get_ExperimentalSensors(index);
        auto fileName = folderName + prefix + nextItem.getName() +".txt";
        auto* nextStream = new std::ifstream{ fileName };
        OPENSIM_THROW_IF(!nextStream->good(),
            FileDoesNotExist,
            fileName);
        // Add imu name to labels
        labels.push_back(nextItem.get_name_in_model());
        // Add corresponding stream to imuStreams
        imuStreams.push_back(nextStream);

        // Skip lines to get to data
        std::string line;
        for (int j = 0; j < 6; j++) {
            std::getline(*nextStream, line);
            if (j == 1 && SimTK::isNaN(dataRate)) { // Extract Data rate from line 1
                std::vector<std::string> tokens = FileAdapter::tokenize(line, ", ");
                // find Update Rate: and parse into dataRate
                if (tokens.size() < 4) continue;
                if (tokens[1] == "Update" && tokens[2] == "Rate:") {
                    dataRate = std::stod(tokens[3]);
                }
            }
            if (j == 5) { // Find indices for PacketCounter, Acc_{X,Y,Z}, Gyr_{X,Y,Z}, Mag_{X,Y,Z} on line 5
                std::vector<std::string> tokens = FileAdapter::tokenize(line, "\t");
                if (packetCounterIndex == -1) packetCounterIndex = find_index(tokens, "PacketCounter");
                if (accIndex == -1) accIndex = find_index(tokens, "Acc_X");
                if (gyroIndex == -1) gyroIndex = find_index(tokens, "Gyr_X");
                if (magIndex == -1) magIndex = find_index(tokens, "Mag_X");
                if (rotationsIndex == -1) rotationsIndex = find_index(tokens, "Mat[1][1]");
            }
        }
    }
    // internally keep track of what data was found in input files
    bool foundLinearAccelerationData = (accIndex != -1);
    bool foundMagneticHeadingData = (magIndex != -1);
    bool foundAngularVelocityData = (gyroIndex != -1);

    // If no Orientation data is available or dataRate can't be deduced we'll abort completely
    OPENSIM_THROW_IF((rotationsIndex == -1 || SimTK::isNaN(dataRate)),
        TableMissingHeader);

    // For all tables, will create row, stitch values from different files then append,time and timestep
    // are based on the first file
    bool done = false;
    double time = 0.0;
    double timeIncrement = 1 / dataRate;
    int rowNumber = 0;
    while (!done){
        // Make vectors one per table
        TimeSeriesTableQuaternion::RowVector
            orientation_row_vector{ n_imus, SimTK::Quaternion() };
        TimeSeriesTableVec3::RowVector
            accel_row_vector{ n_imus, SimTK::Vec3(SimTK::NaN) };
        TimeSeriesTableVec3::RowVector
            magneto_row_vector{ n_imus, SimTK::Vec3(SimTK::NaN) };
        TimeSeriesTableVec3::RowVector
            gyro_row_vector{ n_imus, SimTK::Vec3(SimTK::NaN) };
        // Cycle through the filles collating values
        int imu_index = 0;
        for (std::vector<std::ifstream*>::iterator it = imuStreams.begin();
            it != imuStreams.end();
            ++it, ++imu_index) {
            std::ifstream* nextStream = *it;
            // parse gyro info from imuStream
            std::vector<std::string> nextRow = FileAdapter::getNextLine(*nextStream, "\t\r");
            if (nextRow.empty()) {
                done = true;
                break;
            }
            if (foundLinearAccelerationData)
                accel_row_vector[imu_index] = SimTK::Vec3(std::stod(nextRow[accIndex]),
                    std::stod(nextRow[accIndex + 1]), std::stod(nextRow[accIndex + 2]));
            if (foundMagneticHeadingData)
                magneto_row_vector[imu_index] = SimTK::Vec3(std::stod(nextRow[magIndex]),
                    std::stod(nextRow[magIndex + 1]), std::stod(nextRow[magIndex + 2]));
            if (foundAngularVelocityData)
                gyro_row_vector[imu_index] = SimTK::Vec3(std::stod(nextRow[gyroIndex]),
                    std::stod(nextRow[gyroIndex + 1]), std::stod(nextRow[gyroIndex + 2]));
            // Create Mat33 then convert into Quaternion
            SimTK::Mat33 imu_matrix{ SimTK::NaN };
            int matrix_entry_index = 0;
            for (int mcol = 0; mcol < 3; mcol++) {
                for (int mrow = 0; mrow < 3; mrow++) {
                    imu_matrix[mrow][mcol] = std::stod(nextRow[rotationsIndex + matrix_entry_index]);
                    matrix_entry_index++;
                }
            }
            // Convert imu_matrix to Quaternion
            SimTK::Rotation imu_rotation{ imu_matrix };
            orientation_row_vector[imu_index] = imu_rotation.convertRotationToQuaternion();
        }
        if (done)
            break;
        // append to the tables
        times[rowNumber] = time;
        if (foundLinearAccelerationData)
            linearAccelerationData[rowNumber] =  accel_row_vector;
        if (foundMagneticHeadingData)
            magneticHeadingData[rowNumber] = magneto_row_vector;
        if (foundAngularVelocityData)
            angularVelocityData[rowNumber] = gyro_row_vector;
        rotationsData[rowNumber] = orientation_row_vector;
        time += timeIncrement;
        rowNumber++;
        if (std::remainder(rowNumber, last_size) == 0) {
            // resize all Data/Matrices, double the size  while keeping data
            int newSize = last_size*2;
            times.resize(newSize);
            // Repeat for Data matrices in use
            if (foundLinearAccelerationData) linearAccelerationData.resizeKeep(newSize, n_imus);
            if (foundMagneticHeadingData) magneticHeadingData.resizeKeep(newSize, n_imus);
            if (foundAngularVelocityData) angularVelocityData.resizeKeep(newSize, n_imus);
            rotationsData.resizeKeep(newSize, n_imus);
            last_size = newSize;
        }
    }
    // Trim Matrices in use to actual data and move into tables
    int actualSize = rowNumber;
    times.resize(actualSize);
    // Repeat for Data matrices in use and create Tables from them or size 0 for empty
    linearAccelerationData.resizeKeep(foundLinearAccelerationData? actualSize: 0,
        n_imus);
    magneticHeadingData.resizeKeep(foundMagneticHeadingData?actualSize: 0,
            n_imus);
    angularVelocityData.resizeKeep(foundAngularVelocityData?actualSize:0,
        n_imus);
    rotationsData.resizeKeep(actualSize, n_imus);
    // Now create the tables from matrices
    // Create 4 tables for Rotations, LinearAccelerations, AngularVelocity, MagneticHeading
    // Tables could be empty if data is not present in file(s)
    DataAdapter::OutputTables tables{};
    auto orientationTable = std::make_shared<TimeSeriesTableQuaternion>(times, rotationsData, labels);
    orientationTable->updTableMetaData()
        .setValueForKey("DataRate", std::to_string(dataRate));
    tables.emplace(Orientations, orientationTable);

    std::vector<double> emptyTimes;
    auto accelerationTable = (foundLinearAccelerationData ?
        std::make_shared<TimeSeriesTableVec3>(times, linearAccelerationData, labels) :
        std::make_shared<TimeSeriesTableVec3>(emptyTimes, linearAccelerationData, labels));
    accelerationTable->updTableMetaData()
        .setValueForKey("DataRate", std::to_string(dataRate));
    tables.emplace(LinearAccelerations, accelerationTable);

    auto magneticHeadingTable = (foundMagneticHeadingData ?
        std::make_shared<TimeSeriesTableVec3>(times, magneticHeadingData, labels) :
        std::make_shared<TimeSeriesTableVec3>(emptyTimes, magneticHeadingData, labels));
    magneticHeadingTable->updTableMetaData()
        .setValueForKey("DataRate", std::to_string(dataRate));
    tables.emplace(MagneticHeading, magneticHeadingTable);

    auto angularVelocityTable = (foundAngularVelocityData ?
        std::make_shared<TimeSeriesTableVec3>(times, angularVelocityData, labels) :
        std::make_shared<TimeSeriesTableVec3>(emptyTimes, angularVelocityData, labels));
    angularVelocityTable->updTableMetaData()
        .setValueForKey("DataRate", std::to_string(dataRate));
    tables.emplace(AngularVelocity, angularVelocityTable);

    return tables;
}

int XsensDataReader::find_index(std::vector<std::string>& tokens, const std::string& keyToMatch) {
    int returnIndex = -1;
    std::vector<std::string>::iterator it = std::find(tokens.begin(), tokens.end(), keyToMatch);
    if (it != tokens.end())
        returnIndex = static_cast<int>(std::distance(tokens.begin(), it));
    return returnIndex;
}

}
<commit_msg>One place to specify number of lines to sktp to locate headers in txt files<commit_after>#include <fstream>
#include "Simbody.h"
#include "Exception.h"
#include "FileAdapter.h"
#include "TimeSeriesTable.h"
#include "XsensDataReader.h"

namespace OpenSim {

const std::string XsensDataReader::Orientations{ "orientations" };
const std::string XsensDataReader::LinearAccelerations{ "linear_accelerations" };
const std::string XsensDataReader::MagneticHeading{ "magnetic_heading" };
const std::string XsensDataReader::AngularVelocity{ "angular_velocity" };

XsensDataReader* XsensDataReader::clone() const {
    return new XsensDataReader{*this};
}

DataAdapter::OutputTables
XsensDataReader::extendRead(const std::string& folderName) const {

    std::vector<std::ifstream*> imuStreams;
    std::vector<std::string> labels;
    // files specified by prefix + file name exist
    double dataRate = SimTK::NaN;
    int packetCounterIndex = -1;
    int accIndex = -1;
    int gyroIndex = -1;
    int magIndex = -1;
    int rotationsIndex = -1;

    int n_imus = _settings.getProperty_ExperimentalSensors().size();
    int last_size = 1024;
    // Will read data into pre-allocated Matrices in-memory rather than appendRow
    // on the fly to avoid the overhead of
    SimTK::Matrix_<SimTK::Quaternion> rotationsData{ last_size, n_imus };
    SimTK::Matrix_<SimTK::Vec3> linearAccelerationData{ last_size, n_imus };
    SimTK::Matrix_<SimTK::Vec3> magneticHeadingData{ last_size, n_imus };
    SimTK::Matrix_<SimTK::Vec3> angularVelocityData{ last_size, n_imus };
    std::vector<double> times;
    times.resize(last_size);

    std::string prefix = _settings.get_trial_prefix();
    for (int index = 0; index < n_imus; ++index) {
        std::string prefix = _settings.get_trial_prefix();
        const ExperimentalSensor& nextItem = _settings.get_ExperimentalSensors(index);
        auto fileName = folderName + prefix + nextItem.getName() +".txt";
        auto* nextStream = new std::ifstream{ fileName };
        OPENSIM_THROW_IF(!nextStream->good(),
            FileDoesNotExist,
            fileName);
        // Add imu name to labels
        labels.push_back(nextItem.get_name_in_model());
        // Add corresponding stream to imuStreams
        imuStreams.push_back(nextStream);

        // Skip lines to get to data
        std::string line;
        int labels_line_number = 5; // Undocumented, just found empirically in Xsens output files
        for (int j = 0; j <= labels_line_number; j++) {
            std::getline(*nextStream, line);
            if (j == 1 && SimTK::isNaN(dataRate)) { // Extract Data rate from line 1
                std::vector<std::string> tokens = FileAdapter::tokenize(line, ", ");
                // find Update Rate: and parse into dataRate
                if (tokens.size() < 4) continue;
                if (tokens[1] == "Update" && tokens[2] == "Rate:") {
                    dataRate = std::stod(tokens[3]);
                }
            }
            if (j == labels_line_number) { // Find indices for PacketCounter, Acc_{X,Y,Z}, Gyr_{X,Y,Z}, Mag_{X,Y,Z} on line 5
                std::vector<std::string> tokens = FileAdapter::tokenize(line, "\t");
                if (packetCounterIndex == -1) packetCounterIndex = find_index(tokens, "PacketCounter");
                if (accIndex == -1) accIndex = find_index(tokens, "Acc_X");
                if (gyroIndex == -1) gyroIndex = find_index(tokens, "Gyr_X");
                if (magIndex == -1) magIndex = find_index(tokens, "Mag_X");
                if (rotationsIndex == -1) rotationsIndex = find_index(tokens, "Mat[1][1]");
            }
        }
    }
    // internally keep track of what data was found in input files
    bool foundLinearAccelerationData = (accIndex != -1);
    bool foundMagneticHeadingData = (magIndex != -1);
    bool foundAngularVelocityData = (gyroIndex != -1);

    // If no Orientation data is available or dataRate can't be deduced we'll abort completely
    OPENSIM_THROW_IF((rotationsIndex == -1 || SimTK::isNaN(dataRate)),
        TableMissingHeader);

    // For all tables, will create row, stitch values from different files then append,time and timestep
    // are based on the first file
    bool done = false;
    double time = 0.0;
    double timeIncrement = 1 / dataRate;
    int rowNumber = 0;
    while (!done){
        // Make vectors one per table
        TimeSeriesTableQuaternion::RowVector
            orientation_row_vector{ n_imus, SimTK::Quaternion() };
        TimeSeriesTableVec3::RowVector
            accel_row_vector{ n_imus, SimTK::Vec3(SimTK::NaN) };
        TimeSeriesTableVec3::RowVector
            magneto_row_vector{ n_imus, SimTK::Vec3(SimTK::NaN) };
        TimeSeriesTableVec3::RowVector
            gyro_row_vector{ n_imus, SimTK::Vec3(SimTK::NaN) };
        // Cycle through the filles collating values
        int imu_index = 0;
        for (std::vector<std::ifstream*>::iterator it = imuStreams.begin();
            it != imuStreams.end();
            ++it, ++imu_index) {
            std::ifstream* nextStream = *it;
            // parse gyro info from imuStream
            std::vector<std::string> nextRow = FileAdapter::getNextLine(*nextStream, "\t\r");
            if (nextRow.empty()) {
                done = true;
                break;
            }
            if (foundLinearAccelerationData)
                accel_row_vector[imu_index] = SimTK::Vec3(std::stod(nextRow[accIndex]),
                    std::stod(nextRow[accIndex + 1]), std::stod(nextRow[accIndex + 2]));
            if (foundMagneticHeadingData)
                magneto_row_vector[imu_index] = SimTK::Vec3(std::stod(nextRow[magIndex]),
                    std::stod(nextRow[magIndex + 1]), std::stod(nextRow[magIndex + 2]));
            if (foundAngularVelocityData)
                gyro_row_vector[imu_index] = SimTK::Vec3(std::stod(nextRow[gyroIndex]),
                    std::stod(nextRow[gyroIndex + 1]), std::stod(nextRow[gyroIndex + 2]));
            // Create Mat33 then convert into Quaternion
            SimTK::Mat33 imu_matrix{ SimTK::NaN };
            int matrix_entry_index = 0;
            for (int mcol = 0; mcol < 3; mcol++) {
                for (int mrow = 0; mrow < 3; mrow++) {
                    imu_matrix[mrow][mcol] = std::stod(nextRow[rotationsIndex + matrix_entry_index]);
                    matrix_entry_index++;
                }
            }
            // Convert imu_matrix to Quaternion
            SimTK::Rotation imu_rotation{ imu_matrix };
            orientation_row_vector[imu_index] = imu_rotation.convertRotationToQuaternion();
        }
        if (done)
            break;
        // append to the tables
        times[rowNumber] = time;
        if (foundLinearAccelerationData)
            linearAccelerationData[rowNumber] =  accel_row_vector;
        if (foundMagneticHeadingData)
            magneticHeadingData[rowNumber] = magneto_row_vector;
        if (foundAngularVelocityData)
            angularVelocityData[rowNumber] = gyro_row_vector;
        rotationsData[rowNumber] = orientation_row_vector;
        time += timeIncrement;
        rowNumber++;
        if (std::remainder(rowNumber, last_size) == 0) {
            // resize all Data/Matrices, double the size  while keeping data
            int newSize = last_size*2;
            times.resize(newSize);
            // Repeat for Data matrices in use
            if (foundLinearAccelerationData) linearAccelerationData.resizeKeep(newSize, n_imus);
            if (foundMagneticHeadingData) magneticHeadingData.resizeKeep(newSize, n_imus);
            if (foundAngularVelocityData) angularVelocityData.resizeKeep(newSize, n_imus);
            rotationsData.resizeKeep(newSize, n_imus);
            last_size = newSize;
        }
    }
    // Trim Matrices in use to actual data and move into tables
    int actualSize = rowNumber;
    times.resize(actualSize);
    // Repeat for Data matrices in use and create Tables from them or size 0 for empty
    linearAccelerationData.resizeKeep(foundLinearAccelerationData? actualSize: 0,
        n_imus);
    magneticHeadingData.resizeKeep(foundMagneticHeadingData?actualSize: 0,
            n_imus);
    angularVelocityData.resizeKeep(foundAngularVelocityData?actualSize:0,
        n_imus);
    rotationsData.resizeKeep(actualSize, n_imus);
    // Now create the tables from matrices
    // Create 4 tables for Rotations, LinearAccelerations, AngularVelocity, MagneticHeading
    // Tables could be empty if data is not present in file(s)
    DataAdapter::OutputTables tables{};
    auto orientationTable = std::make_shared<TimeSeriesTableQuaternion>(times, rotationsData, labels);
    orientationTable->updTableMetaData()
        .setValueForKey("DataRate", std::to_string(dataRate));
    tables.emplace(Orientations, orientationTable);

    std::vector<double> emptyTimes;
    auto accelerationTable = (foundLinearAccelerationData ?
        std::make_shared<TimeSeriesTableVec3>(times, linearAccelerationData, labels) :
        std::make_shared<TimeSeriesTableVec3>(emptyTimes, linearAccelerationData, labels));
    accelerationTable->updTableMetaData()
        .setValueForKey("DataRate", std::to_string(dataRate));
    tables.emplace(LinearAccelerations, accelerationTable);

    auto magneticHeadingTable = (foundMagneticHeadingData ?
        std::make_shared<TimeSeriesTableVec3>(times, magneticHeadingData, labels) :
        std::make_shared<TimeSeriesTableVec3>(emptyTimes, magneticHeadingData, labels));
    magneticHeadingTable->updTableMetaData()
        .setValueForKey("DataRate", std::to_string(dataRate));
    tables.emplace(MagneticHeading, magneticHeadingTable);

    auto angularVelocityTable = (foundAngularVelocityData ?
        std::make_shared<TimeSeriesTableVec3>(times, angularVelocityData, labels) :
        std::make_shared<TimeSeriesTableVec3>(emptyTimes, angularVelocityData, labels));
    angularVelocityTable->updTableMetaData()
        .setValueForKey("DataRate", std::to_string(dataRate));
    tables.emplace(AngularVelocity, angularVelocityTable);

    return tables;
}

int XsensDataReader::find_index(std::vector<std::string>& tokens, const std::string& keyToMatch) {
    int returnIndex = -1;
    std::vector<std::string>::iterator it = std::find(tokens.begin(), tokens.end(), keyToMatch);
    if (it != tokens.end())
        returnIndex = static_cast<int>(std::distance(tokens.begin(), it));
    return returnIndex;
}

}
<|endoftext|>


<commit_before>//===- Interpreter.cpp - Top-Level LLVM Interpreter Implementation --------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the top-level functionality for the LLVM interpreter.
// This interpreter is designed to be a very simple, portable, inefficient
// interpreter.
//
//===----------------------------------------------------------------------===//

#include "Interpreter.h"
#include "llvm/CodeGen/IntrinsicLowering.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Module.h"
#include "llvm/ModuleProvider.h"
using namespace llvm;

static struct RegisterInterp {
  RegisterInterp() { Interpreter::Register(); }
} InterpRegistrator;

namespace llvm {
  void LinkInInterpreter() {
  }
}

/// create - Create a new interpreter object.  This can never fail.
///
ExecutionEngine *Interpreter::create(ModuleProvider *MP) {
  Module *M;
  try {
    M = MP->materializeModule();
  } catch (...) {
    return 0;  // error materializing the module.
  }

  // FIXME: This should probably compute the entire data layout
  std::string DataLayout;
  int Test = 0;
  *(char*)&Test = 1;    // Return true if the host is little endian
  bool isLittleEndian = (Test == 1);
  DataLayout.append(isLittleEndian ? "e" : "E");

	bool Ptr64 = sizeof(void*) == 8;
	DataLayout.append(Ptr64 ? "-p:64:64" : "-p:32:32");

  M->setDataLayout(DataLayout);

  return new Interpreter(M);
}

//===----------------------------------------------------------------------===//
// Interpreter ctor - Initialize stuff
//
Interpreter::Interpreter(Module *M) : ExecutionEngine(M), TD(M) {

  memset(&ExitValue, 0, sizeof(ExitValue));
  setTargetData(&TD);
  // Initialize the "backend"
  initializeExecutionEngine();
  initializeExternalFunctions();
  emitGlobals();

  IL = new IntrinsicLowering(TD);
}

Interpreter::~Interpreter() {
  delete IL;
}

void Interpreter::runAtExitHandlers () {
  while (!AtExitHandlers.empty()) {
    callFunction(AtExitHandlers.back(), std::vector<GenericValue>());
    AtExitHandlers.pop_back();
    run();
  }
}

/// run - Start execution with the specified function and arguments.
///
GenericValue
Interpreter::runFunction(Function *F,
                         const std::vector<GenericValue> &ArgValues) {
  assert (F && "Function *F was null at entry to run()");

  // Try extra hard not to pass extra args to a function that isn't
  // expecting them.  C programmers frequently bend the rules and
  // declare main() with fewer parameters than it actually gets
  // passed, and the interpreter barfs if you pass a function more
  // parameters than it is declared to take. This does not attempt to
  // take into account gratuitous differences in declared types,
  // though.
  std::vector<GenericValue> ActualArgs;
  const unsigned ArgCount = F->getFunctionType()->getNumParams();
  for (unsigned i = 0; i < ArgCount; ++i)
    ActualArgs.push_back(ArgValues[i]);

  // Set up the function call.
  callFunction(F, ActualArgs);

  // Start executing the function.
  run();

  return ExitValue;
}

<commit_msg>Remove tabs.<commit_after>//===- Interpreter.cpp - Top-Level LLVM Interpreter Implementation --------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the top-level functionality for the LLVM interpreter.
// This interpreter is designed to be a very simple, portable, inefficient
// interpreter.
//
//===----------------------------------------------------------------------===//

#include "Interpreter.h"
#include "llvm/CodeGen/IntrinsicLowering.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Module.h"
#include "llvm/ModuleProvider.h"
using namespace llvm;

static struct RegisterInterp {
  RegisterInterp() { Interpreter::Register(); }
} InterpRegistrator;

namespace llvm {
  void LinkInInterpreter() {
  }
}

/// create - Create a new interpreter object.  This can never fail.
///
ExecutionEngine *Interpreter::create(ModuleProvider *MP) {
  Module *M;
  try {
    M = MP->materializeModule();
  } catch (...) {
    return 0;  // error materializing the module.
  }

  // FIXME: This should probably compute the entire data layout
  std::string DataLayout;
  int Test = 0;
  *(char*)&Test = 1;    // Return true if the host is little endian
  bool isLittleEndian = (Test == 1);
  DataLayout.append(isLittleEndian ? "e" : "E");

  bool Ptr64 = sizeof(void*) == 8;
  DataLayout.append(Ptr64 ? "-p:64:64" : "-p:32:32");

  M->setDataLayout(DataLayout);

  return new Interpreter(M);
}

//===----------------------------------------------------------------------===//
// Interpreter ctor - Initialize stuff
//
Interpreter::Interpreter(Module *M) : ExecutionEngine(M), TD(M) {

  memset(&ExitValue, 0, sizeof(ExitValue));
  setTargetData(&TD);
  // Initialize the "backend"
  initializeExecutionEngine();
  initializeExternalFunctions();
  emitGlobals();

  IL = new IntrinsicLowering(TD);
}

Interpreter::~Interpreter() {
  delete IL;
}

void Interpreter::runAtExitHandlers () {
  while (!AtExitHandlers.empty()) {
    callFunction(AtExitHandlers.back(), std::vector<GenericValue>());
    AtExitHandlers.pop_back();
    run();
  }
}

/// run - Start execution with the specified function and arguments.
///
GenericValue
Interpreter::runFunction(Function *F,
                         const std::vector<GenericValue> &ArgValues) {
  assert (F && "Function *F was null at entry to run()");

  // Try extra hard not to pass extra args to a function that isn't
  // expecting them.  C programmers frequently bend the rules and
  // declare main() with fewer parameters than it actually gets
  // passed, and the interpreter barfs if you pass a function more
  // parameters than it is declared to take. This does not attempt to
  // take into account gratuitous differences in declared types,
  // though.
  std::vector<GenericValue> ActualArgs;
  const unsigned ArgCount = F->getFunctionType()->getNumParams();
  for (unsigned i = 0; i < ArgCount; ++i)
    ActualArgs.push_back(ArgValues[i]);

  // Set up the function call.
  callFunction(F, ActualArgs);

  // Start executing the function.
  run();

  return ExitValue;
}

<|endoftext|>


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

#include "chrome/browser/ui/webui/bidi_checker_web_ui_test.h"

#include "base/base_paths.h"
#include "base/i18n/rtl.h"
#include "base/path_service.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/autofill/autofill_common_test.h"
#include "chrome/browser/autofill/autofill_profile.h"
#include "chrome/browser/autofill/personal_data_manager.h"
#include "chrome/browser/autofill/personal_data_manager_factory.h"
#include "chrome/browser/history/history.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/ui_test_utils.h"
#include "ui/base/resource/resource_bundle.h"

#if defined(OS_POSIX) && defined(TOOLKIT_USES_GTK)
#include <gtk/gtk.h>
#endif

// These tests are failing on linux views build. crbug.com/96891
#if defined(TOOLKIT_VIEWS) && defined(OS_LINUX) && !defined(OS_CHROMEOS)
#define MAYBE_TestCrashesPageRTL DISABLED_TestCrashesPageRTL
#define MAYBE_TestDownloadsPageRTL DISABLED_TestDownloadsPageRTL
#define MAYBE_TestMainHistoryPageRTL DISABLED_TestMainHistoryPageRTL
#define MAYBE_TestNewTabPageRTL DISABLED_TestNewTabPageRTL
#define MAYBE_TestPluginsPageRTL DISABLED_TestPluginsPageRTL
#define MAYBE_TestSettingsAutofillPageRTL DISABLED_TestSettingsAutofillPageRTL
#define MAYBE_TestSettingsPageRTL DISABLED_TestSettingsPageRTL
#else
#define MAYBE_TestCrashesPageRTL TestCrashesPageRTL
#define MAYBE_TestDownloadsPageRTL TestDownloadsPageRTL
#define MAYBE_TestMainHistoryPageRTL TestMainHistoryPageRTL
// Disabled, http://crbug.com/97453
#define MAYBE_TestNewTabPageRTL DISABLED_TestNewTabPageRTL
#define MAYBE_TestPluginsPageRTL TestPluginsPageRTL
#define MAYBE_TestSettingsAutofillPageRTL TestSettingsAutofillPageRTL
#define MAYBE_TestSettingsPageRTL TestSettingsPageRTL
#endif

static const FilePath::CharType* kWebUIBidiCheckerLibraryJS =
    FILE_PATH_LITERAL("third_party/bidichecker/bidichecker_packaged.js");

namespace {
FilePath WebUIBidiCheckerLibraryJSPath() {
  FilePath src_root;
  if (!PathService::Get(base::DIR_SOURCE_ROOT, &src_root))
    LOG(ERROR) << "Couldn't find source root";
  return src_root.Append(kWebUIBidiCheckerLibraryJS);
}
}

static const FilePath::CharType* kBidiCheckerTestsJS =
    FILE_PATH_LITERAL("bidichecker_tests.js");

WebUIBidiCheckerBrowserTest::~WebUIBidiCheckerBrowserTest() {}

WebUIBidiCheckerBrowserTest::WebUIBidiCheckerBrowserTest() {}

void WebUIBidiCheckerBrowserTest::SetUpInProcessBrowserTestFixture() {
  WebUIBrowserTest::SetUpInProcessBrowserTestFixture();
  WebUIBrowserTest::AddLibrary(WebUIBidiCheckerLibraryJSPath());
  WebUIBrowserTest::AddLibrary(FilePath(kBidiCheckerTestsJS));
}

void WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(const char pageURL[],
                                                       bool isRTL) {
  ui_test_utils::NavigateToURL(browser(), GURL(pageURL));
  ASSERT_TRUE(RunJavascriptTest("runBidiChecker",
                                Value::CreateStringValue(pageURL),
                                Value::CreateBooleanValue(isRTL)));
}

// WebUIBidiCheckerBrowserTestFakeBidi

WebUIBidiCheckerBrowserTestFakeBidi::~WebUIBidiCheckerBrowserTestFakeBidi() {}

WebUIBidiCheckerBrowserTestFakeBidi::WebUIBidiCheckerBrowserTestFakeBidi() {}

void WebUIBidiCheckerBrowserTestFakeBidi::SetUpOnMainThread() {
  WebUIBidiCheckerBrowserTest::SetUpOnMainThread();
  FilePath pak_path;
  app_locale_ = base::i18n::GetConfiguredLocale();
  ASSERT_TRUE(PathService::Get(base::FILE_MODULE, &pak_path));
  pak_path = pak_path.DirName();
  pak_path = pak_path.AppendASCII("pseudo_locales");
  pak_path = pak_path.AppendASCII("fake-bidi");
  pak_path = pak_path.ReplaceExtension(FILE_PATH_LITERAL("pak"));
  ResourceBundle::GetSharedInstance().OverrideLocalePakForTest(pak_path);
  ResourceBundle::ReloadSharedInstance("he");
#if defined(OS_POSIX) && defined(TOOLKIT_USES_GTK)
  gtk_widget_set_default_direction(GTK_TEXT_DIR_RTL);
#endif
}

void WebUIBidiCheckerBrowserTestFakeBidi::CleanUpOnMainThread() {
  WebUIBidiCheckerBrowserTest::CleanUpOnMainThread();
#if defined(OS_POSIX) && defined(TOOLKIT_USES_GTK)
  gtk_widget_set_default_direction(GTK_TEXT_DIR_LTR);
#endif
  ResourceBundle::GetSharedInstance().OverrideLocalePakForTest(FilePath());
  ResourceBundle::ReloadSharedInstance(app_locale_);
}

// Tests

IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestMainHistoryPageLTR) {
  HistoryService* history_service =
      browser()->profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
  GURL history_url = GURL("http://www.ynet.co.il");
  history_service->AddPage(history_url, history::SOURCE_BROWSED);
  string16 title;
  ASSERT_TRUE(UTF8ToUTF16("\xD7\x91\xD7\x93\xD7\x99\xD7\xA7\xD7\x94\x21",
                          12,
                          &title));
  history_service->SetPageTitle(history_url, title);
  RunBidiCheckerOnPage(chrome::kChromeUIHistoryURL, false);
}

IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
                       MAYBE_TestMainHistoryPageRTL) {
  HistoryService* history_service =
      browser()->profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
  GURL history_url = GURL("http://www.google.com");
  history_service->AddPage(history_url, history::SOURCE_BROWSED);
  string16 title = UTF8ToUTF16("Google");
  history_service->SetPageTitle(history_url, title);
  WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUIHistoryURL,
                                                    true);
}

IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestAboutPageLTR) {
  RunBidiCheckerOnPage(chrome::kChromeUIAboutURL, false);
}

IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestBugReportPageLTR) {
  RunBidiCheckerOnPage(chrome::kChromeUIBugReportURL, false);
}

IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestCrashesPageLTR) {
  RunBidiCheckerOnPage(chrome::kChromeUICrashesURL, false);
}

IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
                       MAYBE_TestCrashesPageRTL) {
  WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUICrashesURL,
                                                    true);
}

IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestDownloadsPageLTR) {
  RunBidiCheckerOnPage(chrome::kChromeUIDownloadsURL, false);
}

IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
                       MAYBE_TestDownloadsPageRTL) {
  WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(
      chrome::kChromeUIDownloadsURL, true);
}

IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestNewTabPageLTR) {
  RunBidiCheckerOnPage(chrome::kChromeUINewTabURL, false);
}

IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
                       MAYBE_TestNewTabPageRTL) {
  WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUINewTabURL,
                                                    true);
}

IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestPluginsPageLTR) {
  RunBidiCheckerOnPage(chrome::kChromeUIPluginsURL, false);
}

IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
                       MAYBE_TestPluginsPageRTL) {
  WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUIPluginsURL,
                                                    true);
}

IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestSettingsPageLTR) {
  RunBidiCheckerOnPage(chrome::kChromeUISettingsURL, false);
}

IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
                       MAYBE_TestSettingsPageRTL) {
  WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(
      chrome::kChromeUISettingsURL, true);
}

#if defined(OS_MACOSX)
// http://crbug.com/94642
#define MAYBE_TestSettingsAutofillPageLTR FLAKY_TestSettingsAutofillPageLTR
#elif defined(OS_WIN)
// http://crbug.com/95425
#define MAYBE_TestSettingsAutofillPageLTR FAILS_TestSettingsAutofillPageLTR
#else
#define MAYBE_TestSettingsAutofillPageLTR TestSettingsAutofillPageLTR
#endif  // defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest,
                       MAYBE_TestSettingsAutofillPageLTR) {
  std::string url(chrome::kChromeUISettingsURL);
  url += std::string(chrome::kAutofillSubPage);

  autofill_test::DisableSystemServices(browser()->profile());
  AutofillProfile profile;
  autofill_test::SetProfileInfo(
      &profile,
      "\xD7\x9E\xD7\xA9\xD7\x94",
      "\xD7\x91",
      "\xD7\x9B\xD7\x94\xD7\x9F",
      "moshe.b.cohen@biditest.com",
      "\xD7\x91\xD7\x93\xD7\x99\xD7\xA7\xD7\x94\x20\xD7\x91\xD7\xA2\xD7\x9E",
      "\xD7\x93\xD7\xA8\xD7\x9A\x20\xD7\x9E\xD7\xA0\xD7\x97\xD7\x9D\x20\xD7\x91\xD7\x92\xD7\x99\xD7\x9F\x20\x32\x33",
      "\xD7\xA7\xD7\x95\xD7\x9E\xD7\x94\x20\x32\x36",
      "\xD7\xAA\xD7\x9C\x20\xD7\x90\xD7\x91\xD7\x99\xD7\x91",
      "",
      "66183",
      "\xD7\x99\xD7\xA9\xD7\xA8\xD7\x90\xD7\x9C",
      "0000");

  PersonalDataManager* personal_data_manager =
    PersonalDataManagerFactory::GetForProfile(browser()->profile());
  ASSERT_TRUE(personal_data_manager);

  personal_data_manager->AddProfile(profile);

  RunBidiCheckerOnPage(url.c_str(), false);
}

IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
                       MAYBE_TestSettingsAutofillPageRTL) {
  std::string url(chrome::kChromeUISettingsURL);
  url += std::string(chrome::kAutofillSubPage);

  autofill_test::DisableSystemServices(browser()->profile());
  AutofillProfile profile;
  autofill_test::SetProfileInfo(
                                &profile,
                                "Milton",
                                "C.",
                                "Waddams",
                                "red.swingline@initech.com",
                                "Initech",
                                "4120 Freidrich Lane",
                                "Basement",
                                "Austin",
                                "Texas",
                                "78744",
                                "United States",
                                "5125551234");

  PersonalDataManager* personal_data_manager =
      PersonalDataManagerFactory::GetForProfile(browser()->profile());
  ASSERT_TRUE(personal_data_manager);

  personal_data_manager->AddProfile(profile);

  WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(url.c_str(), true);
}
<commit_msg>Fixing bidi checker issues on linux views.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/webui/bidi_checker_web_ui_test.h"

#include "base/base_paths.h"
#include "base/i18n/rtl.h"
#include "base/path_service.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/autofill/autofill_common_test.h"
#include "chrome/browser/autofill/autofill_profile.h"
#include "chrome/browser/autofill/personal_data_manager.h"
#include "chrome/browser/autofill/personal_data_manager_factory.h"
#include "chrome/browser/history/history.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/ui_test_utils.h"
#include "ui/base/resource/resource_bundle.h"

#if defined(OS_POSIX) && defined(TOOLKIT_USES_GTK)
#include <gtk/gtk.h>
#endif

static const FilePath::CharType* kWebUIBidiCheckerLibraryJS =
    FILE_PATH_LITERAL("third_party/bidichecker/bidichecker_packaged.js");

namespace {
FilePath WebUIBidiCheckerLibraryJSPath() {
  FilePath src_root;
  if (!PathService::Get(base::DIR_SOURCE_ROOT, &src_root))
    LOG(ERROR) << "Couldn't find source root";
  return src_root.Append(kWebUIBidiCheckerLibraryJS);
}
}

static const FilePath::CharType* kBidiCheckerTestsJS =
    FILE_PATH_LITERAL("bidichecker_tests.js");

WebUIBidiCheckerBrowserTest::~WebUIBidiCheckerBrowserTest() {}

WebUIBidiCheckerBrowserTest::WebUIBidiCheckerBrowserTest() {}

void WebUIBidiCheckerBrowserTest::SetUpInProcessBrowserTestFixture() {
  WebUIBrowserTest::SetUpInProcessBrowserTestFixture();
  WebUIBrowserTest::AddLibrary(WebUIBidiCheckerLibraryJSPath());
  WebUIBrowserTest::AddLibrary(FilePath(kBidiCheckerTestsJS));
}

void WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(const char pageURL[],
                                                       bool isRTL) {
  ui_test_utils::NavigateToURL(browser(), GURL(pageURL));
  ASSERT_TRUE(RunJavascriptTest("runBidiChecker",
                                Value::CreateStringValue(pageURL),
                                Value::CreateBooleanValue(isRTL)));
}

// WebUIBidiCheckerBrowserTestFakeBidi

WebUIBidiCheckerBrowserTestFakeBidi::~WebUIBidiCheckerBrowserTestFakeBidi() {}

WebUIBidiCheckerBrowserTestFakeBidi::WebUIBidiCheckerBrowserTestFakeBidi() {}

void WebUIBidiCheckerBrowserTestFakeBidi::SetUpOnMainThread() {
  WebUIBidiCheckerBrowserTest::SetUpOnMainThread();
  FilePath pak_path;
  app_locale_ = base::i18n::GetConfiguredLocale();
  ASSERT_TRUE(PathService::Get(base::FILE_MODULE, &pak_path));
  pak_path = pak_path.DirName();
  pak_path = pak_path.AppendASCII("pseudo_locales");
  pak_path = pak_path.AppendASCII("fake-bidi");
  pak_path = pak_path.ReplaceExtension(FILE_PATH_LITERAL("pak"));
  ResourceBundle::GetSharedInstance().OverrideLocalePakForTest(pak_path);
  ResourceBundle::ReloadSharedInstance("he");
  base::i18n::SetICUDefaultLocale("he");
#if defined(OS_POSIX) && defined(TOOLKIT_USES_GTK)
  gtk_widget_set_default_direction(GTK_TEXT_DIR_RTL);
#endif
}

void WebUIBidiCheckerBrowserTestFakeBidi::CleanUpOnMainThread() {
  WebUIBidiCheckerBrowserTest::CleanUpOnMainThread();
#if defined(OS_POSIX) && defined(TOOLKIT_USES_GTK)
  gtk_widget_set_default_direction(GTK_TEXT_DIR_LTR);
#endif
  base::i18n::SetICUDefaultLocale(app_locale_);
  ResourceBundle::GetSharedInstance().OverrideLocalePakForTest(FilePath());
  ResourceBundle::ReloadSharedInstance(app_locale_);
}

// Tests

IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestMainHistoryPageLTR) {
  HistoryService* history_service =
      browser()->profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
  GURL history_url = GURL("http://www.ynet.co.il");
  history_service->AddPage(history_url, history::SOURCE_BROWSED);
  string16 title;
  ASSERT_TRUE(UTF8ToUTF16("\xD7\x91\xD7\x93\xD7\x99\xD7\xA7\xD7\x94\x21",
                          12,
                          &title));
  history_service->SetPageTitle(history_url, title);
  RunBidiCheckerOnPage(chrome::kChromeUIHistoryURL, false);
}

IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
                       TestMainHistoryPageRTL) {
  HistoryService* history_service =
      browser()->profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
  GURL history_url = GURL("http://www.google.com");
  history_service->AddPage(history_url, history::SOURCE_BROWSED);
  string16 title = UTF8ToUTF16("Google");
  history_service->SetPageTitle(history_url, title);
  WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUIHistoryURL,
                                                    true);
}

IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestAboutPageLTR) {
  RunBidiCheckerOnPage(chrome::kChromeUIAboutURL, false);
}

IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestBugReportPageLTR) {
  RunBidiCheckerOnPage(chrome::kChromeUIBugReportURL, false);
}

IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestCrashesPageLTR) {
  RunBidiCheckerOnPage(chrome::kChromeUICrashesURL, false);
}

IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
                       TestCrashesPageRTL) {
  WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUICrashesURL,
                                                    true);
}

IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestDownloadsPageLTR) {
  RunBidiCheckerOnPage(chrome::kChromeUIDownloadsURL, false);
}

IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
                       TestDownloadsPageRTL) {
  WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(
      chrome::kChromeUIDownloadsURL, true);
}

IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestNewTabPageLTR) {
  RunBidiCheckerOnPage(chrome::kChromeUINewTabURL, false);
}

// http://crbug.com/97453
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
                       DISABLED_TestNewTabPageRTL) {
  WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUINewTabURL,
                                                    true);
}

IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestPluginsPageLTR) {
  RunBidiCheckerOnPage(chrome::kChromeUIPluginsURL, false);
}

IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
                       TestPluginsPageRTL) {
  WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUIPluginsURL,
                                                    true);
}

IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestSettingsPageLTR) {
  RunBidiCheckerOnPage(chrome::kChromeUISettingsURL, false);
}

IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
                       TestSettingsPageRTL) {
  WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(
      chrome::kChromeUISettingsURL, true);
}

#if defined(OS_MACOSX)
// http://crbug.com/94642
#define MAYBE_TestSettingsAutofillPageLTR FLAKY_TestSettingsAutofillPageLTR
#elif defined(OS_WIN)
// http://crbug.com/95425
#define MAYBE_TestSettingsAutofillPageLTR FAILS_TestSettingsAutofillPageLTR
#else
#define MAYBE_TestSettingsAutofillPageLTR TestSettingsAutofillPageLTR
#endif  // defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest,
                       MAYBE_TestSettingsAutofillPageLTR) {
  std::string url(chrome::kChromeUISettingsURL);
  url += std::string(chrome::kAutofillSubPage);

  autofill_test::DisableSystemServices(browser()->profile());
  AutofillProfile profile;
  autofill_test::SetProfileInfo(
      &profile,
      "\xD7\x9E\xD7\xA9\xD7\x94",
      "\xD7\x91",
      "\xD7\x9B\xD7\x94\xD7\x9F",
      "moshe.b.cohen@biditest.com",
      "\xD7\x91\xD7\x93\xD7\x99\xD7\xA7\xD7\x94\x20\xD7\x91\xD7\xA2\xD7\x9E",
      "\xD7\x93\xD7\xA8\xD7\x9A\x20\xD7\x9E\xD7\xA0\xD7\x97\xD7\x9D\x20\xD7\x91\xD7\x92\xD7\x99\xD7\x9F\x20\x32\x33",
      "\xD7\xA7\xD7\x95\xD7\x9E\xD7\x94\x20\x32\x36",
      "\xD7\xAA\xD7\x9C\x20\xD7\x90\xD7\x91\xD7\x99\xD7\x91",
      "",
      "66183",
      "\xD7\x99\xD7\xA9\xD7\xA8\xD7\x90\xD7\x9C",
      "0000");

  PersonalDataManager* personal_data_manager =
    PersonalDataManagerFactory::GetForProfile(browser()->profile());
  ASSERT_TRUE(personal_data_manager);

  personal_data_manager->AddProfile(profile);

  RunBidiCheckerOnPage(url.c_str(), false);
}

IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
                       TestSettingsAutofillPageRTL) {
  std::string url(chrome::kChromeUISettingsURL);
  url += std::string(chrome::kAutofillSubPage);

  autofill_test::DisableSystemServices(browser()->profile());
  AutofillProfile profile;
  autofill_test::SetProfileInfo(
                                &profile,
                                "Milton",
                                "C.",
                                "Waddams",
                                "red.swingline@initech.com",
                                "Initech",
                                "4120 Freidrich Lane",
                                "Basement",
                                "Austin",
                                "Texas",
                                "78744",
                                "United States",
                                "5125551234");

  PersonalDataManager* personal_data_manager =
      PersonalDataManagerFactory::GetForProfile(browser()->profile());
  ASSERT_TRUE(personal_data_manager);

  personal_data_manager->AddProfile(profile);

  WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(url.c_str(), true);
}
<|endoftext|>