<commit_before>/**
  * Touhou Community Reliant Automatic Patcher
  * Tasogare Frontier support plugin
  *
  * ----
  *
  * On-the-fly th145 TFCS patcher (*.csv)
  * Most CSV files can also be provided as TFCS files (and are provided by the game as TFCS files).
  * These CSV files aren't supported for now because the ULiL TFCS parser
  * is way more reliable than the ULiL CSV parser for these files.
  * If we add CSV support here, I think we'd better do it in the form of CSV=>TFCS conversion,
  * followed by TFCS patching.
  */

#include <thcrap.h>
#include "thcrap_tasofro.h"
#include "tfcs.h"
#include "pl.h"
#include <zlib.h>
#include <string>
#include <vector>
#include <list>

static int inflate_bytes(BYTE* file_in, size_t size_in, BYTE* file_out, size_t size_out)
{
	int ret;
	z_stream strm;

	strm.zalloc = NULL;
	strm.zfree = NULL;
	strm.opaque = NULL;
	strm.next_in = file_in;
	strm.avail_in = size_in;
	strm.next_out = file_out;
	strm.avail_out = size_out;
	ret = inflateInit(&strm);
	if (ret != Z_OK) {
		return ret;
	}
	do {
		ret = inflate(&strm, Z_NO_FLUSH);
		if (ret != Z_OK) {
			break;
		}
	} while (ret != Z_STREAM_END);
	inflateEnd(&strm);
	return ret == Z_STREAM_END ? Z_OK : ret;
}

static int deflate_bytes(BYTE* file_in, size_t size_in, BYTE* file_out, size_t* size_out)
{
	int ret;
	z_stream strm;

	strm.zalloc = NULL;
	strm.zfree = NULL;
	strm.opaque = NULL;
	strm.next_in = file_in;
	strm.avail_in = size_in;
	strm.next_out = file_out;
	strm.avail_out = *size_out;
	ret = deflateInit(&strm, Z_BEST_COMPRESSION);
	if (ret != Z_OK) {
		return ret;
	}
	do {
		ret = deflate(&strm, Z_FINISH);
		if (ret != Z_OK) {
			break;
		}
	} while (ret != Z_STREAM_END);
	deflateEnd(&strm);
	*size_out -= strm.avail_out;
	return ret == Z_STREAM_END ? Z_OK : ret;
}

void patch_line(BYTE *&in, BYTE *&out, DWORD nb_col, json_t *patch_row)
{
	// Read input
	std::vector<std::string> line;
	for (DWORD col = 0; col < nb_col; col++) {
		DWORD field_size = *(DWORD*)in;
		in += sizeof(DWORD);
		line.push_back(std::string((const char*)in, field_size));
		in += field_size;
	}

	// Patch as data/win/message/*.csv
	json_t *patch_lines = json_object_get(patch_row, "lines");
	if (patch_lines && line.size() <= 13 && line[4].empty() == false) {
		std::list<TasofroPl::ALine*> texts;
		// We want to overwrite all the balloons with the user-provided ones,
		// so we only need to put the 1st one, we can ignore the others.
		TasofroPl::AText *text = new TasofroPl::WinText(std::vector<std::string>({
			line[4],
			line[3]
		}));
		texts.push_back(text);
		text->patch(texts, texts.begin(), "", patch_lines);

		size_t i = 0;
		for (TasofroPl::ALine* it : texts) {
			if (i == 3) {
				log_print("TFCS: warning: trying to put more than 3 balloons in a win line.\n");
				break;
			}
			line[1 + 4 * i + 3] = it->get(0);
			line[1 + 4 * i + 2] = it->get(1);
			i++;
		}
	}

	// Patch each column independently
	json_t *patch_col;
	for (DWORD col = 0; col < nb_col; col++) {
		patch_col = json_object_numkey_get(patch_row, col);
		if (patch_col && json_is_string(patch_col)) {
			line[col] = json_string_value(patch_col);
		}
	}

	// Write output
	for (const std::string& col : line) {
		DWORD field_size = col.length();
		*(DWORD*)out = field_size;
		out += sizeof(DWORD);
		memcpy(out, col.c_str(), field_size);
		out += field_size;
	}
}

void skip_line(BYTE *&in, BYTE *&out, DWORD nb_col)
{
	for (DWORD col = 0; col < nb_col; col++) {
		DWORD field_size = *(DWORD*)in; in += sizeof(DWORD);
		*(DWORD*)out = field_size;      out += sizeof(DWORD);

		memcpy(out, in, field_size);
		in  += field_size;
		out += field_size;
	}
}

int patch_tfcs(void *file_inout, size_t size_out, size_t size_in, const char *fn, json_t *patch)
{
	if (!patch) {
		return 0;
	}

	tfcs_header_t *header;

	// Read TFCS header
	header = (tfcs_header_t*)file_inout;
	if (size_in < sizeof(header) || memcmp(header->magic, "TFCS\0", 5) != 0) {
		// Invalid TFCS file (probably a regular CSV file)
		return patch_csv(file_inout, size_out, size_in, fn, patch);
	}

	BYTE *file_in_uncomp = (BYTE*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, header->uncomp_size);
	inflate_bytes(header->data, header->comp_size, file_in_uncomp, header->uncomp_size);

	// We don't have patch_size here, but it is equal to size_out - size_in.
	DWORD file_out_uncomp_size = header->uncomp_size + (size_out - size_in);
	BYTE *file_out_uncomp = (BYTE*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, file_out_uncomp_size);

	BYTE *ptr_in  = file_in_uncomp;
	BYTE *ptr_out = file_out_uncomp;

	DWORD nb_row;
	DWORD nb_col;
	DWORD row;

	nb_row = *(DWORD*)ptr_in;  ptr_in  += sizeof(DWORD);
	*(DWORD*)ptr_out = nb_row; ptr_out += sizeof(DWORD);

	for (row = 0; row < nb_row; row++) {
		nb_col = *(DWORD*)ptr_in;  ptr_in  += sizeof(DWORD);
		*(DWORD*)ptr_out = nb_col; ptr_out += sizeof(DWORD);
		json_t *patch_row = json_object_numkey_get(patch, row);

		if (patch_row) {
			patch_line(ptr_in, ptr_out, nb_col, patch_row);
		}
		else {
			skip_line(ptr_in, ptr_out, nb_col);
		}
	}

	// Write result
	file_out_uncomp_size = ptr_out - file_out_uncomp;
	header->uncomp_size = file_out_uncomp_size;
	size_out -= sizeof(header) - 1;
	int ret = deflate_bytes(file_out_uncomp, file_out_uncomp_size, header->data, &size_out);
	header->comp_size = size_out;
	if (ret != Z_OK) {
		log_printf("WARNING: tasofro CSV patching: compression failed with zlib error %d\n", ret);
	}

	HeapFree(GetProcessHeap(), 0, file_in_uncomp);
	HeapFree(GetProcessHeap(), 0, file_out_uncomp);

	return 1;
}

size_t get_tfcs_size(const char*, json_t*, size_t patch_size)
{
	// Because a lot of these files are zipped, guessing their exact patched size is hard. We'll add a few more bytes.
	if (patch_size) {
		return (size_t)(patch_size * 1.2) + 1;
	}
	else {
		return 0;
	}
}<commit_msg>thcrap_tasofro: Add support for th155 win messages. [V]<commit_after>/**
  * Touhou Community Reliant Automatic Patcher
  * Tasogare Frontier support plugin
  *
  * ----
  *
  * On-the-fly th145 TFCS patcher (*.csv)
  * Most CSV files can also be provided as TFCS files (and are provided by the game as TFCS files).
  * These CSV files aren't supported for now because the ULiL TFCS parser
  * is way more reliable than the ULiL CSV parser for these files.
  * If we add CSV support here, I think we'd better do it in the form of CSV=>TFCS conversion,
  * followed by TFCS patching.
  */

#include <thcrap.h>
#include "thcrap_tasofro.h"
#include "tfcs.h"
#include "pl.h"
#include <zlib.h>
#include <string>
#include <vector>
#include <list>

static int inflate_bytes(BYTE* file_in, size_t size_in, BYTE* file_out, size_t size_out)
{
	int ret;
	z_stream strm;

	strm.zalloc = NULL;
	strm.zfree = NULL;
	strm.opaque = NULL;
	strm.next_in = file_in;
	strm.avail_in = size_in;
	strm.next_out = file_out;
	strm.avail_out = size_out;
	ret = inflateInit(&strm);
	if (ret != Z_OK) {
		return ret;
	}
	do {
		ret = inflate(&strm, Z_NO_FLUSH);
		if (ret != Z_OK) {
			break;
		}
	} while (ret != Z_STREAM_END);
	inflateEnd(&strm);
	return ret == Z_STREAM_END ? Z_OK : ret;
}

static int deflate_bytes(BYTE* file_in, size_t size_in, BYTE* file_out, size_t* size_out)
{
	int ret;
	z_stream strm;

	strm.zalloc = NULL;
	strm.zfree = NULL;
	strm.opaque = NULL;
	strm.next_in = file_in;
	strm.avail_in = size_in;
	strm.next_out = file_out;
	strm.avail_out = *size_out;
	ret = deflateInit(&strm, Z_BEST_COMPRESSION);
	if (ret != Z_OK) {
		return ret;
	}
	do {
		ret = deflate(&strm, Z_FINISH);
		if (ret != Z_OK) {
			break;
		}
	} while (ret != Z_STREAM_END);
	deflateEnd(&strm);
	*size_out -= strm.avail_out;
	return ret == Z_STREAM_END ? Z_OK : ret;
}

