<commit_before>#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"

#ifdef __APPLE__
#if TARGET_IOS
#import <OpenGLES/ES2/gl.h>
#import <OpenGLES/ES2/glext.h>
#else
#import <OpenGL/OpenGL.h>
#import <OpenGL/gl3.h>
#endif
#else
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <EGL/egl.h>
#endif

#include <functional>
#include <memory>
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <unordered_set>
#include <map>
#include <cstdint>
#include <string>
#include <tuple>
#include <utility>
#include <array>
#include <stdio.h>
#include <cmath>

#include "NativeBitmap.h"
#include "Texture.h"
#include "Material.h"
#include "Trig.h"
#include "TrigBatch.h"
#include "MeshObject.h"
#include "MaterialList.h"
#include "Scene.h"
#include "WavefrontOBJReader.h"
#include "Logger.h"

#include "AudioSink.h"
#include "SoundClip.h"
#include "SoundUtils.h"
#include "SoundListener.h"
#include "SoundEmitter.h"

#include "Vec2i.h"
#include "IMapElement.h"
#include "CActor.h"
#include "CGameDelegate.h"
#include "CMap.h"

#include "VBORenderingJob.h"
#include "DungeonGLES2Renderer.h"
#include "LightningStrategy.h"
#include "GameNativeAPI.h"

#include "IRenderer.h"
#include "NativeBitmap.h"
#include "CKnight.h"
#include "CGame.h"
#include "Common.h"
#include "NoudarGLES2Bridge.h"
#include "SplatAnimation.h"

#include "NoudarDungeonSnapshot.h"

std::shared_ptr<odb::DungeonGLES2Renderer> gles2Renderer = nullptr;
std::map<int, glm::vec2> mPositions;

bool hasActiveSplats;
odb::LightMap lightMap;
odb::AnimationList animationList;
long animationTime = 0;
bool hasCache = false;
odb::LightMap lightMapCache;

std::vector<std::shared_ptr<odb::NativeBitmap>> textures;
std::shared_ptr<Knights::CGame> game;
std::shared_ptr<odb::NoudarGLES2Bridge> render;
std::vector<std::shared_ptr<odb::SoundEmitter>> soundEmitters;
std::vector<std::shared_ptr<odb::SplatAnimation>> splatAnimation;
std::shared_ptr<odb::SoundListener> mainListener;

odb::NoudarDungeonSnapshot snapshot;

bool setupGraphics(int w, int h, std::string vertexShader, std::string fragmentShader, std::vector<std::shared_ptr<odb::NativeBitmap>> textureList ) {
	textures = textureList;

	gles2Renderer = std::make_shared<odb::DungeonGLES2Renderer>();

	gles2Renderer->setTexture(textures);
	animationTime = 0;

	hasCache = false;

	for (int y = 0; y < 20; ++y) {
		for (int x = 0; x < 20; ++x) {
			lightMapCache[ y ][ x ] = 0;
		}
	}

	return gles2Renderer->init(w, h, vertexShader.c_str(), fragmentShader.c_str());
}

void renderFrame(long delta) {
	if (gles2Renderer != nullptr && game != nullptr && textures.size() > 0) {

		gles2Renderer->updateFadeState(delta);
		auto cursor = game->getCursorPosition();
		gles2Renderer->setCursorPosition( cursor.x, cursor.y );
		gles2Renderer->setPlayerHealth( game->getMap()->getAvatar()->getHP() );
		gles2Renderer->render(snapshot.map, snapshot.snapshot, snapshot.splat, lightMap, snapshot.ids, animationList, animationTime);
		gles2Renderer->updateCamera(delta);
	}
}

void shutdown() {
	gles2Renderer->shutdown();
	animationList.clear();
	mPositions.clear();
	animationTime = 0;
	textures.clear();
	hasCache = false;

	for (int y = 0; y < 20; ++y) {
		for (int x = 0; x < 20; ++x) {
			lightMapCache[y][x] = 0;
		}
	}

	gles2Renderer = nullptr;
}

void updateAnimations( long delta ) {
	auto it = animationList.begin();
	while (it != animationList.end()) {
		if (animationTime - (std::get<2>(it->second)) >= odb::kAnimationLength) {
			it = animationList.erase(it);
		} else {
			it = next(it);
		}
	}

	hasActiveSplats = splatAnimation.size() > 0;

	for ( auto splat : splatAnimation ) {
		odb::Logger::log( "updating animatings" );
		splat->update( delta );
	}

	splatAnimation.erase( std::remove_if( splatAnimation.begin(), splatAnimation.end(),
	                              [](std::shared_ptr<odb::SplatAnimation> splat){ return splat->isFinished();}
	), splatAnimation.end() );

	if ( hasActiveSplats ) {
		game->tick();
	}

	animationTime += delta;
}

void addCharacterMovement(int id, glm::vec2 previousPosition, glm::vec2 newPosition) {

	auto movement = std::make_tuple<>(previousPosition, newPosition, animationTime);

	if (animationList.count(id) > 0) {

		auto animation = animationList[id];
		auto prevPosition = std::get<0>(animation);
		animation = std::make_tuple<>(prevPosition, newPosition, animationTime);
	}

	animationList[id] = movement;

	char floorType = snapshot.map[ newPosition.y ][ newPosition.x ];

	if ( floorType  == '.' || floorType == '-' ) {
		soundEmitters[0]->play(mainListener);
	} else if ( floorType == '_' || floorType == '=') {
		soundEmitters[1]->play(mainListener);
	} else {
		if ( floorType == '{' || floorType == '(' || floorType == ')' || floorType == '}' || floorType == '2' || floorType == '7' || '~' ) {
			soundEmitters[1]->play(mainListener);
		}
	}

}

void updateCharacterMovements(const int *idsLocal) {
	int position;
	for (int y = 0; y < Knights::kMapSize; ++y) {
		for (int x = 0; x < Knights::kMapSize; ++x) {

			position = (y * Knights::kMapSize) + x;
			int id = idsLocal[position];
			snapshot.ids[y][x] = id;

			if (id != 0) {
				auto previousPosition = mPositions[id];

				if (previousPosition != glm::vec2(x, y) ) {
					mPositions[id] = glm::vec2(x, y);

					if ( game->getTurn() > 0  ) {
						addCharacterMovement(id, previousPosition, mPositions[id]);
					}
				}
			}
		}
	}
}

void setCameraPosition( int x, int y ) {
	if (gles2Renderer != nullptr) {
		gles2Renderer->setCameraPosition(x, y);
	}
}

void updateLevelSnapshot(const int *level, const int *actors, const int *splats) {
	hasActiveSplats = false;
	int position;

	for (int y = 0; y < Knights::kMapSize; ++y) {
		for (int x = 0; x < Knights::kMapSize; ++x) {
			position = ( Knights::kMapSize * y ) + x;
			snapshot.map[y][x] = (odb::ETextures) level[position];
			snapshot.snapshot[y][x] = (odb::ETextures) actors[position];
			snapshot.splat[y][x] = -1;
			lightMap[y][x] = lightMapCache[y][x];
		}
	}

	for ( auto& splatAnim : splatAnimation ) {
		auto pos = splatAnim->getPosition();
		snapshot.splat[pos.y][pos.x] = static_cast<odb::ETextures >( splatAnim->getSplatFrame());
	}

//	for (int y = 0; y < 20; ++y) {
//		for (int x = 0; x < 20; ++x) {
//
//			if (map[y][x] == '|') {
//
//				if (!hasCache) {
//					odb::LightningStrategy::castLightInAllDirections(lightMapCache, 255, map, x, y);
//					odb::LightningStrategy::castLightInAllDirections(lightMap, 255, map, x, y);
//				}
//			}
//		}
//	}

	hasCache = true;
}

void startFadingIn() {
	if (gles2Renderer != nullptr) {
		gles2Renderer->startFadingIn();
	}
}

void startFadingOut() {
	if (gles2Renderer != nullptr) {
		gles2Renderer->startFadingOut();
	}
}

bool isAnimating() {

	if (gles2Renderer != nullptr) {
		return gles2Renderer->isAnimating() && !hasActiveSplats;
	}

	return false;
}

void rotateCameraLeft() {

	if (gles2Renderer != nullptr&& !isAnimating() ) {
		gles2Renderer->rotateLeft();
		render->setNextCommand('i');
		game->tick();
		render->setNextCommand('.');
	}
}

void rotateCameraRight() {

	if (gles2Renderer != nullptr&& !isAnimating() ) {
		gles2Renderer->rotateRight();
		render->setNextCommand('p');
		game->tick();
		render->setNextCommand('.');
	}
}

void onReleasedLongPressingMove() {
	if (gles2Renderer != nullptr) {
		gles2Renderer->onReleasedLongPressingMove();
	}
}

void onLongPressingMove() {
	if (gles2Renderer != nullptr) {
		gles2Renderer->onLongPressingMove();
	}
}

void setEyeViewMatrix( float* eyeView ) {
	if (gles2Renderer != nullptr) {
		gles2Renderer->setEyeView(eyeView);
	}
}

void setPerspectiveMatrix( float* perspectiveMatrix ) {
	if (gles2Renderer != nullptr) {
		gles2Renderer->setPerspectiveMatrix(perspectiveMatrix);
	}
}

void setAngleXZ( float XZAngle ) {
	if (gles2Renderer != nullptr) {
		gles2Renderer->setAngleXZ(XZAngle);
	}
}

void setAngleYZ( float YZAngle ) {
	if (gles2Renderer != nullptr) {
		gles2Renderer->setAngleYZ(YZAngle);
	}
}

void loadMapData( std::string geoFile, std::string petFile ) {
}

void readMap( std::string data ) {
	render = std::make_shared<odb::NoudarGLES2Bridge>();

	std::string::size_type n = 0;
	while ( ( n = data.find( "\n", n ) ) != std::string::npos )
	{
		data.replace( n, 1, "" );
		++n;
	}

	auto onMonsterDead = [&]( Knights::Vec2i pos ) {
		soundEmitters[ 4 ]->play( mainListener );
	};

	auto onPlayerDead = [&](Knights::Vec2i pos) {
		soundEmitters[ 6 ]->play( mainListener );
	};

	auto onPlayerAttack = [&](Knights::Vec2i pos) {
		soundEmitters[ 7 ]->play( mainListener );
	};

	auto onMonsterAttack = [&](Knights::Vec2i pos) {

	};

	auto onMonsterDamaged = [&](Knights::Vec2i pos) {
		auto splat = std::make_shared<odb::SplatAnimation>( pos );
		splatAnimation.push_back( splat );
		splat->startSplatAnimation();

		soundEmitters[ 3 ]->play( mainListener );
	};

	auto onPlayerDamaged = [&](Knights::Vec2i pos) {
		soundEmitters[ 5 ]->play( mainListener );
	};

	auto gameDelegate = std::make_shared<Knights::CGameDelegate>();

	gameDelegate->setMonsterAttackedCallback( onMonsterAttack );
	gameDelegate->setMonsterDiedCallback( onMonsterDead );
	gameDelegate->setMonsterDamagedCallback(onMonsterDamaged);
	gameDelegate->setPlayerAttackedCallback( onPlayerAttack );
	gameDelegate->setPlayerDiedCallback( onPlayerDead );
	gameDelegate->setPlayerDamagedCallback( onPlayerDamaged );

	game = std::make_shared<Knights::CGame>( data, render, gameDelegate );

	if ( game != nullptr ) {
		game->tick();
	}
}

void moveUp() {

	if ( game != nullptr && !isAnimating() ) {
		render->setNextCommand('o');
		game->tick();
		render->setNextCommand('.');
	}
}

void moveDown() {

	if ( game != nullptr && !isAnimating() ) {
		render->setNextCommand('p');
		game->tick();
		render->setNextCommand('p');
		game->tick();
		render->setNextCommand('o');
		game->tick();
		render->setNextCommand('i');
		game->tick();
		render->setNextCommand('i');
		game->tick();
		render->setNextCommand('.');
	}
}

void moveLeft() {

	if ( game != nullptr && !isAnimating() ) {
		render->setNextCommand('i');
		game->tick();
		render->setNextCommand('o');
		game->tick();
		render->setNextCommand('p');
		game->tick();
		render->setNextCommand('.');
	}
}

void moveRight() {

	if ( game != nullptr && !isAnimating() ) {
		render->setNextCommand('p');
		game->tick();
		render->setNextCommand('o');
		game->tick();
		render->setNextCommand('i');
		game->tick();
		render->setNextCommand('.');
	}
}

void gameLoopTick( long ms ) {
    updateAnimations( ms );
}

void setSoundEmitters( std::vector<std::shared_ptr<odb::SoundEmitter>> emitters, std::shared_ptr<odb::SoundListener> listener ) {
	soundEmitters = emitters;
	mainListener = listener;
}

void forceDirection( int direction ) {
	char directions[] = { 'r', 'f', 'c', 'd'};
	render->setNextCommand( directions[ direction ] );
	game->tick();
	render->setNextCommand('.');

}
<commit_msg>Enable back the lightning<commit_after>#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"