void patch_line(BYTE *&in, BYTE *&out, DWORD nb_col, json_t *patch_row)
{
	// Read input
	std::vector<std::string> line;
	for (DWORD col = 0; col < nb_col; col++) {
		DWORD field_size = *(DWORD*)in;
		in += sizeof(DWORD);
		line.push_back(std::string((const char*)in, field_size));
		in += field_size;
	}

	// Patch as data/win/message/*.csv
	unsigned int start;
	if (game_id <= TH145) {
		start = 1;
	}
	else {
		start = 9;
	}
	json_t *patch_lines = json_object_get(patch_row, "lines");
	if (patch_lines && line.size() <= start + 12 && line[start + 3].empty() == false) {
		std::list<TasofroPl::ALine*> texts;
		// We want to overwrite all the balloons with the user-provided ones,
		// so we only need to put the 1st one, we can ignore the others.
		TasofroPl::AText *text = new TasofroPl::WinText(std::vector<std::string>({
			line[start + 3],
			line[start + 2]
		}));
		texts.push_back(text);
		text->patch(texts, texts.begin(), "", patch_lines);

		size_t i = 0;
		for (TasofroPl::ALine* it : texts) {
			if (i == 3) {
				log_print("TFCS: warning: trying to put more than 3 balloons in a win line.\n");
				break;
			}
			line[start + 4 * i + 3] = it->get(0);
			line[start + 4 * i + 2] = it->get(1);
			i++;
		}
	}

	// Patch each column independently
	json_t *patch_col;
	for (DWORD col = 0; col < nb_col; col++) {
		patch_col = json_object_numkey_get(patch_row, col);
		if (patch_col && json_is_string(patch_col)) {
			line[col] = json_string_value(patch_col);
		}
	}

	// Write output
	for (const std::string& col : line) {
		DWORD field_size = col.length();
		*(DWORD*)out = field_size;
		out += sizeof(DWORD);
		memcpy(out, col.c_str(), field_size);
		out += field_size;
	}
}

void skip_line(BYTE *&in, BYTE *&out, DWORD nb_col)
{
	for (DWORD col = 0; col < nb_col; col++) {
		DWORD field_size = *(DWORD*)in; in += sizeof(DWORD);
		*(DWORD*)out = field_size;      out += sizeof(DWORD);

		memcpy(out, in, field_size);
		in  += field_size;
		out += field_size;
	}
}

int patch_tfcs(void *file_inout, size_t size_out, size_t size_in, const char *fn, json_t *patch)
{
	if (!patch) {
		return 0;
	}

	tfcs_header_t *header;

	// Read TFCS header
	header = (tfcs_header_t*)file_inout;
	if (size_in < sizeof(header) || memcmp(header->magic, "TFCS\0", 5) != 0) {
		// Invalid TFCS file (probably a regular CSV file)
		return patch_csv(file_inout, size_out, size_in, fn, patch);
	}

	BYTE *file_in_uncomp = (BYTE*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, header->uncomp_size);
	inflate_bytes(header->data, header->comp_size, file_in_uncomp, header->uncomp_size);

	// We don't have patch_size here, but it is equal to size_out - size_in.
	DWORD file_out_uncomp_size = header->uncomp_size + (size_out - size_in);
	BYTE *file_out_uncomp = (BYTE*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, file_out_uncomp_size);

	BYTE *ptr_in  = file_in_uncomp;
	BYTE *ptr_out = file_out_uncomp;

	DWORD nb_row;
	DWORD nb_col;
	DWORD row;

	nb_row = *(DWORD*)ptr_in;  ptr_in  += sizeof(DWORD);
	*(DWORD*)ptr_out = nb_row; ptr_out += sizeof(DWORD);

	for (row = 0; row < nb_row; row++) {
		nb_col = *(DWORD*)ptr_in;  ptr_in  += sizeof(DWORD);
		*(DWORD*)ptr_out = nb_col; ptr_out += sizeof(DWORD);
		json_t *patch_row = json_object_numkey_get(patch, row);

		if (patch_row) {
			patch_line(ptr_in, ptr_out, nb_col, patch_row);
		}
		else {
			skip_line(ptr_in, ptr_out, nb_col);
		}
	}

	// Write result
	file_out_uncomp_size = ptr_out - file_out_uncomp;
	header->uncomp_size = file_out_uncomp_size;
	size_out -= sizeof(header) - 1;
	int ret = deflate_bytes(file_out_uncomp, file_out_uncomp_size, header->data, &size_out);
	header->comp_size = size_out;
	if (ret != Z_OK) {
		log_printf("WARNING: tasofro CSV patching: compression failed with zlib error %d\n", ret);
	}

	HeapFree(GetProcessHeap(), 0, file_in_uncomp);
	HeapFree(GetProcessHeap(), 0, file_out_uncomp);

	return 1;
}

size_t get_tfcs_size(const char*, json_t*, size_t patch_size)
{
	// Because a lot of these files are zipped, guessing their exact patched size is hard. We'll add a few more bytes.
	if (patch_size) {
		return (size_t)(patch_size * 1.2) + 1;
	}
	else {
		return 0;
	}
}<|endoftext|>


<commit_before>#include "stdafx.h"
#include "ResourceLoader\NLREAssimpAssetImporter.h"

NLREAssimpAssetImporter::NLREAssimpAssetImporter(NLRERenderingDevice* renderingDevice, NLRETextureLoader* textureLoader)
{
	_renderingDevice = renderingDevice;
	_textureLoader = textureLoader;

	if (!initialize())
	{
		NLRE_Log::err(NLRE_Log::CRITICAL, "Assimp asset importer failed to initialize");
		throw std::exception("Assimp asset importer failed to initialize");
	}
}

NLREAssimpAssetImporter::NLREAssimpAssetImporter(const NLREAssimpAssetImporter& other)
{
}

NLREAssimpAssetImporter::~NLREAssimpAssetImporter()
{

}

bool NLREAssimpAssetImporter::initialize()
{
	if (_renderingDevice == NULL || _textureLoader == NULL)
	{
		NLRE_Log::err(NLRE_Log::CRITICAL, "Un-initialized parameters");
		return false;
	}

	return true;
}

bool NLREAssimpAssetImporter::importAssets(std::wstring path, std::vector<NLRE_RenderableAsset*>& assets)
{
	Assimp::Importer importer;
	std::string assetPath(path.begin(), path.end());
	const aiScene* scene = importer.ReadFile(assetPath.c_str(),
		aiProcess_MakeLeftHanded |
		aiProcess_CalcTangentSpace |
		aiProcess_Triangulate |
		aiProcess_JoinIdenticalVertices |
		aiProcess_GenUVCoords|
		aiProcess_GenNormals |
		aiProcess_SortByPType|
		aiProcess_RemoveComponent|
		//aiProcess_FlipUVs				|
		aiProcess_SortByPType);

	if (!scene)
	{
		NLRE_Log::err(NLRE_Log::REG, "Failed to import asset: ", assetPath);
		return false;
	}

	assets = loadAsStatic(scene);

	return true;
}

std::vector<NLRE_RenderableAsset*> NLREAssimpAssetImporter::loadAsStatic(const aiScene* scene)
{
	std::vector<NLRE_RenderableAsset*> assets;
	NLRE_Mesh** meshArr = loadMeshes(scene);
	NLRE_Material** materialArr = loadMaterials(scene);

	//nextNode(scene, scene->mRootNode, scene->mRootNode->mTransformation, meshes);
	return assets;
}

/*void NLREAssimpAssetImporter::nextNode(const aiScene* scene, aiNode* node, aiMatrix4x4& accTransform, std::vector<NLRE_Mesh*>& meshes)
{
	aiMatrix4x4 transform;

	if (node->mNumMeshes > 0)
	{
		for (int i = 0; i < node->mNumMeshes; i++)
		{
			addMesh(scene, node->mMeshes[i], transform, meshes);
		}
	}
	else
	{
		transform = node->mTransformation * accTransform;
	}
	for (int i = 0; i < node->mNumChildren; i++)
	{
		nextNode(scene, node->mChildren[i], transform, meshes);
	}
}
*/
NLRE_Mesh** NLREAssimpAssetImporter::loadMeshes(const aiScene* scene)
{
	if (!scene->HasMeshes()) return NULL;

	NLRE_Mesh** meshArr = new NLRE_Mesh*[scene->mNumMeshes];
	for (int i = 0; i < scene->mNumMeshes; i++)
	{
		NLRE_GeomStr* geomStreamArr = NULL;
		unsigned int geomStreamLength = 0;
		loadGeometryStream(scene->mMeshes[i], geomStreamArr, geomStreamLength);
		_renderingDevice->createBuffer<NLRE_GeomStr>(NLRE_BIND_VERTEX_BUFFER, NLRE_USAGE_IMMUTABLE, geomStreamArr, geomStreamLength, meshArr[i]->geomBuffer);

		NLRE_Index* indexArr = NULL;
		unsigned int indexArrLength = 0;
		loadIndices(scene->mMeshes[i], indexArr, indexArrLength);
		_renderingDevice->createBuffer<NLRE_Index>(NLRE_BIND_INDEX_BUFFER, NLRE_USAGE_IMMUTABLE, indexArr, indexArrLength, meshArr[i]->indexBuffer);
	}

	return meshArr;
}

void NLREAssimpAssetImporter::loadGeometryStream(aiMesh* mesh, NLRE_GeomStr*& geomStreamArr, unsigned int& streamLength)
{
	if (!mesh->HasPositions()) return;

	streamLength = mesh->mNumVertices;
	geomStreamArr = new NLRE_GeomStr[streamLength];
	for (int i = 0; i < streamLength; i++)
	{
		const aiVector3D* pos = &(mesh->mVertices[i]);
		const aiVector3D* normal = &(mesh->mNormals[i]);
		const aiVector3D* texCoord = &(mesh->mTextureCoords[0][i]);

		geomStreamArr[i].position = NLE_FLOAT3(pos->x, pos->y, pos->z);
		if (mesh->HasNormals())
		{
			geomStreamArr[i].normal = NLE_FLOAT3(normal->x, normal->y, normal->z);
		}
		if (mesh->HasTextureCoords(0))
		{
			geomStreamArr[i].textCoord = NLE_FLOAT2(texCoord->x, texCoord->y);
		}
	}
}