#ifdef __APPLE__
#if TARGET_IOS
#import <OpenGLES/ES2/gl.h>
#import <OpenGLES/ES2/glext.h>
#else
#import <OpenGL/OpenGL.h>
#import <OpenGL/gl3.h>
#endif
#else
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <EGL/egl.h>
#endif

#include <functional>
#include <memory>
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <unordered_set>
#include <map>
#include <cstdint>
#include <string>
#include <tuple>
#include <utility>
#include <array>
#include <stdio.h>
#include <cmath>

#include "NativeBitmap.h"
#include "Texture.h"
#include "Material.h"
#include "Trig.h"
#include "TrigBatch.h"
#include "MeshObject.h"
#include "MaterialList.h"
#include "Scene.h"
#include "WavefrontOBJReader.h"
#include "Logger.h"

#include "AudioSink.h"
#include "SoundClip.h"
#include "SoundUtils.h"
#include "SoundListener.h"
#include "SoundEmitter.h"

#include "Vec2i.h"
#include "IMapElement.h"
#include "CActor.h"
#include "CGameDelegate.h"
#include "CMap.h"

#include "VBORenderingJob.h"
#include "DungeonGLES2Renderer.h"
#include "LightningStrategy.h"
#include "GameNativeAPI.h"

#include "IRenderer.h"
#include "NativeBitmap.h"
#include "CKnight.h"
#include "CGame.h"
#include "Common.h"
#include "NoudarGLES2Bridge.h"
#include "SplatAnimation.h"

#include "NoudarDungeonSnapshot.h"

std::shared_ptr<odb::DungeonGLES2Renderer> gles2Renderer = nullptr;
std::map<int, glm::vec2> mPositions;

bool hasActiveSplats;
odb::LightMap lightMap;
odb::AnimationList animationList;
long animationTime = 0;
bool hasCache = false;
odb::LightMap lightMapCache;

std::vector<std::shared_ptr<odb::NativeBitmap>> textures;
std::shared_ptr<Knights::CGame> game;
std::shared_ptr<odb::NoudarGLES2Bridge> render;
std::vector<std::shared_ptr<odb::SoundEmitter>> soundEmitters;
std::vector<std::shared_ptr<odb::SplatAnimation>> splatAnimation;
std::shared_ptr<odb::SoundListener> mainListener;

odb::NoudarDungeonSnapshot snapshot;

bool setupGraphics(int w, int h, std::string vertexShader, std::string fragmentShader, std::vector<std::shared_ptr<odb::NativeBitmap>> textureList ) {
	textures = textureList;

	gles2Renderer = std::make_shared<odb::DungeonGLES2Renderer>();

	gles2Renderer->setTexture(textures);
	animationTime = 0;

	hasCache = false;

	for (int y = 0; y < 20; ++y) {
		for (int x = 0; x < 20; ++x) {
			lightMapCache[ y ][ x ] = 0;
		}
	}

	return gles2Renderer->init(w, h, vertexShader.c_str(), fragmentShader.c_str());
}

void renderFrame(long delta) {
	if (gles2Renderer != nullptr && game != nullptr && textures.size() > 0) {

		gles2Renderer->updateFadeState(delta);
		auto cursor = game->getCursorPosition();
		gles2Renderer->setCursorPosition( cursor.x, cursor.y );
		gles2Renderer->setPlayerHealth( game->getMap()->getAvatar()->getHP() );
		gles2Renderer->render(snapshot.map, snapshot.snapshot, snapshot.splat, lightMap, snapshot.ids, animationList, animationTime);
		gles2Renderer->updateCamera(delta);
	}
}

void shutdown() {
	gles2Renderer->shutdown();
	animationList.clear();
	mPositions.clear();
	animationTime = 0;
	textures.clear();
	hasCache = false;

	for (int y = 0; y < 20; ++y) {
		for (int x = 0; x < 20; ++x) {
			lightMapCache[y][x] = 0;
		}
	}

	gles2Renderer = nullptr;
}

void updateAnimations( long delta ) {
	auto it = animationList.begin();
	while (it != animationList.end()) {
		if (animationTime - (std::get<2>(it->second)) >= odb::kAnimationLength) {
			it = animationList.erase(it);
		} else {
			it = next(it);
		}
	}

	hasActiveSplats = splatAnimation.size() > 0;

	for ( auto splat : splatAnimation ) {
		odb::Logger::log( "updating animatings" );
		splat->update( delta );
	}

	splatAnimation.erase( std::remove_if( splatAnimation.begin(), splatAnimation.end(),
	                              [](std::shared_ptr<odb::SplatAnimation> splat){ return splat->isFinished();}
	), splatAnimation.end() );

	if ( hasActiveSplats ) {
		game->tick();
	}

	animationTime += delta;
}

void addCharacterMovement(int id, glm::vec2 previousPosition, glm::vec2 newPosition) {

	auto movement = std::make_tuple<>(previousPosition, newPosition, animationTime);

	if (animationList.count(id) > 0) {

		auto animation = animationList[id];
		auto prevPosition = std::get<0>(animation);
		animation = std::make_tuple<>(prevPosition, newPosition, animationTime);
	}

	animationList[id] = movement;

	char floorType = snapshot.map[ newPosition.y ][ newPosition.x ];

	if ( floorType  == '.' || floorType == '-' ) {
		soundEmitters[0]->play(mainListener);
	} else if ( floorType == '_' || floorType == '=') {
		soundEmitters[1]->play(mainListener);
	} else {
		if ( floorType == '{' || floorType == '(' || floorType == ')' || floorType == '}' || floorType == '2' || floorType == '7' || '~' ) {
			soundEmitters[1]->play(mainListener);
		}
	}

}

void updateCharacterMovements(const int *idsLocal) {
	int position;
	for (int y = 0; y < Knights::kMapSize; ++y) {
		for (int x = 0; x < Knights::kMapSize; ++x) {

			position = (y * Knights::kMapSize) + x;
			int id = idsLocal[position];
			snapshot.ids[y][x] = id;

			if (id != 0) {
				auto previousPosition = mPositions[id];

				if (previousPosition != glm::vec2(x, y) ) {
					mPositions[id] = glm::vec2(x, y);

					if ( game->getTurn() > 0  ) {
						addCharacterMovement(id, previousPosition, mPositions[id]);
					}
				}
			}
		}
	}
}

void setCameraPosition( int x, int y ) {
	if (gles2Renderer != nullptr) {
		gles2Renderer->setCameraPosition(x, y);
	}
}

void updateLevelSnapshot(const int *level, const int *actors, const int *splats) {
	hasActiveSplats = false;
	int position;

	for (int y = 0; y < Knights::kMapSize; ++y) {
		for (int x = 0; x < Knights::kMapSize; ++x) {
			position = ( Knights::kMapSize * y ) + x;
			snapshot.map[y][x] = (odb::ETextures) level[position];
			snapshot.snapshot[y][x] = (odb::ETextures) actors[position];
			snapshot.splat[y][x] = -1;
			lightMap[y][x] = lightMapCache[y][x];
		}
	}

	for ( auto& splatAnim : splatAnimation ) {
		auto pos = splatAnim->getPosition();
		snapshot.splat[pos.y][pos.x] = static_cast<odb::ETextures >( splatAnim->getSplatFrame());
	}

	for (int y = 0; y < 20; ++y) {
		for (int x = 0; x < 20; ++x) {

			if (snapshot.map[y][x] == '|') {

				if (!hasCache) {
					odb::LightningStrategy::castLightInAllDirections(lightMapCache, 255, snapshot.map, x, y);
					odb::LightningStrategy::castLightInAllDirections(lightMap, 255, snapshot.map, x, y);
				}
			}
		}
	}

	hasCache = true;
}

void startFadingIn() {
	if (gles2Renderer != nullptr) {
		gles2Renderer->startFadingIn();
	}
}

void startFadingOut() {
	if (gles2Renderer != nullptr) {
		gles2Renderer->startFadingOut();
	}
}

bool isAnimating() {

	if (gles2Renderer != nullptr) {
		return gles2Renderer->isAnimating() && !hasActiveSplats;
	}

	return false;
}

void rotateCameraLeft() {

	if (gles2Renderer != nullptr&& !isAnimating() ) {
		gles2Renderer->rotateLeft();
		render->setNextCommand('i');
		game->tick();
		render->setNextCommand('.');
	}
}

void rotateCameraRight() {

	if (gles2Renderer != nullptr&& !isAnimating() ) {
		gles2Renderer->rotateRight();
		render->setNextCommand('p');
		game->tick();
		render->setNextCommand('.');
	}
}

void onReleasedLongPressingMove() {
	if (gles2Renderer != nullptr) {
		gles2Renderer->onReleasedLongPressingMove();
	}
}

void onLongPressingMove() {
	if (gles2Renderer != nullptr) {
		gles2Renderer->onLongPressingMove();
	}
}

void setEyeViewMatrix( float* eyeView ) {
	if (gles2Renderer != nullptr) {
		gles2Renderer->setEyeView(eyeView);
	}
}

void setPerspectiveMatrix( float* perspectiveMatrix ) {
	if (gles2Renderer != nullptr) {
		gles2Renderer->setPerspectiveMatrix(perspectiveMatrix);
	}
}

void setAngleXZ( float XZAngle ) {
	if (gles2Renderer != nullptr) {
		gles2Renderer->setAngleXZ(XZAngle);
	}
}

void setAngleYZ( float YZAngle ) {
	if (gles2Renderer != nullptr) {
		gles2Renderer->setAngleYZ(YZAngle);
	}
}

void loadMapData( std::string geoFile, std::string petFile ) {
}

void readMap( std::string data ) {
	render = std::make_shared<odb::NoudarGLES2Bridge>();

	std::string::size_type n = 0;
	while ( ( n = data.find( "\n", n ) ) != std::string::npos )
	{
		data.replace( n, 1, "" );
		++n;
	}

	auto onMonsterDead = [&]( Knights::Vec2i pos ) {
		soundEmitters[ 4 ]->play( mainListener );
	};

	auto onPlayerDead = [&](Knights::Vec2i pos) {
		soundEmitters[ 6 ]->play( mainListener );
	};

	auto onPlayerAttack = [&](Knights::Vec2i pos) {
		soundEmitters[ 7 ]->play( mainListener );
	};

	auto onMonsterAttack = [&](Knights::Vec2i pos) {

	};

	auto onMonsterDamaged = [&](Knights::Vec2i pos) {
		auto splat = std::make_shared<odb::SplatAnimation>( pos );
		splatAnimation.push_back( splat );
		splat->startSplatAnimation();

		soundEmitters[ 3 ]->play( mainListener );
	};

	auto onPlayerDamaged = [&](Knights::Vec2i pos) {
		soundEmitters[ 5 ]->play( mainListener );
	};

	auto gameDelegate = std::make_shared<Knights::CGameDelegate>();

	gameDelegate->setMonsterAttackedCallback( onMonsterAttack );
	gameDelegate->setMonsterDiedCallback( onMonsterDead );
	gameDelegate->setMonsterDamagedCallback(onMonsterDamaged);
	gameDelegate->setPlayerAttackedCallback( onPlayerAttack );
	gameDelegate->setPlayerDiedCallback( onPlayerDead );
	gameDelegate->setPlayerDamagedCallback( onPlayerDamaged );

	game = std::make_shared<Knights::CGame>( data, render, gameDelegate );

	if ( game != nullptr ) {
		game->tick();
	}
}

void moveUp() {

	if ( game != nullptr && !isAnimating() ) {
		render->setNextCommand('o');
		game->tick();
		render->setNextCommand('.');
	}
}

void moveDown() {

	if ( game != nullptr && !isAnimating() ) {
		render->setNextCommand('p');
		game->tick();
		render->setNextCommand('p');
		game->tick();
		render->setNextCommand('o');
		game->tick();
		render->setNextCommand('i');
		game->tick();
		render->setNextCommand('i');
		game->tick();
		render->setNextCommand('.');
	}
}

void moveLeft() {

	if ( game != nullptr && !isAnimating() ) {
		render->setNextCommand('i');
		game->tick();
		render->setNextCommand('o');
		game->tick();
		render->setNextCommand('p');
		game->tick();
		render->setNextCommand('.');
	}
}

void moveRight() {

	if ( game != nullptr && !isAnimating() ) {
		render->setNextCommand('p');
		game->tick();
		render->setNextCommand('o');
		game->tick();
		render->setNextCommand('i');
		game->tick();
		render->setNextCommand('.');
	}
}

void gameLoopTick( long ms ) {
    updateAnimations( ms );
}

void setSoundEmitters( std::vector<std::shared_ptr<odb::SoundEmitter>> emitters, std::shared_ptr<odb::SoundListener> listener ) {
	soundEmitters = emitters;
	mainListener = listener;
}

void forceDirection( int direction ) {
	char directions[] = { 'r', 'f', 'c', 'd'};
	render->setNextCommand( directions[ direction ] );
	game->tick();
	render->setNextCommand('.');

}
<|endoftext|>


<commit_before>//******************************************************************************
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// 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 "ApplicationMain.h"
#include "StringHelpers.h"
#include "winobjc\winobjc.h"

#include <assert.h>
#include <string>

using namespace Windows::Foundation;
using namespace Windows::UI::Core;
using namespace Windows::System::Threading;

void EbrSetWritableFolder(const char* folder);
void IWSetTemporaryFolder(const char* folder);

typedef void* EbrEvent;

int EbrEventTimedMultipleWait(EbrEvent* events, int numEvents, double timeout, SocketWait* sockets);

void* g_XamlUIFiber = nullptr;
void* g_WinObjcUIFiber = nullptr;

int XamlTimedMultipleWait(EbrEvent* events, int numEvents, double timeout, SocketWait* sockets) {
    //  If our current fiber is the main winobjc UI thread,
    //  we perform the wait on a separate worker thread, then
    //  yield to the Xaml Dispatcher fiber.  Once the worker thread wakes
    //  up, it will queue the result on the Xaml dispatcher, then
    //  have it switch back to the winobjc fiber with the result
    if (::GetCurrentFiber() == g_WinObjcUIFiber) {
        int retval = 0;
        bool signaled = false;
        auto dispatcher = CoreWindow::GetForCurrentThread()->Dispatcher;
        ThreadPool::RunAsync(
            ref new WorkItemHandler([&retval, &signaled, events, numEvents, timeout, sockets, dispatcher](IAsyncAction ^ action) {
            //  Wait for an event
            retval = EbrEventTimedMultipleWait(events, numEvents, timeout, sockets);
            signaled = true;

            //  Dispatch it on the UI thread
            dispatcher->RunAsync(CoreDispatcherPriority::High, ref new DispatchedHandler([]()
            {
                ::SwitchToFiber(g_WinObjcUIFiber);
            }));
        }));

        //  ** WARNING ** The "local" retval is passed by ref to the lamba - never wake up this
        //  fiber from somewhere else!
        ::SwitchToFiber(g_XamlUIFiber);

        assert(signaled);
        return retval;
    }
    else {
        return EbrEventTimedMultipleWait(events, numEvents, timeout, sockets);
    }
}

extern "C" unsigned int XamlWaitHandle(uintptr_t hEvent, unsigned int timeout) {
    int retval = 0;
    bool signaled = false;
    auto dispatcher = CoreWindow::GetForCurrentThread()->Dispatcher;
    ThreadPool::RunAsync(
        ref new WorkItemHandler([&retval, &signaled, hEvent, timeout, dispatcher](IAsyncAction ^ action) {
        //  Wait for an event
        retval = WaitForSingleObjectEx((HANDLE)hEvent, timeout, TRUE);
        signaled = true;

        //  Dispatch it on the UI thread
        dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([]()
        {
            ::SwitchToFiber(g_WinObjcUIFiber);
        }));
    }));

    //  ** WARNING ** The "local" retval is passed by ref to the lamba - never wake up this
    //  fiber from somewhere else!
    ::SwitchToFiber(g_XamlUIFiber);

    assert(signaled);
    return retval;
}

struct StartParameters {
    int argc;
    char** argv;
    std::string principalClassName;
    std::string delegateClassName;
    float windowWidth, windowHeight;
};

StartParameters g_startParams = { 0, nullptr, std::string(), std::string(), 0.0f, 0.0f };

static VOID CALLBACK WinObjcMainLoop(LPVOID param) {
    ApplicationMainStart(g_startParams.argc,
                         g_startParams.argv,
                         g_startParams.principalClassName.c_str(),
                         g_startParams.delegateClassName.c_str(),
                         g_startParams.windowWidth,
                         g_startParams.windowHeight);
}

void SetXamlUIWaiter();

static void StartCompositedRunLoop() {
    // Switch this xaml/winrt thread to a fiber, and store it
    ::ConvertThreadToFiberEx(nullptr, FIBER_FLAG_FLOAT_SWITCH);
    g_XamlUIFiber = ::GetCurrentFiber();

    // Create our WinObjC fiber
    const size_t stackCommitSize = 4096 * 4; // 4 pages
    const size_t stackReserveSize = 1024 * 1024; // 1MB
    g_WinObjcUIFiber = ::CreateFiberEx(stackCommitSize, stackReserveSize, FIBER_FLAG_FLOAT_SWITCH, WinObjcMainLoop, nullptr);

    // Switch to the WinObjC fiber to kick off the IOS launch sequence
    ::SwitchToFiber(g_WinObjcUIFiber);
}

void InitializeApp() {
    // Only init once.
    // No lock needed as this is only called from the UI thread.
    static bool initialized = false;
    if (initialized) {
        return;
    }
    initialized = true;

    // Set our writable and temp folders
    char writableFolder[2048];
    size_t outLen;
    auto pathData = Windows::Storage::ApplicationData::Current->LocalFolder->Path->Data();
    wcstombs_s(&outLen, writableFolder, pathData, sizeof(writableFolder));
    EbrSetWritableFolder(writableFolder);

    auto tempPathData = Windows::Storage::ApplicationData::Current->TemporaryFolder->Path->Data();
    wcstombs_s(&outLen, writableFolder, tempPathData, sizeof(writableFolder));
    IWSetTemporaryFolder(writableFolder);

    // Set the waiter routine for yielding waits to the XAML/UI thread
    SetXamlUIWaiter();
}

extern "C" void IWRunApplicationMain(Platform::String^ principalClassName,
                                     Platform::String^ delegateClassName,
                                     float windowWidth,
                                     float windowHeight) {
    // Perform initialization
    InitializeApp();

    // Store the start parameters to hand off to the run loop
    g_startParams.argc = 0;
    g_startParams.argv = nullptr;
    g_startParams.principalClassName = Strings::WideToNarrow(principalClassName->Data());
    g_startParams.delegateClassName = Strings::WideToNarrow(delegateClassName->Data());
    g_startParams.windowWidth = windowWidth;
    g_startParams.windowHeight = windowHeight;

    // Kick off the run loop
    StartCompositedRunLoop();
}
<commit_msg>Don't pass bogus string pointer to wcstomb_s<commit_after>//******************************************************************************
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// 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 "ApplicationMain.h"
#include "StringHelpers.h"
#include "winobjc\winobjc.h"

#include <assert.h>
#include <string>

using namespace Windows::Foundation;
using namespace Windows::UI::Core;
using namespace Windows::System::Threading;

void EbrSetWritableFolder(const char* folder);
void IWSetTemporaryFolder(const char* folder);

typedef void* EbrEvent;

int EbrEventTimedMultipleWait(EbrEvent* events, int numEvents, double timeout, SocketWait* sockets);

void* g_XamlUIFiber = nullptr;
void* g_WinObjcUIFiber = nullptr;

int XamlTimedMultipleWait(EbrEvent* events, int numEvents, double timeout, SocketWait* sockets) {
    //  If our current fiber is the main winobjc UI thread,
    //  we perform the wait on a separate worker thread, then
    //  yield to the Xaml Dispatcher fiber.  Once the worker thread wakes
    //  up, it will queue the result on the Xaml dispatcher, then
    //  have it switch back to the winobjc fiber with the result
    if (::GetCurrentFiber() == g_WinObjcUIFiber) {
        int retval = 0;
        bool signaled = false;
        auto dispatcher = CoreWindow::GetForCurrentThread()->Dispatcher;
        ThreadPool::RunAsync(
            ref new WorkItemHandler([&retval, &signaled, events, numEvents, timeout, sockets, dispatcher](IAsyncAction ^ action) {
            //  Wait for an event
            retval = EbrEventTimedMultipleWait(events, numEvents, timeout, sockets);
            signaled = true;

            //  Dispatch it on the UI thread
            dispatcher->RunAsync(CoreDispatcherPriority::High, ref new DispatchedHandler([]()
            {
                ::SwitchToFiber(g_WinObjcUIFiber);
            }));
        }));

        //  ** WARNING ** The "local" retval is passed by ref to the lamba - never wake up this
        //  fiber from somewhere else!
        ::SwitchToFiber(g_XamlUIFiber);

        assert(signaled);
        return retval;
    }
    else {
        return EbrEventTimedMultipleWait(events, numEvents, timeout, sockets);
    }
}

extern "C" unsigned int XamlWaitHandle(uintptr_t hEvent, unsigned int timeout) {
    int retval = 0;
    bool signaled = false;
    auto dispatcher = CoreWindow::GetForCurrentThread()->Dispatcher;
    ThreadPool::RunAsync(
        ref new WorkItemHandler([&retval, &signaled, hEvent, timeout, dispatcher](IAsyncAction ^ action) {
        //  Wait for an event
        retval = WaitForSingleObjectEx((HANDLE)hEvent, timeout, TRUE);
        signaled = true;

        //  Dispatch it on the UI thread
        dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([]()
        {
            ::SwitchToFiber(g_WinObjcUIFiber);
        }));
    }));

    //  ** WARNING ** The "local" retval is passed by ref to the lamba - never wake up this
    //  fiber from somewhere else!
    ::SwitchToFiber(g_XamlUIFiber);

    assert(signaled);
    return retval;
}

struct StartParameters {
    int argc;
    char** argv;
    std::string principalClassName;
    std::string delegateClassName;
    float windowWidth, windowHeight;
};

StartParameters g_startParams = { 0, nullptr, std::string(), std::string(), 0.0f, 0.0f };

static VOID CALLBACK WinObjcMainLoop(LPVOID param) {
    ApplicationMainStart(g_startParams.argc,
                         g_startParams.argv,
                         g_startParams.principalClassName.c_str(),
                         g_startParams.delegateClassName.c_str(),
                         g_startParams.windowWidth,
                         g_startParams.windowHeight);
}

void SetXamlUIWaiter();

static void StartCompositedRunLoop() {
    // Switch this xaml/winrt thread to a fiber, and store it
    ::ConvertThreadToFiberEx(nullptr, FIBER_FLAG_FLOAT_SWITCH);
    g_XamlUIFiber = ::GetCurrentFiber();

    // Create our WinObjC fiber
    const size_t stackCommitSize = 4096 * 4; // 4 pages
    const size_t stackReserveSize = 1024 * 1024; // 1MB
    g_WinObjcUIFiber = ::CreateFiberEx(stackCommitSize, stackReserveSize, FIBER_FLAG_FLOAT_SWITCH, WinObjcMainLoop, nullptr);

    // Switch to the WinObjC fiber to kick off the IOS launch sequence
    ::SwitchToFiber(g_WinObjcUIFiber);
}

void InitializeApp() {
    // Only init once.
    // No lock needed as this is only called from the UI thread.
    static bool initialized = false;
    if (initialized) {
        return;
    }
    initialized = true;

    // Set our writable and temp folders
    char writableFolder[2048];
    size_t outLen;
    auto pathData = Windows::Storage::ApplicationData::Current->LocalFolder->Path;
    wcstombs_s(&outLen, writableFolder, pathData->Data(), sizeof(writableFolder) - 1);
    EbrSetWritableFolder(writableFolder);

    auto tempPathData = Windows::Storage::ApplicationData::Current->TemporaryFolder->Path;
    wcstombs_s(&outLen, writableFolder, tempPathData->Data(), sizeof(writableFolder) - 1);
    IWSetTemporaryFolder(writableFolder);

    // Set the waiter routine for yielding waits to the XAML/UI thread
    SetXamlUIWaiter();
}

extern "C" void IWRunApplicationMain(Platform::String^ principalClassName,
                                     Platform::String^ delegateClassName,
                                     float windowWidth,
                                     float windowHeight) {
    // Perform initialization
    InitializeApp();

    // Store the start parameters to hand off to the run loop
    g_startParams.argc = 0;
    g_startParams.argv = nullptr;
    g_startParams.principalClassName = Strings::WideToNarrow(principalClassName->Data());
    g_startParams.delegateClassName = Strings::WideToNarrow(delegateClassName->Data());
    g_startParams.windowWidth = windowWidth;
    g_startParams.windowHeight = windowHeight;

    // Kick off the run loop
    StartCompositedRunLoop();
}
<|endoftext|>


<commit_before>// ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //

//! @file

#ifndef DO_IMAGEPROCESSING_WARP_HPP
#define DO_IMAGEPROCESSING_WARP_HPP

#include <DO/ImageProcessing/Interpolation.hpp>

namespace DO {

  template <typename T, typename S>
  void warp(const Image<T>& src, Image<T>& dst,
            const Matrix<S, 3, 3>& homography,
            const T& default_fill_color = PixelTraits<T>::min())
  {
    typedef typename PixelTraits<T>::template Cast<double>::pixel_type
      DoublePixel;
    typedef typename PixelTraits<T>::channel_type ChannelType;
    typedef Matrix<S, 3, 3> Matrix3;
    typedef Matrix<S, 3, 1> Vector3;
    typedef Matrix<S, 2, 1> Vector2;

    const Matrix3& H = homography;

    typename Image<T>::array_iterator it = dst.begin_array();
    for ( ; !it.end(); ++it)
    {
      // Get the corresponding coordinates in the source src.
      Vector3 H_p;
      H_p = H * (Vector3() << it.position().template cast<S>(), 1).finished();
      H_p /= H_p(2);

      // Check if the position is not in the src domain [0,w[ x [0,h[.
      bool position_is_in_src_domain =
        H_p.x() >= 0 || H_p.x() < S(src.width()) ||
        H_p.y() >= 0 || H_p.y() < S(src.height());

      // Fill with either the default value or the interpolated value.
      if (position_is_in_src_domain)
      {
        Vector2 H_p_2(H_p.template head<2>());
        DoublePixel pixel_value( interpolate(src, H_p_2) );
        *it = PixelTraits<DoublePixel>::template Cast<ChannelType>::apply(
          pixel_value);
      }
      else
        *it = default_fill_color;
    }
  }

}