void NLREAssimpAssetImporter::loadIndices(aiMesh* mesh, NLRE_Index*& indexArr, unsigned int& indexArrLength)
{
	if (!mesh->HasFaces()) return;

	indexArrLength = mesh->mNumFaces * 3;
	indexArr = new NLRE_Index[indexArrLength];
	int counter = 0;
	for (int k = 0; k < mesh->mNumFaces; k++)
	{
		const aiFace& tempFace = mesh->mFaces[k];
		for (int m = 0; m < 3; m++)
		{
			indexArr[counter] = tempFace.mIndices[m];
			counter++;
		}
	}
}

NLRE_Material** NLREAssimpAssetImporter::loadMaterials(const aiScene* scene)
{
	if (!scene->HasMaterials()) return NULL;

	NLRE_Material** materialArr = new NLRE_Material*[scene->mNumMaterials];
	for (int i = 0; i < scene->mNumMaterials; i++)
	{
		NLRE_MaterialBufferStruct materialBuffStruct;
		loadMaterialBuffer(scene->mMaterials[i], materialBuffStruct);
		_renderingDevice->createBuffer<NLRE_MaterialBufferStruct>(NLRE_BIND_CONSTANT_BUFFER, NLRE_USAGE_IMMUTABLE, &materialBuffStruct, 1, materialArr[i]->materialBuffer);

		loadMaterialParams(scene->mMaterials[i], materialArr[i]);
	}
	return materialArr;
}

void NLREAssimpAssetImporter::loadMaterialParams(aiMaterial* material, NLRE_Material*& nlreMaterial)
{
	material->Get(AI_MATKEY_TWOSIDED, nlreMaterial->twoSided);

	int temp = 0;

	if (material->Get(AI_MATKEY_BLEND_FUNC, temp) == AI_SUCCESS) nlreMaterial->blendMode = temp;
	if (material->Get(AI_MATKEY_SHADING_MODEL, temp) == AI_SUCCESS) nlreMaterial->shadingModel = temp;
	if (material->Get(AI_MATKEY_MAPPINGMODE_U_DIFFUSE(0), temp) == AI_SUCCESS) nlreMaterial->textureMappingMode_u = temp;
	if (material->Get(AI_MATKEY_MAPPINGMODE_V_DIFFUSE(0), temp) == AI_SUCCESS) nlreMaterial->textureMappingMode_v = temp;
}

void NLREAssimpAssetImporter::loadMaterialBuffer(aiMaterial* material, NLRE_MaterialBufferStruct& materialStruct)
{
		aiColor3D tempColor;
		if (material->Get(AI_MATKEY_COLOR_DIFFUSE, tempColor) == AI_SUCCESS)
		{
			materialStruct.diffuseColor.x = tempColor.r;
			materialStruct.diffuseColor.y = tempColor.g;
			materialStruct.diffuseColor.z = tempColor.b;
		}
		if (material->Get(AI_MATKEY_COLOR_AMBIENT, tempColor) == AI_SUCCESS)
		{
			materialStruct.ambientColor.x = tempColor.r;
			materialStruct.ambientColor.y = tempColor.g;
			materialStruct.ambientColor.z = tempColor.b;
		}
		if (material->Get(AI_MATKEY_COLOR_SPECULAR, tempColor) == AI_SUCCESS)
		{
			materialStruct.specularColor.x = tempColor.r;
			materialStruct.specularColor.y = tempColor.g;
			materialStruct.specularColor.z = tempColor.b;
		}
		if (material->Get(AI_MATKEY_COLOR_EMISSIVE, tempColor) == AI_SUCCESS)
		{
			materialStruct.emissiveColor.x = tempColor.r;
			materialStruct.emissiveColor.y = tempColor.g;
			materialStruct.emissiveColor.z = tempColor.b;
		}
		if (material->Get(AI_MATKEY_COLOR_TRANSPARENT, tempColor) == AI_SUCCESS)
		{
			materialStruct.transparentColor.x = tempColor.r;
			materialStruct.transparentColor.y = tempColor.g;
			materialStruct.transparentColor.z = tempColor.b;
		}

		float temp = 0.0f;
		if (material->Get(AI_MATKEY_OPACITY, temp) == AI_SUCCESS) materialStruct.opacity = temp;
		if(material->Get(AI_MATKEY_SHININESS, temp) == AI_SUCCESS) materialStruct.shininess = temp;
		if(material->Get(AI_MATKEY_SHININESS_STRENGTH, temp) == AI_SUCCESS) materialStruct.shininess_str = temp;
		if(material->Get(AI_MATKEY_REFRACTI, temp) == AI_SUCCESS) materialStruct.refracti = temp;
}<commit_msg>material params indented for readability<commit_after>#include "stdafx.h"
#include "ResourceLoader\NLREAssimpAssetImporter.h"

NLREAssimpAssetImporter::NLREAssimpAssetImporter(NLRERenderingDevice* renderingDevice, NLRETextureLoader* textureLoader)
{
	_renderingDevice = renderingDevice;
	_textureLoader = textureLoader;

	if (!initialize())
	{
		NLRE_Log::err(NLRE_Log::CRITICAL, "Assimp asset importer failed to initialize");
		throw std::exception("Assimp asset importer failed to initialize");
	}
}

NLREAssimpAssetImporter::NLREAssimpAssetImporter(const NLREAssimpAssetImporter& other)
{
}

NLREAssimpAssetImporter::~NLREAssimpAssetImporter()
{

}

bool NLREAssimpAssetImporter::initialize()
{
	if (_renderingDevice == NULL || _textureLoader == NULL)
	{
		NLRE_Log::err(NLRE_Log::CRITICAL, "Un-initialized parameters");
		return false;
	}

	return true;
}

bool NLREAssimpAssetImporter::importAssets(std::wstring path, std::vector<NLRE_RenderableAsset*>& assets)
{
	Assimp::Importer importer;
	std::string assetPath(path.begin(), path.end());
	const aiScene* scene = importer.ReadFile(assetPath.c_str(),
		aiProcess_MakeLeftHanded |
		aiProcess_CalcTangentSpace |
		aiProcess_Triangulate |
		aiProcess_JoinIdenticalVertices |
		aiProcess_GenUVCoords|
		aiProcess_GenNormals |
		aiProcess_SortByPType|
		aiProcess_RemoveComponent|
		//aiProcess_FlipUVs				|
		aiProcess_SortByPType);

	if (!scene)
	{
		NLRE_Log::err(NLRE_Log::REG, "Failed to import asset: ", assetPath);
		return false;
	}

	assets = loadAsStatic(scene);

	return true;
}

std::vector<NLRE_RenderableAsset*> NLREAssimpAssetImporter::loadAsStatic(const aiScene* scene)
{
	std::vector<NLRE_RenderableAsset*> assets;
	NLRE_Mesh** meshArr = loadMeshes(scene);
	NLRE_Material** materialArr = loadMaterials(scene);

	//nextNode(scene, scene->mRootNode, scene->mRootNode->mTransformation, meshes);
	return assets;
}

/*void NLREAssimpAssetImporter::nextNode(const aiScene* scene, aiNode* node, aiMatrix4x4& accTransform, std::vector<NLRE_Mesh*>& meshes)
{
	aiMatrix4x4 transform;

	if (node->mNumMeshes > 0)
	{
		for (int i = 0; i < node->mNumMeshes; i++)
		{
			addMesh(scene, node->mMeshes[i], transform, meshes);
		}
	}
	else
	{
		transform = node->mTransformation * accTransform;
	}
	for (int i = 0; i < node->mNumChildren; i++)
	{
		nextNode(scene, node->mChildren[i], transform, meshes);
	}
}
*/
NLRE_Mesh** NLREAssimpAssetImporter::loadMeshes(const aiScene* scene)
{
	if (!scene->HasMeshes()) return NULL;

	NLRE_Mesh** meshArr = new NLRE_Mesh*[scene->mNumMeshes];
	for (int i = 0; i < scene->mNumMeshes; i++)
	{
		NLRE_GeomStr* geomStreamArr = NULL;
		unsigned int geomStreamLength = 0;
		loadGeometryStream(scene->mMeshes[i], geomStreamArr, geomStreamLength);
		_renderingDevice->createBuffer<NLRE_GeomStr>(NLRE_BIND_VERTEX_BUFFER, NLRE_USAGE_IMMUTABLE, geomStreamArr, geomStreamLength, meshArr[i]->geomBuffer);

		NLRE_Index* indexArr = NULL;
		unsigned int indexArrLength = 0;
		loadIndices(scene->mMeshes[i], indexArr, indexArrLength);
		_renderingDevice->createBuffer<NLRE_Index>(NLRE_BIND_INDEX_BUFFER, NLRE_USAGE_IMMUTABLE, indexArr, indexArrLength, meshArr[i]->indexBuffer);
	}

	return meshArr;
}

void NLREAssimpAssetImporter::loadGeometryStream(aiMesh* mesh, NLRE_GeomStr*& geomStreamArr, unsigned int& streamLength)
{
	if (!mesh->HasPositions()) return;

	streamLength = mesh->mNumVertices;
	geomStreamArr = new NLRE_GeomStr[streamLength];
	for (int i = 0; i < streamLength; i++)
	{
		const aiVector3D* pos = &(mesh->mVertices[i]);
		const aiVector3D* normal = &(mesh->mNormals[i]);
		const aiVector3D* texCoord = &(mesh->mTextureCoords[0][i]);

		geomStreamArr[i].position = NLE_FLOAT3(pos->x, pos->y, pos->z);
		if (mesh->HasNormals())
		{
			geomStreamArr[i].normal = NLE_FLOAT3(normal->x, normal->y, normal->z);
		}
		if (mesh->HasTextureCoords(0))
		{
			geomStreamArr[i].textCoord = NLE_FLOAT2(texCoord->x, texCoord->y);
		}
	}
}