#endif /* DO_IMAGEPROCESSING_WARP_HPP */<commit_msg>Change variable name.<commit_after>// ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //

//! @file

#ifndef DO_IMAGEPROCESSING_WARP_HPP
#define DO_IMAGEPROCESSING_WARP_HPP

#include <DO/ImageProcessing/Interpolation.hpp>

namespace DO {

  template <typename T, typename S>
  void warp(const Image<T>& src, Image<T>& dst,
            const Matrix<S, 3, 3>& homography_from_dst_to_src,
            const T& default_fill_color = PixelTraits<T>::min())
  {
    typedef typename PixelTraits<T>::template Cast<double>::pixel_type
      DoublePixel;
    typedef typename PixelTraits<T>::channel_type ChannelType;
    typedef Matrix<S, 3, 3> Matrix3;
    typedef Matrix<S, 3, 1> Vector3;
    typedef Matrix<S, 2, 1> Vector2;

    const Matrix3& H = homography_from_dst_to_src;

    typename Image<T>::array_iterator it = dst.begin_array();
    for ( ; !it.end(); ++it)
    {
      // Get the corresponding coordinates in the source src.
      Vector3 H_p;
      H_p = H * (Vector3() << it.position().template cast<S>(), 1).finished();
      H_p /= H_p(2);

      // Check if the position is not in the src domain [0,w[ x [0,h[.
      bool position_is_in_src_domain =
        H_p.x() >= 0 || H_p.x() < S(src.width()) ||
        H_p.y() >= 0 || H_p.y() < S(src.height());

      // Fill with either the default value or the interpolated value.
      if (position_is_in_src_domain)
      {
        Vector2 H_p_2(H_p.template head<2>());
        DoublePixel pixel_value( interpolate(src, H_p_2) );
        *it = PixelTraits<DoublePixel>::template Cast<ChannelType>::apply(
          pixel_value);
      }
      else
        *it = default_fill_color;
    }
  }

}

#endif /* DO_IMAGEPROCESSING_WARP_HPP */<|endoftext|>


<commit_before>#include <glm/gtc/matrix_transform.hpp>

#include "Core/Engine.hh"
#include "Core/Renderer.hh"
#include "DemoScene.hh"

#include "ResourceManager/SharedMesh.hh"
#include "ResourceManager/Texture.hh"
#include "ResourceManager/CubeMap.hh"
#include "Components/RotationForce.hh"
#include "Components/MaterialComponent.h"
#include <Components/CameraComponent.hh>
#include <Components/TrackBallComponent.hpp>
#include <OpenGL/ComputeShader.hh>
#include <Systems/RotationForceSystem.hpp>
#include <Systems/MeshRenderSystem.h>
#include <Systems/GraphNodeSystem.hpp>
#include <Systems/CameraSystem.hpp>
#include <Systems/TrackBallSystem.hpp>
#include "ResourceManager/ResourceManager.hh"
#include <Core/Engine.hh>
#include <Entities/EntityManager.h>

#include <SDL\SDL.h>

DemoScene::DemoScene(Engine &engine) : AScene(engine)
{
}

DemoScene::~DemoScene(void)
{
}

Handle	DemoScene::createPlanet(float rotSpeed, float orbitSpeed,
												glm::vec3 &pos, glm::vec3 &scale,
												std::string const &shader,
												std::string const &tex1, std::string const &tex2, std::string const &tex3,
												std::string const &tex4)
{
	auto &m = _engine.getInstance<EntityManager>();
	auto p = m.createEntity();
	auto e = m.createEntity();
	p->addComponent<Component::GraphNode>();
	e->addComponent<Component::GraphNode>();

	e->setLocalTransform() = glm::translate(e->getLocalTransform(), pos);
	e->setLocalTransform() = glm::scale(e->getLocalTransform(), scale);

	SmartPointer<Component::MeshRenderer>	r = e->addComponent<Component::MeshRenderer>("model:ball");

	SmartPointer<Material> materialPlanet = _engine.getInstance<Renderer>().getMaterialManager().createMaterial("material:planet_" + shader);

	materialPlanet->pushShader(shader);

	e->addComponent<Component::MaterialComponent>(std::string("material:planet_" + shader));

	//r->addMaterial(materialPlanet);
	r->addTexture(tex1, 0);
	if (!tex2.empty())
		r->addTexture(tex2, 1);
	if (!tex3.empty())
		r->addTexture(tex3, 2);
	if (!tex4.empty())
		r->addTexture(tex4, 3);

	e->addComponent<Component::RotationForce>(glm::vec3(0, orbitSpeed, 0));
	p->getComponent<Component::GraphNode>()->addSon(e);
	p->addComponent<Component::RotationForce>(glm::vec3(0, rotSpeed, 0));
	return (p);
}

bool 			DemoScene::userStart()
{
	// System Tests
	//
	//

	addSystem<RotationForceSystem>(0);
	addSystem<MeshRendererSystem>(0);
	addSystem<GraphNodeSystem>(100);
	addSystem<TrackBallSystem>(150);
	addSystem<CameraSystem>(200);

	//
	//
	// end System Test

	std::string		perModelVars[] =
	{
		"model"
	};

	std::string		perFrameVars[] =
	{
		"projection",
		"view",
		"light",
		"time"
	};

	OpenGLTools::Shader &s = _engine.getInstance<Renderer>().addShader("earth",
		"./Shaders/earth.vp",
		"./Shaders/earth.fp");
		//.bindActiveTexture("fDayTexture", 0)
		//.bindActiveTexture("fNightTexture", 1)
		//.bindActiveTexture("fClouds", 2)
		//.bindActiveTexture("fBump", 3);

	_engine.getInstance<Renderer>().addUniform("PerFrame")
		.init(&s, "PerFrame", perFrameVars);
	_engine.getInstance<Renderer>().addUniform("PerModel")
		.init(&s, "PerModel", perModelVars);

	_engine.getInstance<Renderer>().addShader("basic", "Shaders/basic.vp", "Shaders/basic.fp", "Shaders/tesselation.gp");
	_engine.getInstance<Renderer>().addShader("basicLight", "Shaders/light.vp", "Shaders/light.fp");
	_engine.getInstance<Renderer>().addShader("bump", "Shaders/bump.vp", "Shaders/bump.fp");
		//.bindActiveTexture("fTexture", 0)
		//.bindActiveTexture("fBump", 1);
	_engine.getInstance<Renderer>().addShader("fboToScreen", "Shaders/fboToScreen.vp", "Shaders/fboToScreen.fp");
	_engine.getInstance<Renderer>().addShader("brightnessFilter", "Shaders/brightnessFilter.vp", "Shaders/brightnessFilter.fp");
	_engine.getInstance<Renderer>().addShader("blurY", "Shaders/brightnessFilter.vp", "Shaders/blur1.fp");

	_engine.getInstance<Renderer>().getShader("basic")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(1).build();
	_engine.getInstance<Renderer>().getShader("basicLight")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(1).build();
	_engine.getInstance<Renderer>().getShader("bump")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(2).build();
	_engine.getInstance<Renderer>().getShader("fboToScreen")->addTarget(GL_COLOR_ATTACHMENT0)
		.addLayer(GL_COLOR_ATTACHMENT0).build();
	_engine.getInstance<Renderer>().getShader("earth")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(4).build();
	_engine.getInstance<Renderer>().getShader("brightnessFilter")->addTarget(GL_COLOR_ATTACHMENT1)
		.addLayer(GL_COLOR_ATTACHMENT0).build();
	_engine.getInstance<Renderer>().getShader("blurY")->addTarget(GL_COLOR_ATTACHMENT2)
		.addLayer(GL_COLOR_ATTACHMENT0).addLayer(GL_COLOR_ATTACHMENT1).build();

	_engine.getInstance<Renderer>().getUniform("PerFrame")->setUniform("light", glm::vec4(0, 0, 0, 1));

	_engine.getInstance<Renderer>().bindShaderToUniform("basicLight", "PerFrame", "PerFrame");
	_engine.getInstance<Renderer>().bindShaderToUniform("basicLight", "PerModel", "PerModel");
	_engine.getInstance<Renderer>().bindShaderToUniform("basic", "PerFrame", "PerFrame");
	_engine.getInstance<Renderer>().bindShaderToUniform("basic", "PerModel", "PerModel");
	_engine.getInstance<Renderer>().bindShaderToUniform("earth", "PerFrame", "PerFrame");
	_engine.getInstance<Renderer>().bindShaderToUniform("earth", "PerModel", "PerModel");
	_engine.getInstance<Renderer>().bindShaderToUniform("bump", "PerFrame", "PerFrame");
	_engine.getInstance<Renderer>().bindShaderToUniform("bump", "PerModel", "PerModel");

	_engine.getInstance<Resources::ResourceManager>().addResource("model:ball", new Resources::SharedMesh(), "./Assets/ball.obj");

	SmartPointer<Resources::Texture>		toRepeat = new Resources::Texture();

	toRepeat->setWrapMode(GL_REPEAT);
	_engine.getInstance<Resources::ResourceManager>().addResource("texture:sun", new Resources::Texture(), "./Assets/SunTexture.tga");
	_engine.getInstance<Resources::ResourceManager>().addResource("texture:earth", new Resources::Texture(), "./Assets/EarthTexture.tga");
	_engine.getInstance<Resources::ResourceManager>().addResource("texture:earthBump", new Resources::Texture(), "./Assets/EarthTextureBump.tga");
	_engine.getInstance<Resources::ResourceManager>().addResource("texture:earthNight", new Resources::Texture(), "./Assets/EarthNightTexture.tga");
	_engine.getInstance<Resources::ResourceManager>().addResource("texture:earthClouds", toRepeat, "./Assets/EarthClouds.tga");
	_engine.getInstance<Resources::ResourceManager>().addResource("texture:sun", new Resources::Texture(), "./Assets/SunTexture.tga");
	_engine.getInstance<Resources::ResourceManager>().addResource("texture:moon", new Resources::Texture(), "./Assets/MoonTexture.tga");
	_engine.getInstance<Resources::ResourceManager>().addResource("texture:moonBump", new Resources::Texture(), "./Assets/MoonNormalMap.tga");

	_engine.getInstance<Resources::ResourceManager>().addResource("cubemap:space", new Resources::CubeMap(), "./Assets/skyboxSpace");

	auto sun = createPlanet(0, 0, glm::vec3(0), glm::vec3(100), "basic", "texture:sun");
	auto earth = createPlanet(7, 20, glm::vec3(300, 0, 0), glm::vec3(20), "earth", "texture:earth", "texture:earthNight", "texture:earthClouds", "texture:earthBump");
	auto moon = createPlanet(0, 10, glm::vec3(5, 0, 0), glm::vec3(0.5), "bump", "texture:moon", "texture:moonBump");

	earth->getComponent<Component::GraphNode>()->getSonsBegin()->get()->getComponent<Component::GraphNode>()->addSon(moon);

	// Generating a lot of planet for performance test
	//
	//

	{
		unsigned int nbPlanet = 500;
		Handle planets[500];

		for (unsigned int i = 0; i < nbPlanet; ++i)
		{
			planets[i] = createPlanet((std::rand() % 200) / 100.0f
				, (std::rand() % 200) / 100.0f,
				glm::vec3(std::rand() % 300 - 150, std::rand() % 300 - 150, std::rand() % 300 - 150),
				glm::vec3(std::rand() % 10 + 10), "basic", "texture:sun");
			if (i == 0)
				sun->getComponent<Component::GraphNode>()->addSon(planets[i]);
			else
				planets[i - 1]->getComponent<Component::GraphNode>()->addSon(planets[i]);
		}
	}

	//
	//
	// END : Generating a lot of planet for performance test

	// --
	// Setting camera with skybox
	// --

	auto camera = _engine.getInstance<EntityManager>().createEntity();
	camera->addComponent<Component::GraphNode>();
	auto cameraComponent = camera->addComponent<Component::CameraComponent>();
	auto trackBall = camera->addComponent<Component::TrackBall>(	*(earth->getComponent<Component::GraphNode>()->getSonsBegin()), 50.0f, 3.0f, 1.0f);

	std::string		vars[] =
	{
		"projection",
		"view"
	};

	OpenGLTools::Shader &sky = _engine.getInstance<Renderer>().addShader("cubemapShader", "Shaders/cubemap.vp", "Shaders/cubemap.fp");

	_engine.getInstance<Renderer>().getShader("cubemapShader")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(1).build();

	_engine.getInstance<Renderer>().addUniform("cameraUniform").
		init(&sky, "cameraUniform", vars);

	_engine.getInstance<Renderer>().bindShaderToUniform("cubemapShader", "cameraUniform", "cameraUniform");

	cameraComponent->attachSkybox("cubemap:space", "cubemapShader");

	// Compute shader Tests
	//
	//

	//OpenGLTools::ComputeShader *cs = new OpenGLTools::ComputeShader();
	//cs->init(File("../GameEngine/Shaders/test.cp"));
	//cs->use();
	//glDispatchCompute(512/16, 512/16, 1);

	//
	//
	// End compute shader test

	return (true);
}

bool 			DemoScene::userUpdate(double time)
{
	if (_engine.getInstance<Input>().getInput(SDLK_ESCAPE) ||
		_engine.getInstance<Input>().getInput(SDL_QUIT))
		return (false);
	return (true);
}
<commit_msg>last benshmark before merge<commit_after>#include <glm/gtc/matrix_transform.hpp>

#include "Core/Engine.hh"
#include "Core/Renderer.hh"
#include "DemoScene.hh"

#include "ResourceManager/SharedMesh.hh"
#include "ResourceManager/Texture.hh"
#include "ResourceManager/CubeMap.hh"
#include "Components/RotationForce.hh"
#include "Components/MaterialComponent.h"
#include <Components/CameraComponent.hh>
#include <Components/TrackBallComponent.hpp>
#include <OpenGL/ComputeShader.hh>
#include <Systems/RotationForceSystem.hpp>
#include <Systems/MeshRenderSystem.h>
#include <Systems/GraphNodeSystem.hpp>
#include <Systems/CameraSystem.hpp>
#include <Systems/TrackBallSystem.hpp>
#include "ResourceManager/ResourceManager.hh"
#include <Core/Engine.hh>
#include <Entities/EntityManager.h>

#include <SDL\SDL.h>

DemoScene::DemoScene(Engine &engine) : AScene(engine)
{
}

DemoScene::~DemoScene(void)
{
}

Handle	DemoScene::createPlanet(float rotSpeed, float orbitSpeed,
												glm::vec3 &pos, glm::vec3 &scale,
												std::string const &shader,
												std::string const &tex1, std::string const &tex2, std::string const &tex3,
												std::string const &tex4)
{
	auto &m = _engine.getInstance<EntityManager>();
	auto p = m.createEntity();
	auto e = m.createEntity();
	p->addComponent<Component::GraphNode>();
	e->addComponent<Component::GraphNode>();

	e->setLocalTransform() = glm::translate(e->getLocalTransform(), pos);
	e->setLocalTransform() = glm::scale(e->getLocalTransform(), scale);

	SmartPointer<Component::MeshRenderer>	r = e->addComponent<Component::MeshRenderer>("model:ball");

	SmartPointer<Material> materialPlanet = _engine.getInstance<Renderer>().getMaterialManager().createMaterial("material:planet_" + shader);

	materialPlanet->pushShader(shader);

	e->addComponent<Component::MaterialComponent>(std::string("material:planet_" + shader));

	//r->addMaterial(materialPlanet);
	r->addTexture(tex1, 0);
	if (!tex2.empty())
		r->addTexture(tex2, 1);
	if (!tex3.empty())
		r->addTexture(tex3, 2);
	if (!tex4.empty())
		r->addTexture(tex4, 3);

	e->addComponent<Component::RotationForce>(glm::vec3(0, orbitSpeed, 0));
	p->getComponent<Component::GraphNode>()->addSon(e);
	p->addComponent<Component::RotationForce>(glm::vec3(0, rotSpeed, 0));
	return (p);
}

bool 			DemoScene::userStart()
{
	// System Tests
	//
	//

	addSystem<RotationForceSystem>(0);
	addSystem<MeshRendererSystem>(0);
	addSystem<GraphNodeSystem>(100);
	addSystem<TrackBallSystem>(150);
	addSystem<CameraSystem>(200);

	//
	//
	// end System Test

	std::string		perModelVars[] =
	{
		"model"
	};

	std::string		perFrameVars[] =
	{
		"projection",
		"view",
		"light",
		"time"
	};

	OpenGLTools::Shader &s = _engine.getInstance<Renderer>().addShader("earth",
		"./Shaders/earth.vp",
		"./Shaders/earth.fp");
		//.bindActiveTexture("fDayTexture", 0)
		//.bindActiveTexture("fNightTexture", 1)
		//.bindActiveTexture("fClouds", 2)
		//.bindActiveTexture("fBump", 3);

	_engine.getInstance<Renderer>().addUniform("PerFrame")
		.init(&s, "PerFrame", perFrameVars);
	_engine.getInstance<Renderer>().addUniform("PerModel")
		.init(&s, "PerModel", perModelVars);

	_engine.getInstance<Renderer>().addShader("basic", "Shaders/basic.vp", "Shaders/basic.fp", "Shaders/tesselation.gp");
	_engine.getInstance<Renderer>().addShader("basicLight", "Shaders/light.vp", "Shaders/light.fp");
	_engine.getInstance<Renderer>().addShader("bump", "Shaders/bump.vp", "Shaders/bump.fp");
		//.bindActiveTexture("fTexture", 0)
		//.bindActiveTexture("fBump", 1);
	_engine.getInstance<Renderer>().addShader("fboToScreen", "Shaders/fboToScreen.vp", "Shaders/fboToScreen.fp");
	_engine.getInstance<Renderer>().addShader("brightnessFilter", "Shaders/brightnessFilter.vp", "Shaders/brightnessFilter.fp");
	_engine.getInstance<Renderer>().addShader("blurY", "Shaders/brightnessFilter.vp", "Shaders/blur1.fp");

	_engine.getInstance<Renderer>().getShader("basic")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(1).build();
	_engine.getInstance<Renderer>().getShader("basicLight")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(1).build();
	_engine.getInstance<Renderer>().getShader("bump")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(2).build();
	_engine.getInstance<Renderer>().getShader("fboToScreen")->addTarget(GL_COLOR_ATTACHMENT0)
		.addLayer(GL_COLOR_ATTACHMENT0).build();
	_engine.getInstance<Renderer>().getShader("earth")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(4).build();
	_engine.getInstance<Renderer>().getShader("brightnessFilter")->addTarget(GL_COLOR_ATTACHMENT1)
		.addLayer(GL_COLOR_ATTACHMENT0).build();
	_engine.getInstance<Renderer>().getShader("blurY")->addTarget(GL_COLOR_ATTACHMENT2)
		.addLayer(GL_COLOR_ATTACHMENT0).addLayer(GL_COLOR_ATTACHMENT1).build();

	_engine.getInstance<Renderer>().getUniform("PerFrame")->setUniform("light", glm::vec4(0, 0, 0, 1));

	_engine.getInstance<Renderer>().bindShaderToUniform("basicLight", "PerFrame", "PerFrame");
	_engine.getInstance<Renderer>().bindShaderToUniform("basicLight", "PerModel", "PerModel");
	_engine.getInstance<Renderer>().bindShaderToUniform("basic", "PerFrame", "PerFrame");
	_engine.getInstance<Renderer>().bindShaderToUniform("basic", "PerModel", "PerModel");
	_engine.getInstance<Renderer>().bindShaderToUniform("earth", "PerFrame", "PerFrame");
	_engine.getInstance<Renderer>().bindShaderToUniform("earth", "PerModel", "PerModel");
	_engine.getInstance<Renderer>().bindShaderToUniform("bump", "PerFrame", "PerFrame");
	_engine.getInstance<Renderer>().bindShaderToUniform("bump", "PerModel", "PerModel");

	_engine.getInstance<Resources::ResourceManager>().addResource("model:ball", new Resources::SharedMesh(), "./Assets/ball.obj");

	SmartPointer<Resources::Texture>		toRepeat = new Resources::Texture();

	toRepeat->setWrapMode(GL_REPEAT);
	_engine.getInstance<Resources::ResourceManager>().addResource("texture:sun", new Resources::Texture(), "./Assets/SunTexture.tga");
	_engine.getInstance<Resources::ResourceManager>().addResource("texture:earth", new Resources::Texture(), "./Assets/EarthTexture.tga");
	_engine.getInstance<Resources::ResourceManager>().addResource("texture:earthBump", new Resources::Texture(), "./Assets/EarthTextureBump.tga");
	_engine.getInstance<Resources::ResourceManager>().addResource("texture:earthNight", new Resources::Texture(), "./Assets/EarthNightTexture.tga");
	_engine.getInstance<Resources::ResourceManager>().addResource("texture:earthClouds", toRepeat, "./Assets/EarthClouds.tga");
	_engine.getInstance<Resources::ResourceManager>().addResource("texture:sun", new Resources::Texture(), "./Assets/SunTexture.tga");
	_engine.getInstance<Resources::ResourceManager>().addResource("texture:moon", new Resources::Texture(), "./Assets/MoonTexture.tga");
	_engine.getInstance<Resources::ResourceManager>().addResource("texture:moonBump", new Resources::Texture(), "./Assets/MoonNormalMap.tga");

	_engine.getInstance<Resources::ResourceManager>().addResource("cubemap:space", new Resources::CubeMap(), "./Assets/skyboxSpace");

	auto sun = createPlanet(0, 0, glm::vec3(0), glm::vec3(100), "basic", "texture:sun");
	auto earth = createPlanet(7, 20, glm::vec3(300, 0, 0), glm::vec3(20), "earth", "texture:earth", "texture:earthNight", "texture:earthClouds", "texture:earthBump");
	auto moon = createPlanet(0, 10, glm::vec3(5, 0, 0), glm::vec3(0.5), "bump", "texture:moon", "texture:moonBump");

	earth->getComponent<Component::GraphNode>()->getSonsBegin()->get()->getComponent<Component::GraphNode>()->addSon(moon);

	// Generating a lot of planet for performance test
	//
	//

	{
		unsigned int nbPlanet = 10000;
		Handle planets[10000];

		for (unsigned int i = 0; i < nbPlanet; ++i)
		{
			planets[i] = createPlanet((std::rand() % 200) / 100.0f
				, (std::rand() % 200) / 100.0f,
				glm::vec3(std::rand() % 300 - 150, std::rand() % 300 - 150, std::rand() % 300 - 150),
				glm::vec3(std::rand() % 10 + 10), "basic", "texture:sun");
			if (i == 0)
				sun->getComponent<Component::GraphNode>()->addSon(planets[i]);
			else
				planets[i - 1]->getComponent<Component::GraphNode>()->addSon(planets[i]);
		}
	}

	//
	//
	// END : Generating a lot of planet for performance test

	// --
	// Setting camera with skybox
	// --

	auto camera = _engine.getInstance<EntityManager>().createEntity();
	camera->addComponent<Component::GraphNode>();
	auto cameraComponent = camera->addComponent<Component::CameraComponent>();
	auto trackBall = camera->addComponent<Component::TrackBall>(	*(earth->getComponent<Component::GraphNode>()->getSonsBegin()), 50.0f, 3.0f, 1.0f);

	std::string		vars[] =
	{
		"projection",
		"view"
	};

	OpenGLTools::Shader &sky = _engine.getInstance<Renderer>().addShader("cubemapShader", "Shaders/cubemap.vp", "Shaders/cubemap.fp");

	_engine.getInstance<Renderer>().getShader("cubemapShader")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(1).build();

	_engine.getInstance<Renderer>().addUniform("cameraUniform").
		init(&sky, "cameraUniform", vars);

	_engine.getInstance<Renderer>().bindShaderToUniform("cubemapShader", "cameraUniform", "cameraUniform");

	cameraComponent->attachSkybox("cubemap:space", "cubemapShader");

	// Compute shader Tests
	//
	//

	//OpenGLTools::ComputeShader *cs = new OpenGLTools::ComputeShader();
	//cs->init(File("../GameEngine/Shaders/test.cp"));
	//cs->use();
	//glDispatchCompute(512/16, 512/16, 1);

	//
	//
	// End compute shader test

	return (true);
}

bool 			DemoScene::userUpdate(double time)
{
	if (_engine.getInstance<Input>().getInput(SDLK_ESCAPE) ||
		_engine.getInstance<Input>().getInput(SDL_QUIT))
		return (false);
	return (true);
}
<|endoftext|>


<commit_before>#include "opencl_utils.h"
namespace ocl {
int global_variable = 66;

const void Init() {}

const std::string DeviceTypeString(cl_device_type type) {
  int ss = type;
  std::string s = "";
  if (type & CL_DEVICE_TYPE_CPU) {
    s += "CL_DEVICE_TYPE_CPU ";
  }
  if (type & CL_DEVICE_TYPE_GPU) {
    s += "CL_DEVICE_TYPE_GPU ";
  }
  if (type & CL_DEVICE_TYPE_ACCELERATOR) {
    s += "CL_DEVICE_TYPE_ACCELERATOR ";
  }
  if (type & CL_DEVICE_TYPE_DEFAULT) {
    s += "CL_DEVICE_TYPE_DEFAULT ";
  }
  return s;
}
}