void NLREAssimpAssetImporter::loadIndices(aiMesh* mesh, NLRE_Index*& indexArr, unsigned int& indexArrLength)
{
	if (!mesh->HasFaces()) return;

	indexArrLength = mesh->mNumFaces * 3;
	indexArr = new NLRE_Index[indexArrLength];
	int counter = 0;
	for (int k = 0; k < mesh->mNumFaces; k++)
	{
		const aiFace& tempFace = mesh->mFaces[k];
		for (int m = 0; m < 3; m++)
		{
			indexArr[counter] = tempFace.mIndices[m];
			counter++;
		}
	}
}

NLRE_Material** NLREAssimpAssetImporter::loadMaterials(const aiScene* scene)
{
	if (!scene->HasMaterials()) return NULL;

	NLRE_Material** materialArr = new NLRE_Material*[scene->mNumMaterials];
	for (int i = 0; i < scene->mNumMaterials; i++)
	{
		NLRE_MaterialBufferStruct materialBuffStruct;
		loadMaterialBuffer(scene->mMaterials[i], materialBuffStruct);
		_renderingDevice->createBuffer<NLRE_MaterialBufferStruct>(NLRE_BIND_CONSTANT_BUFFER, NLRE_USAGE_IMMUTABLE, &materialBuffStruct, 1, materialArr[i]->materialBuffer);

		loadMaterialParams(scene->mMaterials[i], materialArr[i]);
	}
	return materialArr;
}

void NLREAssimpAssetImporter::loadMaterialParams(aiMaterial* material, NLRE_Material*& nlreMaterial)
{
	material->Get(AI_MATKEY_TWOSIDED, nlreMaterial->twoSided);

	int temp = 0;

	if (material->Get(AI_MATKEY_BLEND_FUNC, temp) == AI_SUCCESS)				nlreMaterial->blendMode = temp;
	if (material->Get(AI_MATKEY_SHADING_MODEL, temp) == AI_SUCCESS)				nlreMaterial->shadingModel = temp;
	if (material->Get(AI_MATKEY_MAPPINGMODE_U_DIFFUSE(0), temp) == AI_SUCCESS)	nlreMaterial->textureMappingMode_u = temp;
	if (material->Get(AI_MATKEY_MAPPINGMODE_V_DIFFUSE(0), temp) == AI_SUCCESS)	nlreMaterial->textureMappingMode_v = temp;
}

void NLREAssimpAssetImporter::loadMaterialBuffer(aiMaterial* material, NLRE_MaterialBufferStruct& materialStruct)
{
		aiColor3D tempColor;
		if (material->Get(AI_MATKEY_COLOR_DIFFUSE, tempColor) == AI_SUCCESS)
		{
			materialStruct.diffuseColor.x = tempColor.r;
			materialStruct.diffuseColor.y = tempColor.g;
			materialStruct.diffuseColor.z = tempColor.b;
		}
		if (material->Get(AI_MATKEY_COLOR_AMBIENT, tempColor) == AI_SUCCESS)
		{
			materialStruct.ambientColor.x = tempColor.r;
			materialStruct.ambientColor.y = tempColor.g;
			materialStruct.ambientColor.z = tempColor.b;
		}
		if (material->Get(AI_MATKEY_COLOR_SPECULAR, tempColor) == AI_SUCCESS)
		{
			materialStruct.specularColor.x = tempColor.r;
			materialStruct.specularColor.y = tempColor.g;
			materialStruct.specularColor.z = tempColor.b;
		}
		if (material->Get(AI_MATKEY_COLOR_EMISSIVE, tempColor) == AI_SUCCESS)
		{
			materialStruct.emissiveColor.x = tempColor.r;
			materialStruct.emissiveColor.y = tempColor.g;
			materialStruct.emissiveColor.z = tempColor.b;
		}
		if (material->Get(AI_MATKEY_COLOR_TRANSPARENT, tempColor) == AI_SUCCESS)
		{
			materialStruct.transparentColor.x = tempColor.r;
			materialStruct.transparentColor.y = tempColor.g;
			materialStruct.transparentColor.z = tempColor.b;
		}

		float temp = 0.0f;
		if(material->Get(AI_MATKEY_OPACITY, temp) == AI_SUCCESS)			materialStruct.opacity = temp;
		if(material->Get(AI_MATKEY_SHININESS, temp) == AI_SUCCESS)			materialStruct.shininess = temp;
		if(material->Get(AI_MATKEY_SHININESS_STRENGTH, temp) == AI_SUCCESS) materialStruct.shininess_str = temp;
		if(material->Get(AI_MATKEY_REFRACTI, temp) == AI_SUCCESS)			materialStruct.refracti = temp;
}<|endoftext|>


<commit_before>// Copyright eeGeo Ltd 2016, All Rights Reserved

#include "EegeoJsonParser.h"
#include "SearchVendorNames.h"
#include "TimeHelpers.h"
#include "InteriorId.h"

#include "document.h"
#include "writer.h"
#include "stringbuffer.h"

#include <sstream>
#include <map>

namespace ExampleApp
{
    namespace Search
    {
        namespace EegeoPois
        {
            namespace SdkModel
            {
                namespace
                {
                    auto SplitIntoTags(const std::string& str, char c)
                    {
                        std::vector<std::string> tags;
                        unsigned previous_start = -1;

                        for (unsigned i = 0; i < str.length(); ++i)
                        {
                            if (str[i] == c)
                            {
                                tags.push_back(str.substr(previous_start + 1, i - previous_start));
                                previous_start = i;
                            }
                        }

                        if (previous_start != str.length() - 1)
                        {
                            tags.push_back(str.substr(previous_start + 1));
                        }

                        return tags;
                    }

                    Search::SdkModel::SearchResultModel ParseSearchResultFromJsonObject(const rapidjson::Value& json)
                    {
                        Eegeo::Space::LatLong location = Eegeo::Space::LatLong::FromDegrees(json["lat"].GetDouble(),
                                                                                json["lon"].GetDouble());

                        std::stringstream idStream;
                        idStream << json["id"].GetInt();

                        bool indoor = json["indoor"].GetBool();
                        Eegeo::Resources::Interiors::InteriorId interiorId(json["indoor_id"].GetString());

                        //TODO: Remove once model supports only tags
                        std::string category = "misc";
                        std::vector<std::string> tags = SplitIntoTags(json["tags"].GetString(), ' ');

                        std::string userData = "";

                        if (json.HasMember("user_data"))
                        {
                            if (json["user_data"].HasMember("subcategory") && json["user_data"]["subcategory"].IsString())
                            {
                                category = json["user_data"]["subcategory"].GetString();
                            }
                            rapidjson::StringBuffer strbuf;
                            rapidjson::Writer<rapidjson::StringBuffer> writer(strbuf);
                            json["user_data"].Accept(writer);
                            userData = strbuf.GetString();
                        }

                        return ExampleApp::Search::SdkModel::SearchResultModel(ExampleApp::Search::SdkModel::SearchResultModel::CurrentVersion,
                                                                               idStream.str(),
                                                                               json["title"].GetString(),
                                                                               json["subtitle"].GetString(),
                                                                               location,
                                                                               static_cast<float>(json["height_offset"].GetDouble()),
                                                                               indoor,
                                                                               interiorId,
                                                                               json["floor_id"].GetInt(),
                                                                               category,
                                                                               tags,
                                                                               ExampleApp::Search::EegeoVendorName,
                                                                               userData,
                                                                               Eegeo::Helpers::Time::MillisecondsSinceEpoch());
                    }
                }

                void EegeoJsonParser::ParseEegeoQueryResults(const std::string& serialized,
                                                                 std::vector<Search::SdkModel::SearchResultModel>& out_results)
                {
                    rapidjson::Document document;

                    if (!document.Parse<0>(serialized.c_str()).HasParseError())
                    {
                        size_t numEntries = document.Size();

                        for(int i = 0; i < numEntries; ++i)
                        {
                            const rapidjson::Value& json = document[i];
                            Search::SdkModel::SearchResultModel result(ParseSearchResultFromJsonObject(json));
                            out_results.push_back(result);
                        }
                    }
                }

                EegeoSearchResultModel TransformToEegeoSearchResult(const Search::SdkModel::SearchResultModel& searchResultModel)
                {
                    rapidjson::Document json;

                    std::string phone = "";
                    std::string webUrl = "";
                    std::string imageUrl = "";

                    if (!json.Parse<0>(searchResultModel.GetJsonData().c_str()).HasParseError())
                    {

                        if(json.HasMember("phone"))
                        {
                            phone = json["phone"].GetString();
                        }

                        if(json.HasMember("web"))
                        {
                            webUrl = json["web"].GetString();
                        }

                        if(json.HasMember("image_url"))
                        {
                            imageUrl = json["image_url"].GetString();
                            const size_t lastSlashIndex(imageUrl.rfind("/"));
                            Eegeo_ASSERT(lastSlashIndex != std::string::npos, "The image_url is not well formed: %s.\n",
                                         imageUrl.c_str());
                        }

                    }

                    return EegeoSearchResultModel(phone,
                                                 webUrl,
                                                 imageUrl);
                }