std::string readable_fs(unsigned int sz /*in bytes*/) {
  float size = (float)sz;
  unsigned int kb = 1024;
  unsigned int mb = kb * 1024;
  unsigned int gb = mb * 1024;
  std::string s = "";
  float minus = 0;
  if (size > gb) {
    float a = floor(size / gb);
    minus += a * gb;
    s += std::to_string((int)a);
    s += "GB, ";
  }
  if (size > mb) {
    float a = floor((size - minus) / mb);
    minus += a * mb;
    s += std::to_string((int)a);
    s += "MB, ";
  }
  if (size > kb) {
    float a = floor((size - minus) / kb);
    minus += a * kb;
    s += std::to_string((int)a);
    s += "KB, ";
  }
  s += std::to_string((int)(size - minus));
  s += "B (";
  s += std::to_string(sz);
  s += ")";
  return s;
}<commit_msg>Linux needs maths<commit_after>#include "opencl_utils.h"
#include <math.h>

namespace ocl {
int global_variable = 66;

const void Init() {}

const std::string DeviceTypeString(cl_device_type type) {
  int ss = type;
  std::string s = "";
  if (type & CL_DEVICE_TYPE_CPU) {
    s += "CL_DEVICE_TYPE_CPU ";
  }
  if (type & CL_DEVICE_TYPE_GPU) {
    s += "CL_DEVICE_TYPE_GPU ";
  }
  if (type & CL_DEVICE_TYPE_ACCELERATOR) {
    s += "CL_DEVICE_TYPE_ACCELERATOR ";
  }
  if (type & CL_DEVICE_TYPE_DEFAULT) {
    s += "CL_DEVICE_TYPE_DEFAULT ";
  }
  return s;
}
}

std::string readable_fs(unsigned int sz /*in bytes*/) {
  float size = (float)sz;
  unsigned int kb = 1024;
  unsigned int mb = kb * 1024;
  unsigned int gb = mb * 1024;
  std::string s = "";
  float minus = 0;
  if (size > gb) {
    float a = floor(size / gb);
    minus += a * gb;
    s += std::to_string((int)a);
    s += "GB, ";
  }
  if (size > mb) {
    float a = floor((size - minus) / mb);
    minus += a * mb;
    s += std::to_string((int)a);
    s += "MB, ";
  }
  if (size > kb) {
    float a = floor((size - minus) / kb);
    minus += a * kb;
    s += std::to_string((int)a);
    s += "KB, ";
  }
  s += std::to_string((int)(size - minus));
  s += "B (";
  s += std::to_string(sz);
  s += ")";
  return s;
}<|endoftext|>


<commit_before>/*
    Crystal Space 3ds2lev xml writer
    Copyright (C) 2001,2002 by Luca Pancallo and Matze Braun

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"

#include <stdlib.h>
#include <ctype.h>
#include <math.h>

// includes for lib3ds
#include <lib3ds/camera.h>
#include <lib3ds/file.h>
#include <lib3ds/io.h>
#include <lib3ds/light.h>
#include <lib3ds/material.h>
#include <lib3ds/matrix.h>
#include <lib3ds/mesh.h>
#include <lib3ds/node.h>
#include <lib3ds/vector.h>

#include <csutil/scfstr.h>

#include "levelwriter.h"

CS_IMPLEMENT_APPLICATION

enum
{
  FLAG_VERBOSE	= 0x0001,
  FLAG_LIST     = 0x0002,    /* List all objects in this 3ds     */
};

enum xyzmode
{
  MODE_XYZ = 0,
  MODE_XZY = 1,
  MODE_YXZ = 2,
  MODE_YZX = 3,
  MODE_ZXY = 4,
  MODE_ZYX = 5
};

/**
 * Simply switch x,y,z coord depending on the selected MODE_XYZ
 */
void ConvertXYZ (xyzmode mode_xyz, float& x, float& y, float& z)
{
  float sw;
  switch (mode_xyz)
  {
    case MODE_XYZ: return;
    case MODE_XZY: sw = y; y = z; z = sw; return;
    case MODE_YXZ: sw = x; x = y; y = sw; return;
    case MODE_YZX: sw = x; x = y; y = z; z = sw; return;
    case MODE_ZXY: sw = x; x = z; z = y; y = sw; return;
    case MODE_ZYX: sw = x; x = z; z = sw; return;
  }
}

/**
 * Swap x,y,z coord depending on the selected MODE_XYZ
 * All vertexes and triangles are affected.
 * All lights are affected.
 */
void Lib3dsConvertXYZ (Lib3dsFile* p3dsFile, xyzmode mode)
{

  // TODO: should be done for -center option. actually not supported.
  //ConvertXYZ (scene->centre.x, scene->centre.y, scene->centre.z);

  // a vertex
  Lib3dsPoint *pCurPoint;

  // used for coords of vertex
  float *xyz;

  // set the current mesh to the first in the file
  Lib3dsMesh *p3dsMesh = p3dsFile->meshes;

  // as long as we have a valid mesh...
  while( p3dsMesh )
  {
    // get the number of vertices in the current mesh
    int numVertices = p3dsMesh->points;
    int i;
    // vertexes pointer
    pCurPoint = p3dsMesh->pointL;
    for ( i = 0 ; i < numVertices ; i++ )
    {
        // index to the position on the list using index
        xyz = pCurPoint->pos;

        // Convert the vertex coords
        ConvertXYZ (mode, xyz[0], xyz[1], xyz[2]);

        // go to next vertex
        pCurPoint++;
    }

    // we must convert also triangles or the texture will be flipped
    // get the triangle count and go to the first triangle
    int numTriangles = p3dsMesh->faces;
    Lib3dsFace *pCurFace = p3dsMesh->faceL;

    // convert each triangle
    for ( i = 0 ; i < numTriangles ; i++ ) {
      float v1 = pCurFace->points[0];
      float v2 = pCurFace->points[1];
      float v3 = pCurFace->points[2];
      ConvertXYZ (mode, v1, v2, v3);
      pCurFace->points[0] = (short unsigned int)v1;
      pCurFace->points[1] = (short unsigned int)v2;
      pCurFace->points[2] = (short unsigned int)v3;

      // go to next triangle
      pCurFace++;
    }

    // go to next mesh
    p3dsMesh = p3dsMesh->next;
  }

  // swap coords of lights
  Lib3dsLight* light;
  for (light = p3dsFile->lights; light; light = light->next)
  {
    ConvertXYZ (mode, light->position[0],
	              light->position[1],
		      light->position[2]);
  }

  // swap coords of cameras
  Lib3dsCamera *camera;
  for (camera = p3dsFile->cameras; camera; camera = camera->next)
  {
    ConvertXYZ (mode, camera->position[0],
		      camera->position[1],
		      camera->position[2]);
    ConvertXYZ (mode, camera->target[0],
		      camera->target[1],
		      camera->target[2]);
  }
}

/**
 * Main function
 */
int main (int argc, char * argv[])
{
  char * infn=0, * outfn=0;
  float xscale = 1, yscale = 1, zscale = 1;
  float xrelocate = 0, yrelocate = 0, zrelocate = 0;
  xyzmode mode_xyz = MODE_XZY;
  int flags = 0;
  LevelWriter writer;

  flags = 0;

  // default to lower left texture origin
  writer.SetFlags (LevelWriter::FLAG_SWAP_V);

  argc--;
  argv++;

  if(!argc)
  {
    fprintf (stderr,
         "3D Studio native objectfile converter v2.0\n"
         "originally by Mats Byggmastar 1996 Espoo, Finland.\n"
	 "This version is for Crystal Space and heavily modified by\n"
	 "Jorrit Tyberghein, Luca Pancallo and Matze Braun.\n"
         "Use:  %s [params...] inputfile.3ds\n"
               "params:\n"
	       " -o file   Name of the output file\n"
               " -v        Verbose mode on\n"
               " -l        Don't convert but list objects in 3ds file\n"
	       " -c	   optimize (combine every two triangles into polys)\n"
               " -r x y z  Relocate objects (x,y,z = floats)\n"
               " -pl       Make polygons lit\n"
               " -3        Output 3D sprite instead of level\n"
	       " -tl       Make texture origin lower left (default)\n"
	       " -b	   Use clearzbuf and clearscreen settings\n"
	       " -xyz      Convert model xyz -> CS xyz\n"
	       " -xzy      Convert model xyz -> CS xzy (default)\n"
	       " -yxz      Convert model xyz -> CS yxz\n"
	       " -yzx      Convert model xyz -> CS yzx\n"
	       " -zxy      Convert model xyz -> CS zxy\n"
	       " -zyx      Convert model xyz -> CS zyx\n",
               argv[-1]);

    return 1;
  }

  // Get the parameters and filenames
  for (int n=0; n<argc; n++)
  {
    if (argv[n][0] == '-' || argv[n][0] == '/')
    {
      switch (toupper(argv[n][1]))
      {
	case 'O':
	  if (n+1<argc)
	    outfn=argv[++n];
	  else
	  {
	    fprintf (stderr, "Missing outputfile name!\n");
	    return 1;
	  }
	  break;
        case 'R':
	  if (n+3<argc)
	  {
	    xrelocate = atof(argv[++n]);
	    yrelocate = atof(argv[++n]);
	    zrelocate = atof(argv[++n]);
	  }
	  else
	  {
	    fprintf(stderr, "Missing relocate value!\n");
	    return 1;
	  }
	  break;
        case 'S':
	  if (n+3<argc)
	  {
	    xscale = atof(argv[++n]);
	    yscale = atof(argv[++n]);
	    zscale = atof(argv[++n]);
	  }
   	  else
	  {
	    fprintf(stderr, "Missing scale value!\n");
	    return 1;
	  }
	  break;
        case 'P':
	  if (toupper (argv[n][2]) == 'L')
	  {
	    writer.SetFlags (LevelWriter::FLAG_LIGHTING);
	  }
	  break;
	case 'V':
	  writer.SetFlags(LevelWriter::FLAG_VERBOSE);
	  flags |= FLAG_VERBOSE;
	  break;
        case 'T':
	  if (toupper (argv[n][2]) == 'L')
	    writer.SetFlags (LevelWriter::FLAG_SWAP_V);
	  break;
	case '3':
	  writer.SetFlags (LevelWriter::FLAG_SPRITE);
	  break;
	case 'L':
	  flags |= FLAG_LIST;
	  break;
	case 'B':
	  writer.SetFlags (LevelWriter::FLAG_CLEARZBUFCLEARSCREEN);
	  break;
	case 'X':
	  if (toupper (argv[n][2]) == 'Y')
	    mode_xyz = MODE_XYZ;
	  else
	    mode_xyz = MODE_XZY;
	  break;
	case 'Y':
	  if (toupper (argv[n][2]) == 'X')
	    mode_xyz = MODE_YXZ;
	  else
	    mode_xyz = MODE_YZX;
	  break;
	case 'Z':
	  if (toupper (argv[n][2]) == 'X')
	    mode_xyz = MODE_ZXY;
	  else
	    mode_xyz = MODE_ZYX;
	  break;
	case 'C':
	  writer.SetFlags(LevelWriter::FLAG_COMBINEFACES);
	  writer.SetFlags(LevelWriter::FLAG_REMOVEDOUBLEVERTICES);
	  break;
	default:
	  fprintf (stderr, "Bad parameter: %s\n",argv[n]);
	  return 1;
      }
    }
    else
    {
      if (!infn)
        infn = argv[n];
      else
      {
	fprintf (stderr, "Too many filenames (can only convert 1 file at once!\n");
        return 1;
      }
    }
  }

  if (!infn)
  {
    fprintf (stderr, "No inputfile specified!\n");
    return 1;
  }

  // <--------- finished parsing parameters ----------->

  // Read inputfile
  Lib3dsFile* file3ds = lib3ds_file_load(infn);
  if (!file3ds ) {
    fprintf (stderr, "Failed to open %s\n", infn);
    return 1;
  }

  // swap xyz if requested
  if (mode_xyz != MODE_XYZ)
    Lib3dsConvertXYZ (file3ds, mode_xyz);

  // Print some interesting information about what we have
  if (flags & FLAG_LIST || flags & FLAG_VERBOSE)
  {
    // fprintf (stderr, "3DS data size: %ld byte\n", size);
    fprintf (stderr, "3DS name: %s\n", file3ds->name);
    fprintf (stderr, "lights: %s\n", file3ds->lights ? "yes" : "no");
    fprintf (stderr, "object-name     faces vertices  maps  matrix\n");

    // set the current mesh to the first in the file
    Lib3dsMesh* mesh;
    for (mesh = file3ds->meshes; mesh; mesh = mesh->next)
    {
        // get the numbers in the current mesh
        fprintf(stderr, "===================================================\n");
        fprintf(stderr, "%-14s  %5ld  %5ld  %5d    %s\n",
              mesh->name, mesh->faces, mesh->points, -1, " ");
    }
  }

  // setup writer
  writer.Set3dsFile (file3ds);
  writer.SetScale (xscale, yscale, zscale);
  writer.SetTranslate (xrelocate, yrelocate, zrelocate);

  if (flags & FLAG_VERBOSE)
    fprintf (stderr, "Writing output in CS format...");

  csRef<iDocument> document = writer.WriteDocument ();
  iString* str = new scfString;
  document->Write (str);

  if (outfn)
  {
    // Write file to disk
    FILE* outfile = fopen (outfn, "w");
    if (!outfile)
    {
      fprintf (stderr, "Couldn't open output file '%s'!\n", outfn);
      return 1;
    }
    fwrite (str->GetData(), 1, str->Length(), outfile);
    fclose (outfile);
  }
  else
  {
    // Write file to stdout
    printf ("%s", str->GetData());
  }

  if (flags & FLAG_VERBOSE)
    fprintf (stderr, "done! \n");

  return 0;
}