                bool TryParseImageDetails(const Search::SdkModel::SearchResultModel& searchResultModel, std::string& out_imageUrl)
                {
                    if(searchResultModel.GetVendor() == ExampleApp::Search::EegeoVendorName)
                    {
                        Search::EegeoPois::SdkModel::EegeoSearchResultModel eegeoResultModel = Search::EegeoPois::SdkModel::TransformToEegeoSearchResult(searchResultModel);

                        out_imageUrl = eegeoResultModel.GetImageUrl();

                        return true;
                    }

                    return false;
                }
            }
        }
    }
}
<commit_msg>Add missing fixup<commit_after>// Copyright eeGeo Ltd 2016, All Rights Reserved

#include "EegeoJsonParser.h"
#include "SearchVendorNames.h"
#include "TimeHelpers.h"
#include "InteriorId.h"

#include "document.h"
#include "writer.h"
#include "stringbuffer.h"

#include <sstream>
#include <map>

namespace ExampleApp
{
    namespace Search
    {
        namespace EegeoPois
        {
            namespace SdkModel
            {
                namespace
                {
                    std::vector<std::string> SplitIntoTags(const std::string& str, char c)
                    {
                        std::vector<std::string> tags;
                        unsigned previous_start = -1;

                        for (unsigned i = 0; i < str.length(); ++i)
                        {
                            if (str[i] == c)
                            {
                                tags.push_back(str.substr(previous_start + 1, i - previous_start));
                                previous_start = i;
                            }
                        }

                        if (previous_start != str.length() - 1)
                        {
                            tags.push_back(str.substr(previous_start + 1));
                        }

                        return tags;
                    }

                    Search::SdkModel::SearchResultModel ParseSearchResultFromJsonObject(const rapidjson::Value& json)
                    {
                        Eegeo::Space::LatLong location = Eegeo::Space::LatLong::FromDegrees(json["lat"].GetDouble(),
                                                                                json["lon"].GetDouble());

                        std::stringstream idStream;
                        idStream << json["id"].GetInt();

                        bool indoor = json["indoor"].GetBool();
                        Eegeo::Resources::Interiors::InteriorId interiorId(json["indoor_id"].GetString());

                        //TODO: Remove once model supports only tags
                        std::string category = "misc";
                        std::vector<std::string> tags = SplitIntoTags(json["tags"].GetString(), ' ');

                        std::string userData = "";

                        if (json.HasMember("user_data"))
                        {
                            if (json["user_data"].HasMember("subcategory") && json["user_data"]["subcategory"].IsString())
                            {
                                category = json["user_data"]["subcategory"].GetString();
                            }
                            rapidjson::StringBuffer strbuf;
                            rapidjson::Writer<rapidjson::StringBuffer> writer(strbuf);
                            json["user_data"].Accept(writer);
                            userData = strbuf.GetString();
                        }

                        return ExampleApp::Search::SdkModel::SearchResultModel(ExampleApp::Search::SdkModel::SearchResultModel::CurrentVersion,
                                                                               idStream.str(),
                                                                               json["title"].GetString(),
                                                                               json["subtitle"].GetString(),
                                                                               location,
                                                                               static_cast<float>(json["height_offset"].GetDouble()),
                                                                               indoor,
                                                                               interiorId,
                                                                               json["floor_id"].GetInt(),
                                                                               category,
                                                                               tags,
                                                                               ExampleApp::Search::EegeoVendorName,
                                                                               userData,
                                                                               Eegeo::Helpers::Time::MillisecondsSinceEpoch());
                    }
                }

                void EegeoJsonParser::ParseEegeoQueryResults(const std::string& serialized,
                                                                 std::vector<Search::SdkModel::SearchResultModel>& out_results)
                {
                    rapidjson::Document document;

                    if (!document.Parse<0>(serialized.c_str()).HasParseError())
                    {
                        size_t numEntries = document.Size();

                        for(int i = 0; i < numEntries; ++i)
                        {
                            const rapidjson::Value& json = document[i];
                            Search::SdkModel::SearchResultModel result(ParseSearchResultFromJsonObject(json));
                            out_results.push_back(result);
                        }
                    }
                }

                EegeoSearchResultModel TransformToEegeoSearchResult(const Search::SdkModel::SearchResultModel& searchResultModel)
                {
                    rapidjson::Document json;

                    std::string phone = "";
                    std::string webUrl = "";
                    std::string imageUrl = "";

                    if (!json.Parse<0>(searchResultModel.GetJsonData().c_str()).HasParseError())
                    {

                        if(json.HasMember("phone"))
                        {
                            phone = json["phone"].GetString();
                        }

                        if(json.HasMember("web"))
                        {
                            webUrl = json["web"].GetString();
                        }

                        if(json.HasMember("image_url"))
                        {
                            imageUrl = json["image_url"].GetString();
                            const size_t lastSlashIndex(imageUrl.rfind("/"));
                            Eegeo_ASSERT(lastSlashIndex != std::string::npos, "The image_url is not well formed: %s.\n",
                                         imageUrl.c_str());
                        }

                    }

                    return EegeoSearchResultModel(phone,
                                                 webUrl,
                                                 imageUrl);
                }

                bool TryParseImageDetails(const Search::SdkModel::SearchResultModel& searchResultModel, std::string& out_imageUrl)
                {
                    if(searchResultModel.GetVendor() == ExampleApp::Search::EegeoVendorName)
                    {
                        Search::EegeoPois::SdkModel::EegeoSearchResultModel eegeoResultModel = Search::EegeoPois::SdkModel::TransformToEegeoSearchResult(searchResultModel);

                        out_imageUrl = eegeoResultModel.GetImageUrl();

                        return true;
                    }

                    return false;
                }
            }
        }
    }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fusumry.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: kz $ $Date: 2006-12-12 15:53:51 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"

#include "fusumry.hxx"

#ifndef _EEITEM_HXX //autogen
#include <svx/eeitem.hxx>
#endif
#ifndef _SVDOTEXT_HXX //autogen
#include <svx/svdotext.hxx>
#endif
#ifndef _SVDUNDO_HXX //autogen
#include <svx/svdundo.hxx>
#endif
#ifndef _SFX_PRINTER_HXX //autogen
#include <sfx2/printer.hxx>
#endif
#ifndef _OUTLOBJ_HXX
#include <svx/outlobj.hxx>
#endif

#include "strings.hrc"

#include "pres.hxx"
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#include "sdpage.hxx"
#ifndef SD_OUTLINER_HXX
#include "Outliner.hxx"
#endif
#ifndef SD_DRAW_VIEW_HXX
#include "drawview.hxx"
#endif
#include "drawdoc.hxx"
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#include "DrawDocShell.hxx"
#include "sdresid.hxx"
#include "optsitem.hxx"
#ifndef SD_DRAW_VIEW_SHELL_HXX
#include "DrawViewShell.hxx"
#endif

namespace sd {

TYPEINIT1( FuSummaryPage, FuPoor );

/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
FuSummaryPage::FuSummaryPage (
    ViewShell* pViewSh,
    ::sd::Window* pWin,
    ::sd::View* pView,
    SdDrawDocument* pDoc,
    SfxRequest& rReq)
    : FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
}

FunctionReference FuSummaryPage::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )
{
    FunctionReference xFunc( new FuSummaryPage( pViewSh, pWin, pView, pDoc, rReq ) );
    xFunc->DoExecute(rReq);
    return xFunc;
}