<commit_msg>missed a line<commit_after>/*
    Crystal Space 3ds2lev xml writer
    Copyright (C) 2001,2002 by Luca Pancallo and Matze Braun

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"

#include <stdlib.h>
#include <ctype.h>
#include <math.h>

// includes for lib3ds
#include <lib3ds/camera.h>
#include <lib3ds/file.h>
#include <lib3ds/io.h>
#include <lib3ds/light.h>
#include <lib3ds/material.h>
#include <lib3ds/matrix.h>
#include <lib3ds/mesh.h>
#include <lib3ds/node.h>
#include <lib3ds/vector.h>

#include <csutil/scfstr.h>

#include "levelwriter.h"

CS_IMPLEMENT_APPLICATION

enum
{
  FLAG_VERBOSE	= 0x0001,
  FLAG_LIST     = 0x0002,    /* List all objects in this 3ds     */
};

enum xyzmode
{
  MODE_XYZ = 0,
  MODE_XZY = 1,
  MODE_YXZ = 2,
  MODE_YZX = 3,
  MODE_ZXY = 4,
  MODE_ZYX = 5
};

/**
 * Simply switch x,y,z coord depending on the selected MODE_XYZ
 */
void ConvertXYZ (xyzmode mode_xyz, float& x, float& y, float& z)
{
  float sw;
  switch (mode_xyz)
  {
    case MODE_XYZ: return;
    case MODE_XZY: sw = y; y = z; z = sw; return;
    case MODE_YXZ: sw = x; x = y; y = sw; return;
    case MODE_YZX: sw = x; x = y; y = z; z = sw; return;
    case MODE_ZXY: sw = x; x = z; z = y; y = sw; return;
    case MODE_ZYX: sw = x; x = z; z = sw; return;
  }
}

/**
 * Swap x,y,z coord depending on the selected MODE_XYZ
 * All vertexes and triangles are affected.
 * All lights are affected.
 */
void Lib3dsConvertXYZ (Lib3dsFile* p3dsFile, xyzmode mode)
{

  // TODO: should be done for -center option. actually not supported.
  //ConvertXYZ (scene->centre.x, scene->centre.y, scene->centre.z);

  // a vertex
  Lib3dsPoint *pCurPoint;

  // used for coords of vertex
  float *xyz;

  // set the current mesh to the first in the file
  Lib3dsMesh *p3dsMesh = p3dsFile->meshes;

  // as long as we have a valid mesh...
  while( p3dsMesh )
  {
    // get the number of vertices in the current mesh
    int numVertices = p3dsMesh->points;
    int i;
    // vertexes pointer
    pCurPoint = p3dsMesh->pointL;
    for ( i = 0 ; i < numVertices ; i++ )
    {
        // index to the position on the list using index
        xyz = pCurPoint->pos;

        // Convert the vertex coords
        ConvertXYZ (mode, xyz[0], xyz[1], xyz[2]);

        // go to next vertex
        pCurPoint++;
    }

    // we must convert also triangles or the texture will be flipped
    // get the triangle count and go to the first triangle
    int numTriangles = p3dsMesh->faces;
    Lib3dsFace *pCurFace = p3dsMesh->faceL;

    // convert each triangle
    for ( i = 0 ; i < numTriangles ; i++ ) {
      float v1 = pCurFace->points[0];
      float v2 = pCurFace->points[1];
      float v3 = pCurFace->points[2];
      ConvertXYZ (mode, v1, v2, v3);
      pCurFace->points[0] = (short unsigned int)v1;
      pCurFace->points[1] = (short unsigned int)v2;
      pCurFace->points[2] = (short unsigned int)v3;

      // go to next triangle
      pCurFace++;
    }

    // go to next mesh
    p3dsMesh = p3dsMesh->next;
  }

  // swap coords of lights
  Lib3dsLight* light;
  for (light = p3dsFile->lights; light; light = light->next)
  {
    ConvertXYZ (mode, light->position[0],
	              light->position[1],
		      light->position[2]);
  }

  // swap coords of cameras
  Lib3dsCamera *camera;
  for (camera = p3dsFile->cameras; camera; camera = camera->next)
  {
    ConvertXYZ (mode, camera->position[0],
		      camera->position[1],
		      camera->position[2]);
    ConvertXYZ (mode, camera->target[0],
		      camera->target[1],
		      camera->target[2]);
  }
}

/**
 * Main function
 */
int main (int argc, char * argv[])
{
  char * infn=0, * outfn=0;
  float xscale = 1, yscale = 1, zscale = 1;
  float xrelocate = 0, yrelocate = 0, zrelocate = 0;
  xyzmode mode_xyz = MODE_XZY;
  int flags = 0;
  LevelWriter writer;

  flags = 0;

  // default to lower left texture origin
  writer.SetFlags (LevelWriter::FLAG_SWAP_V);

  argc--;
  argv++;

  if(!argc)
  {
    fprintf (stderr,
         "3D Studio native objectfile converter v2.0\n"
         "originally by Mats Byggmastar 1996 Espoo, Finland.\n"
	 "This version is for Crystal Space and heavily modified by\n"
	 "Jorrit Tyberghein, Luca Pancallo and Matze Braun.\n"
         "Use:  %s [params...] inputfile.3ds\n"
               "params:\n"
	       " -o file   Name of the output file\n"
               " -v        Verbose mode on\n"
               " -l        Don't convert but list objects in 3ds file\n"
	       " -c	   optimize (combine every two triangles into polys)\n"
               " -r x y z  Relocate objects (x,y,z = floats)\n"
	       " -s x y t  Scale objects (x,y,z = floats)\n"
               " -pl       Make polygons lit\n"
               " -3        Output 3D sprite instead of level\n"
	       " -tl       Make texture origin lower left (default)\n"
	       " -b	   Use clearzbuf and clearscreen settings\n"
	       " -xyz      Convert model xyz -> CS xyz\n"
	       " -xzy      Convert model xyz -> CS xzy (default)\n"
	       " -yxz      Convert model xyz -> CS yxz\n"
	       " -yzx      Convert model xyz -> CS yzx\n"
	       " -zxy      Convert model xyz -> CS zxy\n"
	       " -zyx      Convert model xyz -> CS zyx\n",
               argv[-1]);

    return 1;
  }

  // Get the parameters and filenames
  for (int n=0; n<argc; n++)
  {
    if (argv[n][0] == '-' || argv[n][0] == '/')
    {
      switch (toupper(argv[n][1]))
      {
	case 'O':
	  if (n+1<argc)
	    outfn=argv[++n];
	  else
	  {
	    fprintf (stderr, "Missing outputfile name!\n");
	    return 1;
	  }
	  break;
        case 'R':
	  if (n+3<argc)
	  {
	    xrelocate = atof(argv[++n]);
	    yrelocate = atof(argv[++n]);
	    zrelocate = atof(argv[++n]);
	  }
	  else
	  {
	    fprintf(stderr, "Missing relocate value!\n");
	    return 1;
	  }
	  break;
        case 'S':
	  if (n+3<argc)
	  {
	    xscale = atof(argv[++n]);
	    yscale = atof(argv[++n]);
	    zscale = atof(argv[++n]);
	  }
   	  else
	  {
	    fprintf(stderr, "Missing scale value!\n");
	    return 1;
	  }
	  break;
        case 'P':
	  if (toupper (argv[n][2]) == 'L')
	  {
	    writer.SetFlags (LevelWriter::FLAG_LIGHTING);
	  }
	  break;
	case 'V':
	  writer.SetFlags(LevelWriter::FLAG_VERBOSE);
	  flags |= FLAG_VERBOSE;
	  break;
        case 'T':
	  if (toupper (argv[n][2]) == 'L')
	    writer.SetFlags (LevelWriter::FLAG_SWAP_V);
	  break;
	case '3':
	  writer.SetFlags (LevelWriter::FLAG_SPRITE);
	  break;
	case 'L':
	  flags |= FLAG_LIST;
	  break;
	case 'B':
	  writer.SetFlags (LevelWriter::FLAG_CLEARZBUFCLEARSCREEN);
	  break;
	case 'X':
	  if (toupper (argv[n][2]) == 'Y')
	    mode_xyz = MODE_XYZ;
	  else
	    mode_xyz = MODE_XZY;
	  break;
	case 'Y':
	  if (toupper (argv[n][2]) == 'X')
	    mode_xyz = MODE_YXZ;
	  else
	    mode_xyz = MODE_YZX;
	  break;
	case 'Z':
	  if (toupper (argv[n][2]) == 'X')
	    mode_xyz = MODE_ZXY;
	  else
	    mode_xyz = MODE_ZYX;
	  break;
	case 'C':
	  writer.SetFlags(LevelWriter::FLAG_COMBINEFACES);
	  writer.SetFlags(LevelWriter::FLAG_REMOVEDOUBLEVERTICES);
	  break;
	default:
	  fprintf (stderr, "Bad parameter: %s\n",argv[n]);
	  return 1;
      }
    }
    else
    {
      if (!infn)
        infn = argv[n];
      else
      {
	fprintf (stderr, "Too many filenames (can only convert 1 file at once!\n");
        return 1;
      }
    }
  }

  if (!infn)
  {
    fprintf (stderr, "No inputfile specified!\n");
    return 1;
  }

  // <--------- finished parsing parameters ----------->

  // Read inputfile
  Lib3dsFile* file3ds = lib3ds_file_load(infn);
  if (!file3ds ) {
    fprintf (stderr, "Failed to open %s\n", infn);
    return 1;
  }

  // swap xyz if requested
  if (mode_xyz != MODE_XYZ)
    Lib3dsConvertXYZ (file3ds, mode_xyz);

  // Print some interesting information about what we have
  if (flags & FLAG_LIST || flags & FLAG_VERBOSE)
  {
    // fprintf (stderr, "3DS data size: %ld byte\n", size);
    fprintf (stderr, "3DS name: %s\n", file3ds->name);
    fprintf (stderr, "lights: %s\n", file3ds->lights ? "yes" : "no");
    fprintf (stderr, "object-name     faces vertices  maps  matrix\n");

    // set the current mesh to the first in the file
    Lib3dsMesh* mesh;
    for (mesh = file3ds->meshes; mesh; mesh = mesh->next)
    {
        // get the numbers in the current mesh
        fprintf(stderr, "===================================================\n");
        fprintf(stderr, "%-14s  %5ld  %5ld  %5d    %s\n",
              mesh->name, mesh->faces, mesh->points, -1, " ");
    }
  }

  // setup writer
  writer.Set3dsFile (file3ds);
  writer.SetScale (xscale, yscale, zscale);
  writer.SetTranslate (xrelocate, yrelocate, zrelocate);

  if (flags & FLAG_VERBOSE)
    fprintf (stderr, "Writing output in CS format...");

  csRef<iDocument> document = writer.WriteDocument ();
  iString* str = new scfString;
  document->Write (str);

  if (outfn)
  {
    // Write file to disk
    FILE* outfile = fopen (outfn, "w");
    if (!outfile)
    {
      fprintf (stderr, "Couldn't open output file '%s'!\n", outfn);
      return 1;
    }
    fwrite (str->GetData(), 1, str->Length(), outfile);
    fclose (outfile);
  }
  else
  {
    // Write file to stdout
    printf ("%s", str->GetData());
  }

  if (flags & FLAG_VERBOSE)
    fprintf (stderr, "done! \n");

  return 0;
}

<|endoftext|>


<commit_before>//===- Version.cpp - Clang Version Number -----------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines several version-related utility functions for Clang.
//
//===----------------------------------------------------------------------===//

#include "clang/Basic/Version.h"
#include "llvm/Support/raw_ostream.h"
#include <cstring>
#include <cstdlib>

using namespace std;