void FuSummaryPage::DoExecute( SfxRequest& rReq )
{
    ::sd::Outliner* pOutl = NULL;
    SdPage* pSummaryPage = NULL;
    USHORT i = 0;
    USHORT nFirstPage = SDRPAGE_NOTFOUND;
    USHORT nSelectedPages = 0;
    USHORT nCount = pDoc->GetSdPageCount(PK_STANDARD);

    while (i < nCount && nSelectedPages <= 1)
    {
        /**********************************************************************
        * Wieviele Seiten sind selektiert?
        * Genau eine Seite selektiert: Ab dieser Seite alles zusammenfassen
        * sonst: Nur die selektierten Seiten zusammenfassen
        **********************************************************************/
        SdPage* pActualPage = pDoc->GetSdPage(i, PK_STANDARD);

        if (pActualPage->IsSelected())
        {
            if (nFirstPage == SDRPAGE_NOTFOUND)
            {
                nFirstPage = i;
            }

            nSelectedPages++;
        }

        i++;
    }

    SfxStyleSheet* pStyle = NULL;

    for (i = nFirstPage; i < nCount; i++)
    {
        SdPage* pActualPage = pDoc->GetSdPage(i, PK_STANDARD);

        if (nSelectedPages <= 1 || pActualPage->IsSelected())
        {
            SdPage* pActualNotesPage = pDoc->GetSdPage(i, PK_NOTES);
            SdrTextObj* pTextObj = (SdrTextObj*) pActualPage->GetPresObj(PRESOBJ_TITLE);

            if (pTextObj && !pTextObj->IsEmptyPresObj())
            {
                if (!pSummaryPage)
                {
                    /**********************************************************
                    * Inhaltsverzeichnis-Seite einfuegen und Outliner anlegen
                    **********************************************************/
                    pView->BegUndo(String(SdResId(STR_UNDO_SUMMARY_PAGE)));
                    SetOfByte aVisibleLayers = pActualPage->TRG_GetMasterPageVisibleLayers();

                    // Seite mit Titel & Gliederung!
                    pSummaryPage = (SdPage*) pDoc->AllocPage(FALSE);
                    pSummaryPage->SetSize(pActualPage->GetSize() );
                    pSummaryPage->SetBorder(pActualPage->GetLftBorder(),
                                     pActualPage->GetUppBorder(),
                                     pActualPage->GetRgtBorder(),
                                     pActualPage->GetLwrBorder() );

                    // Seite hinten einfuegen
                    pDoc->InsertPage(pSummaryPage, nCount * 2 + 1);
                    pView->AddUndo(pDoc->GetSdrUndoFactory().CreateUndoNewPage(*pSummaryPage));

                    // MasterPage der aktuellen Seite verwenden
                    pSummaryPage->TRG_SetMasterPage(pActualPage->TRG_GetMasterPage());
                    pSummaryPage->SetLayoutName(pActualPage->GetLayoutName());
                    pSummaryPage->SetAutoLayout(AUTOLAYOUT_ENUM, TRUE);
                    pSummaryPage->TRG_SetMasterPageVisibleLayers(aVisibleLayers);
                    pSummaryPage->setHeaderFooterSettings(pActualPage->getHeaderFooterSettings());

                    // Notiz-Seite
                    SdPage* pNotesPage = (SdPage*) pDoc->AllocPage(FALSE);
                    pNotesPage->SetSize(pActualNotesPage->GetSize());
                    pNotesPage->SetBorder(pActualNotesPage->GetLftBorder(),
                                          pActualNotesPage->GetUppBorder(),
                                          pActualNotesPage->GetRgtBorder(),
                                          pActualNotesPage->GetLwrBorder() );
                    pNotesPage->SetPageKind(PK_NOTES);

                    // Seite hinten einfuegen
                    pDoc->InsertPage(pNotesPage, nCount * 2 + 2);
                    pView->AddUndo(pDoc->GetSdrUndoFactory().CreateUndoNewPage(*pNotesPage));

                    // MasterPage der aktuellen Seite verwenden
                    pNotesPage->TRG_SetMasterPage(pActualNotesPage->TRG_GetMasterPage());
                    pNotesPage->SetLayoutName(pActualNotesPage->GetLayoutName());
                    pNotesPage->SetAutoLayout(pActualNotesPage->GetAutoLayout(), TRUE);
                    pNotesPage->TRG_SetMasterPageVisibleLayers(aVisibleLayers);
                    pNotesPage->setHeaderFooterSettings(pActualNotesPage->getHeaderFooterSettings());

                    pOutl = new ::sd::Outliner( pDoc, OUTLINERMODE_OUTLINEOBJECT );
                    pOutl->SetUpdateMode(FALSE);
                    pOutl->EnableUndo(FALSE);

                    if (pDocSh)
                        pOutl->SetRefDevice(SD_MOD()->GetRefDevice( *pDocSh ));

                    pOutl->SetDefTab( pDoc->GetDefaultTabulator() );
                    pOutl->SetStyleSheetPool((SfxStyleSheetPool*) pDoc->GetStyleSheetPool());
                    pStyle = pSummaryPage->GetStyleSheetForPresObj( PRESOBJ_OUTLINE );
                    pOutl->SetStyleSheet( 0, pStyle );
                    pOutl->SetMinDepth(0);
                }

                /**************************************************************
                * Text hinzufuegen
                **************************************************************/
                OutlinerParaObject* pParaObj = pTextObj->GetOutlinerParaObject();
                pParaObj->SetOutlinerMode( OUTLINERMODE_OUTLINEOBJECT );
                pOutl->AddText(*pParaObj);
            }
        }
    }

    if (pSummaryPage)
    {
        SdrTextObj* pTextObj = (SdrTextObj*) pSummaryPage->GetPresObj(PRESOBJ_OUTLINE);

        // Harte Absatz- und Zeichenattribute entfernen
        SfxItemSet aEmptyEEAttr(pDoc->GetPool(), EE_ITEMS_START, EE_ITEMS_END);
        ULONG nParaCount = pOutl->GetParagraphCount();

        for (USHORT nPara = 0; nPara < nParaCount; nPara++)
        {
            pOutl->SetStyleSheet( nPara, pStyle );
            pOutl->QuickRemoveCharAttribs(nPara);
            pOutl->SetParaAttribs(nPara, aEmptyEEAttr);
            pOutl->SetDepth(pOutl->GetParagraph(nPara), 1);
        }

        pTextObj->SetOutlinerParaObject( pOutl->CreateParaObject() );
        pTextObj->SetEmptyPresObj(FALSE);

        // Harte Attribute entfernen (Flag auf TRUE)
        SfxItemSet aAttr(pDoc->GetPool());
        aAttr.Put(XLineStyleItem(XLINE_NONE));
        aAttr.Put(XFillStyleItem(XFILL_NONE));
        pTextObj->SetMergedItemSet(aAttr);

        pView->EndUndo();
        delete pOutl;

        DrawViewShell* pDrawViewShell= dynamic_cast< DrawViewShell* >( pViewShell );
        if(pDrawViewShell)
        {
            pDrawViewShell->SwitchPage( (pSummaryPage->GetPageNum() - 1) / 2);
        }
    }
}

} // end of namespace sd
<commit_msg>INTEGRATION: CWS sdwarningsbegone (1.10.38); FILE MERGED 2006/11/22 12:41:56 cl 1.10.38.1: #i69285# warning free code changes for unxlngi6.pro<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fusumry.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: kz $ $Date: 2006-12-12 17:24:47 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"

#include "fusumry.hxx"

#ifndef _EEITEM_HXX //autogen
#include <svx/eeitem.hxx>
#endif
#ifndef _SVDOTEXT_HXX //autogen
#include <svx/svdotext.hxx>
#endif
#ifndef _SVDUNDO_HXX //autogen
#include <svx/svdundo.hxx>
#endif
#ifndef _SFX_PRINTER_HXX //autogen
#include <sfx2/printer.hxx>
#endif
#ifndef _OUTLOBJ_HXX
#include <svx/outlobj.hxx>
#endif

#include "strings.hrc"

#include "pres.hxx"
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#include "sdpage.hxx"
#ifndef SD_OUTLINER_HXX
#include "Outliner.hxx"
#endif
#ifndef SD_DRAW_VIEW_HXX
#include "drawview.hxx"
#endif
#include "drawdoc.hxx"
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#include "DrawDocShell.hxx"
#include "sdresid.hxx"
#include "optsitem.hxx"
#ifndef SD_DRAW_VIEW_SHELL_HXX
#include "DrawViewShell.hxx"
#endif

namespace sd {

TYPEINIT1( FuSummaryPage, FuPoor );

/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
FuSummaryPage::FuSummaryPage (
    ViewShell* pViewSh,
    ::sd::Window* pWin,
    ::sd::View* pView,
    SdDrawDocument* pDoc,
    SfxRequest& rReq)
    : FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
}

FunctionReference FuSummaryPage::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )
{
    FunctionReference xFunc( new FuSummaryPage( pViewSh, pWin, pView, pDoc, rReq ) );
    xFunc->DoExecute(rReq);
    return xFunc;
}

void FuSummaryPage::DoExecute( SfxRequest& )
{
    ::sd::Outliner* pOutl = NULL;
    SdPage* pSummaryPage = NULL;
    USHORT i = 0;
    USHORT nFirstPage = SDRPAGE_NOTFOUND;
    USHORT nSelectedPages = 0;
    USHORT nCount = mpDoc->GetSdPageCount(PK_STANDARD);

    while (i < nCount && nSelectedPages <= 1)
    {
        /**********************************************************************
        * Wieviele Seiten sind selektiert?
        * Genau eine Seite selektiert: Ab dieser Seite alles zusammenfassen
        * sonst: Nur die selektierten Seiten zusammenfassen
        **********************************************************************/
        SdPage* pActualPage = mpDoc->GetSdPage(i, PK_STANDARD);

        if (pActualPage->IsSelected())
        {
            if (nFirstPage == SDRPAGE_NOTFOUND)
            {
                nFirstPage = i;
            }

            nSelectedPages++;
        }

        i++;
    }

    SfxStyleSheet* pStyle = NULL;

    for (i = nFirstPage; i < nCount; i++)
    {
        SdPage* pActualPage = mpDoc->GetSdPage(i, PK_STANDARD);

        if (nSelectedPages <= 1 || pActualPage->IsSelected())
        {
            SdPage* pActualNotesPage = mpDoc->GetSdPage(i, PK_NOTES);
            SdrTextObj* pTextObj = (SdrTextObj*) pActualPage->GetPresObj(PRESOBJ_TITLE);

            if (pTextObj && !pTextObj->IsEmptyPresObj())
            {
                if (!pSummaryPage)
                {
                    /**********************************************************
                    * Inhaltsverzeichnis-Seite einfuegen und Outliner anlegen
                    **********************************************************/
                    mpView->BegUndo(String(SdResId(STR_UNDO_SUMMARY_PAGE)));
                    SetOfByte aVisibleLayers = pActualPage->TRG_GetMasterPageVisibleLayers();

                    // Seite mit Titel & Gliederung!
                    pSummaryPage = (SdPage*) mpDoc->AllocPage(FALSE);
                    pSummaryPage->SetSize(pActualPage->GetSize() );
                    pSummaryPage->SetBorder(pActualPage->GetLftBorder(),
                                     pActualPage->GetUppBorder(),
                                     pActualPage->GetRgtBorder(),
                                     pActualPage->GetLwrBorder() );

                    // Seite hinten einfuegen
                    mpDoc->InsertPage(pSummaryPage, nCount * 2 + 1);
                    mpView->AddUndo(mpDoc->GetSdrUndoFactory().CreateUndoNewPage(*pSummaryPage));

                    // MasterPage der aktuellen Seite verwenden
                    pSummaryPage->TRG_SetMasterPage(pActualPage->TRG_GetMasterPage());
                    pSummaryPage->SetLayoutName(pActualPage->GetLayoutName());
                    pSummaryPage->SetAutoLayout(AUTOLAYOUT_ENUM, TRUE);
                    pSummaryPage->TRG_SetMasterPageVisibleLayers(aVisibleLayers);
                    pSummaryPage->setHeaderFooterSettings(pActualPage->getHeaderFooterSettings());

                    // Notiz-Seite
                    SdPage* pNotesPage = (SdPage*) mpDoc->AllocPage(FALSE);
                    pNotesPage->SetSize(pActualNotesPage->GetSize());
                    pNotesPage->SetBorder(pActualNotesPage->GetLftBorder(),
                                          pActualNotesPage->GetUppBorder(),
                                          pActualNotesPage->GetRgtBorder(),
                                          pActualNotesPage->GetLwrBorder() );
                    pNotesPage->SetPageKind(PK_NOTES);

                    // Seite hinten einfuegen
                    mpDoc->InsertPage(pNotesPage, nCount * 2 + 2);
                    mpView->AddUndo(mpDoc->GetSdrUndoFactory().CreateUndoNewPage(*pNotesPage));

                    // MasterPage der aktuellen Seite verwenden
                    pNotesPage->TRG_SetMasterPage(pActualNotesPage->TRG_GetMasterPage());
                    pNotesPage->SetLayoutName(pActualNotesPage->GetLayoutName());
                    pNotesPage->SetAutoLayout(pActualNotesPage->GetAutoLayout(), TRUE);
                    pNotesPage->TRG_SetMasterPageVisibleLayers(aVisibleLayers);
                    pNotesPage->setHeaderFooterSettings(pActualNotesPage->getHeaderFooterSettings());

                    pOutl = new ::sd::Outliner( mpDoc, OUTLINERMODE_OUTLINEOBJECT );
                    pOutl->SetUpdateMode(FALSE);
                    pOutl->EnableUndo(FALSE);

                    if (mpDocSh)
                        pOutl->SetRefDevice(SD_MOD()->GetRefDevice( *mpDocSh ));

                    pOutl->SetDefTab( mpDoc->GetDefaultTabulator() );
                    pOutl->SetStyleSheetPool((SfxStyleSheetPool*) mpDoc->GetStyleSheetPool());
                    pStyle = pSummaryPage->GetStyleSheetForPresObj( PRESOBJ_OUTLINE );
                    pOutl->SetStyleSheet( 0, pStyle );
                    pOutl->SetMinDepth(0);
                }

                /**************************************************************
                * Text hinzufuegen
                **************************************************************/
                OutlinerParaObject* pParaObj = pTextObj->GetOutlinerParaObject();
                pParaObj->SetOutlinerMode( OUTLINERMODE_OUTLINEOBJECT );
                pOutl->AddText(*pParaObj);
            }
        }
    }

    if (pSummaryPage)
    {
        SdrTextObj* pTextObj = (SdrTextObj*) pSummaryPage->GetPresObj(PRESOBJ_OUTLINE);

        // Harte Absatz- und Zeichenattribute entfernen
        SfxItemSet aEmptyEEAttr(mpDoc->GetPool(), EE_ITEMS_START, EE_ITEMS_END);
        ULONG nParaCount = pOutl->GetParagraphCount();

        for (USHORT nPara = 0; nPara < nParaCount; nPara++)
        {
            pOutl->SetStyleSheet( nPara, pStyle );
            pOutl->QuickRemoveCharAttribs(nPara);
            pOutl->SetParaAttribs(nPara, aEmptyEEAttr);
            pOutl->SetDepth(pOutl->GetParagraph(nPara), 1);
        }

        pTextObj->SetOutlinerParaObject( pOutl->CreateParaObject() );
        pTextObj->SetEmptyPresObj(FALSE);

        // Harte Attribute entfernen (Flag auf TRUE)
        SfxItemSet aAttr(mpDoc->GetPool());
        aAttr.Put(XLineStyleItem(XLINE_NONE));
        aAttr.Put(XFillStyleItem(XFILL_NONE));
        pTextObj->SetMergedItemSet(aAttr);

        mpView->EndUndo();
        delete pOutl;

        DrawViewShell* pDrawViewShell= dynamic_cast< DrawViewShell* >( mpViewShell );
        if(pDrawViewShell)
        {
            pDrawViewShell->SwitchPage( (pSummaryPage->GetPageNum() - 1) / 2);
        }
    }
}

} // end of namespace sd
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fuhhconv.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-12-14 17:11:58 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SD_FUHHCONV_HXX
#define _SD_FUHHCONV_HXX

#ifndef _SD_FUPOOR_HXX
#include "fupoor.hxx"
#endif

namespace sd {

class Outliner;

class FuHangulHanjaConversion : public FuPoor
{
 public:
    TYPEINFO();

    static FunctionReference Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq );

    void StartConversion( INT16 nSourceLanguage,  INT16 nTargetLanguage,
                          const Font *pTargetFont, INT32 nOptions, BOOL bIsInteractive );

    void StartChineseConversion();

    void ConvertStyles( INT16 nTargetLanguage, const Font *pTargetFont );

    Outliner* GetOutliner() const { return pSdOutliner; }

 protected:
    ~FuHangulHanjaConversion();

    Outliner*   pSdOutliner;
    BOOL            bOwnOutliner;

private:
    FuHangulHanjaConversion (
        ViewShell* pViewSh,
        ::sd::Window* pWin,
        ::sd::View* pView,
        SdDrawDocument* pDoc,
        SfxRequest& rReq );

};

#endif // _SD_FUHHCONV_HXX

} // end of namespace sd
<commit_msg>INTEGRATION: CWS changefileheader (1.6.556); FILE MERGED 2008/03/31 13:58:14 rt 1.6.556.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: fuhhconv.hxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _SD_FUHHCONV_HXX
#define _SD_FUHHCONV_HXX

#ifndef _SD_FUPOOR_HXX
#include "fupoor.hxx"
#endif

namespace sd {

class Outliner;

class FuHangulHanjaConversion : public FuPoor
{
 public:
    TYPEINFO();

    static FunctionReference Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq );

    void StartConversion( INT16 nSourceLanguage,  INT16 nTargetLanguage,
                          const Font *pTargetFont, INT32 nOptions, BOOL bIsInteractive );

    void StartChineseConversion();

    void ConvertStyles( INT16 nTargetLanguage, const Font *pTargetFont );

    Outliner* GetOutliner() const { return pSdOutliner; }

 protected:
    ~FuHangulHanjaConversion();

    Outliner*   pSdOutliner;
    BOOL            bOwnOutliner;

private:
    FuHangulHanjaConversion (
        ViewShell* pViewSh,
        ::sd::Window* pWin,
        ::sd::View* pView,
        SdDrawDocument* pDoc,
        SfxRequest& rReq );

};

#endif // _SD_FUHHCONV_HXX

} // end of namespace sd
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: fuparagr.hxx,v $
 *
 *  $Revision: 1.1.1.1 $
 *
 *  last change: $Author: hr $ $Date: 2000-09-18 16:48:39 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SD_FUPARAGR_HXX
#define _SD_FUPARAGR_HXX

#ifndef _SD_FUPOOR_HXX
#include "fupoor.hxx"
#endif

class FuParagraph : public FuPoor
{
 public:
    TYPEINFO();

    FuParagraph( SdViewShell* pViewSh, SdWindow* pWin, SdView* pView,
                 SdDrawDocument* pDoc, SfxRequest& rReq);
    ~FuParagraph() {}

    virtual void Activate() {}         // Function aktivieren
    virtual void Deactivate() {}           // Function deaktivieren
};

#endif // _SD_FUPARAGR_HXX

<commit_msg>INTEGRATION: CWS impress1 (1.1.1.1.262); FILE MERGED 2003/09/16 13:36:03 af 1.1.1.1.262.1: #111996# Introduction of namespace sd. Use of sub-shells.<commit_after>/*************************************************************************
 *
 *  $RCSfile: fuparagr.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: obo $ $Date: 2004-01-20 12:08:07 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef SD_FU_PARAGRAPH_HXX
#define SD_FU_PARAGRAPH_HXX

#ifndef SD_FU_POOR_HXX
#include "fupoor.hxx"
#endif

namespace sd {

class FuParagraph
    : public FuPoor
{
public:
    TYPEINFO();

    FuParagraph (
        ViewShell* pViewSh,
        ::sd::Window* pWin,
        ::sd::View* pView,
        SdDrawDocument* pDoc,
        SfxRequest& rReq);
    virtual ~FuParagraph (void) {}

    virtual void Activate() {}         // Function aktivieren
    virtual void Deactivate() {}           // Function deaktivieren
};

} // end of namespace

#endif

<|endoftext|>


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

#include "brw_shader.h"
#include "brw_nir.h"
#include "compiler/glsl/ir_uniform.h"

static void
brw_nir_setup_glsl_builtin_uniform(nir_variable *var,
                                   const struct gl_program *prog,
                                   struct brw_stage_prog_data *stage_prog_data,
                                   bool is_scalar)
{
   const nir_state_slot *const slots = var->state_slots;
   assert(var->state_slots != NULL);

   unsigned uniform_index = var->data.driver_location / 4;
   for (unsigned int i = 0; i < var->num_state_slots; i++) {
      /* This state reference has already been setup by ir_to_mesa, but we'll
       * get the same index back here.
       */
      int index = _mesa_add_state_reference(prog->Parameters,
					    (gl_state_index *)slots[i].tokens);

      /* Add each of the unique swizzles of the element as a parameter.
       * This'll end up matching the expected layout of the
       * array/matrix/structure we're trying to fill in.
       */
      int last_swiz = -1;
      for (unsigned j = 0; j < 4; j++) {
         int swiz = GET_SWZ(slots[i].swizzle, j);

         /* If we hit a pair of identical swizzles, this means we've hit the
          * end of the builtin variable.  In scalar mode, we should just quit
          * and move on to the next one.  In vec4, we need to continue and pad
          * it out to 4 components.
          */
         if (swiz == last_swiz && is_scalar)
            break;

         last_swiz = swiz;

         stage_prog_data->param[uniform_index++] =
            &prog->Parameters->ParameterValues[index][swiz];
      }
   }
}