namespace clang {

llvm::StringRef getClangRepositoryPath() {
  static const char URL[] = "$URL$";
  const char *URLEnd = URL + strlen(URL);

  const char *End = strstr(URL, "/lib/Basic");
  if (End)
    URLEnd = End;

  End = strstr(URL, "/clang/tools/clang");
  if (End)
    URLEnd = End;

  const char *Begin = strstr(URL, "cfe/");
  if (Begin)
    return llvm::StringRef(Begin + 4, URLEnd - Begin - 4);

  return llvm::StringRef(URL, URLEnd - URL);
}

std::string getClangRevision() {
#ifndef SVN_REVISION
  // Subversion was not available at build time?
  return "";
#else
  std::string revision;
  llvm::raw_string_ostream OS(revision);
  OS << strtol(SVN_REVISION, 0, 10);
  return revision;
#endif
}

std::string getClangFullRepositoryVersion() {
  std::string buf;
  llvm::raw_string_ostream OS(buf);
  OS << getClangRepositoryPath();
  const std::string &Revision = getClangRevision();
  if (!Revision.empty())
    OS << ' ' << Revision;
  return buf;
}

std::string getClangFullVersion() {
  std::string buf;
  llvm::raw_string_ostream OS(buf);
#ifdef CLANG_VENDOR
  OS << CLANG_VENDOR;
#endif
  OS << "clang version " CLANG_VERSION_STRING " ("
     << getClangFullRepositoryVersion() << ')';
  return buf;
}

} // end namespace clang
<commit_msg>Make getClangRevision() check that SVN_VERSION is an empty string  (even if it is defined).  This fixes the issue of this function returning '0' when SVN_VERSION is defined to be "".<commit_after>//===- Version.cpp - Clang Version Number -----------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines several version-related utility functions for Clang.
//
//===----------------------------------------------------------------------===//

#include "clang/Basic/Version.h"
#include "llvm/Support/raw_ostream.h"
#include <cstring>
#include <cstdlib>

using namespace std;

namespace clang {

llvm::StringRef getClangRepositoryPath() {
  static const char URL[] = "$URL$";
  const char *URLEnd = URL + strlen(URL);

  const char *End = strstr(URL, "/lib/Basic");
  if (End)
    URLEnd = End;

  End = strstr(URL, "/clang/tools/clang");
  if (End)
    URLEnd = End;

  const char *Begin = strstr(URL, "cfe/");
  if (Begin)
    return llvm::StringRef(Begin + 4, URLEnd - Begin - 4);

  return llvm::StringRef(URL, URLEnd - URL);
}

std::string getClangRevision() {
#ifdef SVN_REVISION
  if (SVN_VERSION[0] != '\0') {
    std::string revision;
    llvm::raw_string_ostream OS(revision);
    OS << strtol(SVN_REVISION, 0, 10);
    return revision;
  }
#endif
  return "";
}

std::string getClangFullRepositoryVersion() {
  std::string buf;
  llvm::raw_string_ostream OS(buf);
  OS << getClangRepositoryPath();
  const std::string &Revision = getClangRevision();
  if (!Revision.empty())
    OS << ' ' << Revision;
  return buf;
}

std::string getClangFullVersion() {
  std::string buf;
  llvm::raw_string_ostream OS(buf);
#ifdef CLANG_VENDOR
  OS << CLANG_VENDOR;
#endif
  OS << "clang version " CLANG_VERSION_STRING " ("
     << getClangFullRepositoryVersion() << ')';
  return buf;
}

} // end namespace clang
<|endoftext|>


<commit_before>/* FLAC input plugin for Winamp3
 * Copyright (C) 2000,2001,2002  Josh Coalson
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * NOTE: this code is derived from the 'rawpcm' example by
 * Nullsoft; the original license for the 'rawpcm' example follows.
 */
/*

  Nullsoft WASABI Source File License

  Copyright 1999-2001 Nullsoft, Inc.

    This software is provided 'as-is', without any express or implied
    warranty.  In no event will the authors be held liable for any damages
    arising from the use of this software.

    Permission is granted to anyone to use this software for any purpose,
    including commercial applications, and to alter it and redistribute it
    freely, subject to the following restrictions:

    1. The origin of this software must not be misrepresented; you must not
       claim that you wrote the original software. If you use this software
       in a product, an acknowledgment in the product documentation would be
       appreciated but is not required.
    2. Altered source versions must be plainly marked as such, and must not be
       misrepresented as being the original software.
    3. This notice may not be removed or altered from any source distribution.

  Brennan Underwood
  brennan@nullsoft.com

*/

#include "cnv_flacpcm.h"
#include "flacpcm.h"

static WACNAME wac;
WAComponentClient *the = &wac;

#include "studio/services/servicei.h"

// {683FA153-4055-467c-ABEE-5E35FA03C51E}
static const GUID guid =
{ 0x683fa153, 0x4055, 0x467c, { 0xab, 0xee, 0x5e, 0x35, 0xfa, 0x3, 0xc5, 0x1e } };

_int nch("# of channels", 2);
_int samplerate("Sample rate", 44100);
_int bps("Bits per second", 16);

WACNAME::WACNAME() : WAComponentClient("RAW files support") {
	registerService(new waServiceT<svc_mediaConverter, FlacPcm>);
}

WACNAME::~WACNAME() {
}

GUID WACNAME::getGUID() {
	return guid;
}

void WACNAME::onRegisterServices() {
	api->core_registerExtension("*.flac","FLAC Files");

	registerAttribute(&nch);
	registerAttribute(&samplerate);
	registerAttribute(&bps);
}
<commit_msg>fix WACNAME<commit_after>/* FLAC input plugin for Winamp3
 * Copyright (C) 2000,2001,2002  Josh Coalson
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * NOTE: this code is derived from the 'rawpcm' example by
 * Nullsoft; the original license for the 'rawpcm' example follows.
 */
/*

  Nullsoft WASABI Source File License

  Copyright 1999-2001 Nullsoft, Inc.

    This software is provided 'as-is', without any express or implied
    warranty.  In no event will the authors be held liable for any damages
    arising from the use of this software.

    Permission is granted to anyone to use this software for any purpose,
    including commercial applications, and to alter it and redistribute it
    freely, subject to the following restrictions:

    1. The origin of this software must not be misrepresented; you must not
       claim that you wrote the original software. If you use this software
       in a product, an acknowledgment in the product documentation would be
       appreciated but is not required.
    2. Altered source versions must be plainly marked as such, and must not be
       misrepresented as being the original software.
    3. This notice may not be removed or altered from any source distribution.

  Brennan Underwood
  brennan@nullsoft.com

*/

#include "cnv_flacpcm.h"
#include "flacpcm.h"

static WACNAME wac;
WAComponentClient *the = &wac;

#include "studio/services/servicei.h"

// {683FA153-4055-467c-ABEE-5E35FA03C51E}
static const GUID guid =
{ 0x683fa153, 0x4055, 0x467c, { 0xab, 0xee, 0x5e, 0x35, 0xfa, 0x3, 0xc5, 0x1e } };

_int nch("# of channels", 2);
_int samplerate("Sample rate", 44100);
_int bps("Bits per second", 16);

WACNAME::WACNAME() : WAComponentClient("FLAC file support") {
	registerService(new waServiceT<svc_mediaConverter, FlacPcm>);
}

WACNAME::~WACNAME() {
}

GUID WACNAME::getGUID() {
	return guid;
}

void WACNAME::onRegisterServices() {
	api->core_registerExtension("*.flac","FLAC Files");

	registerAttribute(&nch);
	registerAttribute(&samplerate);
	registerAttribute(&bps);
}
<|endoftext|>


<commit_before>/*
  Crystal Space Quake Milk Shape ASCII convertor
  Copyright (C) 2002 by Steven Geens <steven.geens@student.kuleuven.ac.be>
  Based upon:
  Crystal Space Quake MDL/MD2 convertor

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Library General Public
  License as published by the Free Software Foundation; either
  version 2 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Library General Public License for more details.

  You should have received a copy of the GNU Library General Public
  License along with this library; if not, write to the Free
  Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "cssysdef.h"
#include "msmodel.h"

CS_IMPLEMENT_APPLICATION

static void usage(FILE* s, int rc)
{
  fprintf(s, "Usage: milk2spr <option> [model-file] [sprite-name]\n[sprite-name] without the trailing .lib\n");
  fprintf(s, "Options:\n");
  fprintf(s, "  -h : help (this page)\n");
  fprintf(s, "  -d <float> : duration of a frame in seconds (default %f)\n",FRAME_DURATION_DEFAULT);
  printCode(s,rc);
  exit(rc);
}

static void fatal_usage() { usage(stderr, -1); }
static void okay_usage()  { usage(stdout,  0); }

static void printCode(FILE* s, int rc)
{
  fprintf(s, "The code example is replaced by a program.\n");
  fprintf(s, "Look in /apps/tests/mottest\n");
  exit(rc);
}

int main(int argc,char *argv[])
{
  printf("milk2spr version 0.9\n"
    "A Milk Shape ASCII model convertor for Crystal Space.\n"
    "By Steven Geens <steven.geens@student.kuleuven.ac.be>\n\n");

  float frameDuration = FRAME_DURATION_DEFAULT;

  if (argc < 2)
  {
    fatal_usage();
  }
  if (argc < 3)
  {
    switch (argv[1][1])
    {
      case 'c':
        printCode(stdout,  0);
      default:
       fatal_usage();
    }
  }
  else
  {
    int i;
    for (i = 1; i < argc - 2; i++)
    {
      if (argv[i][0] != '-' && argv[i][0] != '/')
      {
        fprintf(stderr, "'%s' unreconized option\n", argv[i]);
        fatal_usage();
      }
      switch (argv[i][1])
      {
      case 'h':
      case '?':
        okay_usage();break;
      case 'c':
        printCode(stdout,  0);break;
      case 'd':
        sscanf (argv[++i], "%f", &frameDuration);
        printf("The duration of a frame set to %g seconds.\n", frameDuration);
        break;
      default:
        fprintf(stderr, "'%s' unreconized option.\n", argv[i]);
        fatal_usage();
      }
    }
  }

  const char* msfile = argv[argc - 2];
  MsModel* ms = NULL;
  if (MsModel::IsFileMsModel(msfile))
    ms = new MsModel(msfile,frameDuration);
  else
  {
    fprintf(stderr, "Not a recognized model file: %s\n", msfile);
    exit(-1);
  }

  if (ms->getError())
  {
    fprintf(stderr, "\nError: %s\n", ms->getErrorString());
    delete ms;
    exit(-1);
  }

  ms->dumpstats(stdout);
  putchar('\n');
  ms->WriteSPR(argv[argc - 1]);

  delete ms;
  return 0;
}

<commit_msg>Allways test first before you commit.<commit_after>/*
  Crystal Space Quake Milk Shape ASCII convertor
  Copyright (C) 2002 by Steven Geens <steven.geens@student.kuleuven.ac.be>
  Based upon:
  Crystal Space Quake MDL/MD2 convertor

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Library General Public
  License as published by the Free Software Foundation; either
  version 2 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Library General Public License for more details.

  You should have received a copy of the GNU Library General Public
  License along with this library; if not, write to the Free
  Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "cssysdef.h"
#include "msmodel.h"

CS_IMPLEMENT_APPLICATION

static void printCode(FILE* s, int rc)
{
  fprintf(s, "The code example is replaced by a program.\n");
  fprintf(s, "Look in /apps/tests/mottest\n");
  exit(rc);
}

static void usage(FILE* s, int rc)
{
  fprintf(s, "Usage: milk2spr <option> [model-file] [sprite-name]\n[sprite-name] without the trailing .lib\n");
  fprintf(s, "Options:\n");
  fprintf(s, "  -h : help (this page)\n");
  fprintf(s, "  -d <float> : duration of a frame in seconds (default %f)\n",FRAME_DURATION_DEFAULT);
  printCode(s,rc);
}

static void fatal_usage() { usage(stderr, -1); }
static void okay_usage()  { usage(stdout,  0); }

int main(int argc,char *argv[])
{
  printf("milk2spr version 0.9\n"
    "A Milk Shape ASCII model convertor for Crystal Space.\n"
    "By Steven Geens <steven.geens@student.kuleuven.ac.be>\n\n");

  float frameDuration = FRAME_DURATION_DEFAULT;

  if (argc < 2)
  {
    fatal_usage();
  }
  if (argc < 3)
  {
    switch (argv[1][1])
    {
      case 'c':
        printCode(stdout,  0);
      default:
       fatal_usage();
    }
  }
  else
  {
    int i;
    for (i = 1; i < argc - 2; i++)
    {
      if (argv[i][0] != '-' && argv[i][0] != '/')
      {
        fprintf(stderr, "'%s' unreconized option\n", argv[i]);
        fatal_usage();
      }
      switch (argv[i][1])
      {
      case 'h':
      case '?':
        okay_usage();break;
      case 'c':
        printCode(stdout,  0);break;
      case 'd':
        sscanf (argv[++i], "%f", &frameDuration);
        printf("The duration of a frame set to %g seconds.\n", frameDuration);
        break;
      default:
        fprintf(stderr, "'%s' unreconized option.\n", argv[i]);
        fatal_usage();
      }
    }
  }

  const char* msfile = argv[argc - 2];
  MsModel* ms = NULL;
  if (MsModel::IsFileMsModel(msfile))
    ms = new MsModel(msfile,frameDuration);
  else
  {
    fprintf(stderr, "Not a recognized model file: %s\n", msfile);
    exit(-1);
  }

  if (ms->getError())
  {
    fprintf(stderr, "\nError: %s\n", ms->getErrorString());
    delete ms;
    exit(-1);
  }

  ms->dumpstats(stdout);
  putchar('\n');
  ms->WriteSPR(argv[argc - 1]);

  delete ms;
  return 0;
}

<|endoftext|>