static void
brw_nir_setup_glsl_uniform(gl_shader_stage stage, nir_variable *var,
                           struct gl_shader_program *shader_prog,
                           struct brw_stage_prog_data *stage_prog_data,
                           bool is_scalar)
{
   int namelen = strlen(var->name);

   /* The data for our (non-builtin) uniforms is stored in a series of
    * gl_uniform_driver_storage structs for each subcomponent that
    * glGetUniformLocation() could name.  We know it's been set up in the same
    * order we'd walk the type, so walk the list of storage and find anything
    * with our name, or the prefix of a component that starts with our name.
    */
   unsigned uniform_index = var->data.driver_location / 4;
   for (unsigned u = 0; u < shader_prog->NumUniformStorage; u++) {
      struct gl_uniform_storage *storage = &shader_prog->UniformStorage[u];

      if (storage->builtin)
         continue;

      if (strncmp(var->name, storage->name, namelen) != 0 ||
          (storage->name[namelen] != 0 &&
           storage->name[namelen] != '.' &&
           storage->name[namelen] != '[')) {
         continue;
      }

      if (storage->type->is_image()) {
         brw_setup_image_uniform_values(stage, stage_prog_data,
                                        uniform_index, storage);
         uniform_index +=
            BRW_IMAGE_PARAM_SIZE * MAX2(storage->array_elements, 1);
      } else {
         gl_constant_value *components = storage->storage;
         unsigned vector_count = (MAX2(storage->array_elements, 1) *
                                  storage->type->matrix_columns);
         unsigned vector_size = storage->type->vector_elements;

         for (unsigned s = 0; s < vector_count; s++) {
            unsigned i;
            for (i = 0; i < vector_size; i++) {
               stage_prog_data->param[uniform_index++] = components++;
            }

            if (!is_scalar) {
               /* Pad out with zeros if needed (only needed for vec4) */
               for (; i < 4; i++) {
                  static const gl_constant_value zero = { 0.0 };
                  stage_prog_data->param[uniform_index++] = &zero;
               }
            }
         }
      }
   }
}

void
brw_nir_setup_glsl_uniforms(nir_shader *shader,
                            struct gl_shader_program *shader_prog,
                            const struct gl_program *prog,
                            struct brw_stage_prog_data *stage_prog_data,
                            bool is_scalar)
{
   nir_foreach_variable(var, &shader->uniforms) {
      /* UBO's, atomics and samplers don't take up space in the
         uniform file */
      if (var->interface_type != NULL || var->type->contains_atomic())
         continue;

      if (strncmp(var->name, "gl_", 3) == 0) {
         brw_nir_setup_glsl_builtin_uniform(var, prog, stage_prog_data,
                                            is_scalar);
      } else {
         brw_nir_setup_glsl_uniform(shader->stage, var, shader_prog,
                                    stage_prog_data, is_scalar);
      }
   }
}

void
brw_nir_setup_arb_uniforms(nir_shader *shader, struct gl_program *prog,
                           struct brw_stage_prog_data *stage_prog_data)
{
   struct gl_program_parameter_list *plist = prog->Parameters;

#ifndef NDEBUG
   if (!shader->uniforms.is_empty()) {
      /* For ARB programs, only a single "parameters" variable is generated to
       * support uniform data.
       */
      assert(shader->uniforms.length() == 1);
      nir_variable *var = (nir_variable *) shader->uniforms.get_head();
      assert(strcmp(var->name, "parameters") == 0);
      assert(var->type->array_size() == (int)plist->NumParameters);
   }
#endif

   for (unsigned p = 0; p < plist->NumParameters; p++) {
      /* Parameters should be either vec4 uniforms or single component
       * constants; matrices and other larger types should have been broken
       * down earlier.
       */
      assert(plist->Parameters[p].Size <= 4);

      unsigned i;
      for (i = 0; i < plist->Parameters[p].Size; i++) {
         stage_prog_data->param[4 * p + i] = &plist->ParameterValues[p][i];
      }
      for (; i < 4; i++) {
         static const gl_constant_value zero = { 0.0 };
         stage_prog_data->param[4 * p + i] = &zero;
      }
   }
}
<commit_msg>i965: fix struct type in comment<commit_after>/*
 * Copyright © 2015 Intel Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

#include "brw_shader.h"
#include "brw_nir.h"
#include "compiler/glsl/ir_uniform.h"

static void
brw_nir_setup_glsl_builtin_uniform(nir_variable *var,
                                   const struct gl_program *prog,
                                   struct brw_stage_prog_data *stage_prog_data,
                                   bool is_scalar)
{
   const nir_state_slot *const slots = var->state_slots;
   assert(var->state_slots != NULL);

   unsigned uniform_index = var->data.driver_location / 4;
   for (unsigned int i = 0; i < var->num_state_slots; i++) {
      /* This state reference has already been setup by ir_to_mesa, but we'll
       * get the same index back here.
       */
      int index = _mesa_add_state_reference(prog->Parameters,
					    (gl_state_index *)slots[i].tokens);

      /* Add each of the unique swizzles of the element as a parameter.
       * This'll end up matching the expected layout of the
       * array/matrix/structure we're trying to fill in.
       */
      int last_swiz = -1;
      for (unsigned j = 0; j < 4; j++) {
         int swiz = GET_SWZ(slots[i].swizzle, j);

         /* If we hit a pair of identical swizzles, this means we've hit the
          * end of the builtin variable.  In scalar mode, we should just quit
          * and move on to the next one.  In vec4, we need to continue and pad
          * it out to 4 components.
          */
         if (swiz == last_swiz && is_scalar)
            break;

         last_swiz = swiz;

         stage_prog_data->param[uniform_index++] =
            &prog->Parameters->ParameterValues[index][swiz];
      }
   }
}

static void
brw_nir_setup_glsl_uniform(gl_shader_stage stage, nir_variable *var,
                           struct gl_shader_program *shader_prog,
                           struct brw_stage_prog_data *stage_prog_data,
                           bool is_scalar)
{
   int namelen = strlen(var->name);

   /* The data for our (non-builtin) uniforms is stored in a series of
    * gl_uniform_storage structs for each subcomponent that
    * glGetUniformLocation() could name.  We know it's been set up in the same
    * order we'd walk the type, so walk the list of storage and find anything
    * with our name, or the prefix of a component that starts with our name.
    */
   unsigned uniform_index = var->data.driver_location / 4;
   for (unsigned u = 0; u < shader_prog->NumUniformStorage; u++) {
      struct gl_uniform_storage *storage = &shader_prog->UniformStorage[u];

      if (storage->builtin)
         continue;

      if (strncmp(var->name, storage->name, namelen) != 0 ||
          (storage->name[namelen] != 0 &&
           storage->name[namelen] != '.' &&
           storage->name[namelen] != '[')) {
         continue;
      }

      if (storage->type->is_image()) {
         brw_setup_image_uniform_values(stage, stage_prog_data,
                                        uniform_index, storage);
         uniform_index +=
            BRW_IMAGE_PARAM_SIZE * MAX2(storage->array_elements, 1);
      } else {
         gl_constant_value *components = storage->storage;
         unsigned vector_count = (MAX2(storage->array_elements, 1) *
                                  storage->type->matrix_columns);
         unsigned vector_size = storage->type->vector_elements;

         for (unsigned s = 0; s < vector_count; s++) {
            unsigned i;
            for (i = 0; i < vector_size; i++) {
               stage_prog_data->param[uniform_index++] = components++;
            }

            if (!is_scalar) {
               /* Pad out with zeros if needed (only needed for vec4) */
               for (; i < 4; i++) {
                  static const gl_constant_value zero = { 0.0 };
                  stage_prog_data->param[uniform_index++] = &zero;
               }
            }
         }
      }
   }
}

void
brw_nir_setup_glsl_uniforms(nir_shader *shader,
                            struct gl_shader_program *shader_prog,
                            const struct gl_program *prog,
                            struct brw_stage_prog_data *stage_prog_data,
                            bool is_scalar)
{
   nir_foreach_variable(var, &shader->uniforms) {
      /* UBO's, atomics and samplers don't take up space in the
         uniform file */
      if (var->interface_type != NULL || var->type->contains_atomic())
         continue;

      if (strncmp(var->name, "gl_", 3) == 0) {
         brw_nir_setup_glsl_builtin_uniform(var, prog, stage_prog_data,
                                            is_scalar);
      } else {
         brw_nir_setup_glsl_uniform(shader->stage, var, shader_prog,
                                    stage_prog_data, is_scalar);
      }
   }
}

void
brw_nir_setup_arb_uniforms(nir_shader *shader, struct gl_program *prog,
                           struct brw_stage_prog_data *stage_prog_data)
{
   struct gl_program_parameter_list *plist = prog->Parameters;

#ifndef NDEBUG
   if (!shader->uniforms.is_empty()) {
      /* For ARB programs, only a single "parameters" variable is generated to
       * support uniform data.
       */
      assert(shader->uniforms.length() == 1);
      nir_variable *var = (nir_variable *) shader->uniforms.get_head();
      assert(strcmp(var->name, "parameters") == 0);
      assert(var->type->array_size() == (int)plist->NumParameters);
   }
#endif

   for (unsigned p = 0; p < plist->NumParameters; p++) {
      /* Parameters should be either vec4 uniforms or single component
       * constants; matrices and other larger types should have been broken
       * down earlier.
       */
      assert(plist->Parameters[p].Size <= 4);

      unsigned i;
      for (i = 0; i < plist->Parameters[p].Size; i++) {
         stage_prog_data->param[4 * p + i] = &plist->ParameterValues[p][i];
      }
      for (; i < 4; i++) {
         static const gl_constant_value zero = { 0.0 };
         stage_prog_data->param[4 * p + i] = &zero;
      }
   }
}
<|endoftext|>