<commit_before>
#include "stdafx.h"
#include "dialog.h"
#include <fstream>
#include <gamesystems/gamesystems.h>
#include "gamesystems/timeevents.h"
#include "infrastructure/vfs.h"
DialogScripts dialogScripts;

static struct DialogScriptsAddresses : temple::AddressTable {

	bool (__cdecl *GetFilename)(int scriptId, char *filename);

	bool (__cdecl *LoadScript)(const char *filename, int &handleOut);

	void (__cdecl *LoadNpcLine)(DialogState &state, bool force);

	void (__cdecl *FreeScript)(int handle);

	DialogScriptsAddresses() {
		rebase(GetFilename, 0x1007E270);
		rebase(LoadScript, 0x10036600);
		rebase(LoadNpcLine, 0x10038590);
		rebase(FreeScript, 0x100346F0);
	}
} addresses;

class DialogHooks : public TempleFix
{
public:

	void apply() override {

		static BOOL (__cdecl*orgLoadDialogFile)(char*, int*) =
			replaceFunction<BOOL(__cdecl)(char*, int*)>(0x10036600, [](char* filename, int* dlgFileHandle){
			return dialogScripts.Load(filename, *dlgFileHandle)?TRUE:FALSE;
			//return orgLoadDialogFile(filename, dlgFileHandle);
		});

	}
} dialogHooks;

bool DialogLine::IsPcLine(){
	return this->minIq != 0;
}

bool DialogLine::IsNpcLine(){
	return !IsPcLine();
}

DialogLine &DialogLine::operator=(DialogLineNew &src){
	auto &dest = *this;

	dest.minIq = src.minIq;
	dest.answerLineId = src.answerLineId;
	dest.key = src.key;
	dest.txt = _strdup(src.txt.c_str());

	// copy testField if not blank
	auto testFieldOk = false;
	for (auto i = 0u; i < src.testField.size(); i++) {
		if (!isspace(src.testField[i])) {
			testFieldOk = true;
			break;
		}
	}
	dest.testField = testFieldOk ? _strdup(src.testField.c_str()) : nullptr;

	// copy effectfield if not blank
	auto effectFieldOk = false;
	for (auto i = 0u; i < src.effectField.size(); i++) {
		if (!isspace(src.effectField[i])) {
			effectFieldOk = true;
			break;
		}
	}
	dest.effectField = effectFieldOk ? _strdup(src.effectField.c_str()) : nullptr;

	if (src.IsNpcLine())
		dest.genderField = _strdup(src.genderField.c_str());
	else
		dest.genderField = (char*)-1;

	return dest;
}

string DialogScripts::GetFilename(int scriptId) {
	char filename[MAX_PATH];
	if (addresses.GetFilename(scriptId, filename)) {
		return filename;
	} else {
		return string();
	}
}

bool DialogScripts::Load(const string& filename, int& dlgHandle) {
	DialogFile *&mFileEntries = temple::GetRef<DialogFile*>(0x108ED0CC);
	int &mFileEntryCount = temple::GetRef<int>(0x108ED0C4);

	if (GetFileEntryByFilename(filename, dlgHandle)){
		auto &entry = mFileEntries[dlgHandle];
		entry.refCount++;
		entry.lastTimeLoaded = gameSystems->GetTimeEvent().GetTime();
		return true;
	}

	DialogFile newEntry;
	strcpy(newEntry.filename, filename.c_str());
	newEntry.refCount = 1;
	newEntry.lineCapacity = newEntry.lineCount = 0;
	newEntry.lastTimeLoaded = gameSystems->GetTimeEvent().GetTime();
	newEntry.lines = nullptr;
	newEntry.unk11C = 0;

	newEntry.GetLinesFromFile();
	if (newEntry.lineCount ==0)
		return false;

	memcpy(&mFileEntries[dlgHandle], &newEntry, sizeof DialogFile);
	mFileEntryCount++;

	return true;
	//return addresses.LoadScript(filename.c_str(), dlgHandle);
}

void DialogScripts::LoadNpcLine(DialogState& state, bool force) {
	addresses.LoadNpcLine(state, force);
}

void DialogScripts::Free(int dlgHandle) {
	addresses.FreeScript(dlgHandle);
}

DialogFile* DialogScripts::GetDialogFileEntry(int dlgHandle){
	DialogFile *&mFileEntries = temple::GetRef<DialogFile*>(0x108ED0CC);
	int &mFileEntryCount = temple::GetRef<int>(0x108ED0C4);

	if (dlgHandle >= mFileEntryCount || dlgHandle < 0)
		return nullptr;
	return &mFileEntries[dlgHandle];
}

ostream & operator<<(ostream & result, DialogLine &line){
	/*
	{1}{NPC txt}{Gender}{     }{speechId }{        }{}
	{2}{PC txt }{      }{minIq}{testField}{answerId}{effectField}
	*/
	if (line.IsPcLine()) {
		result << "{" << line.key << "}";
		if (line.txt)
			result << "{" << line.txt << "}";
		else
			result << "{}";
		result << "{}"; // blank gender field

		result << "{" << line.minIq << "}";
		if (line.testField)
			result << "{" << line.testField << "}";
		else
			result << "{}";
		result << "{" << line.answerLineId << "}";

		if (line.effectField)
			result << "{" << line.effectField << "}";
		else
			result << "{}";

		//result = fmt::format("\{{}\}\{{}\}\{\}\{{}\}\{{}\}\{{}\}\{{}\}",
		//	line.key, line.txt, line.minIq, line.testField, line.answerLineId, line.effectField );
	}
	else {

		result << "{" << line.key << "}";
		if (line.txt)
			result << "{" << line.txt << "}";
		else
			result << "{}";

		if (line.genderField)
			result << "{" << line.genderField << "}";
		else
			result << "{}";

		result << "{}";
		result << "{}";
		result << "{}";

		if (line.effectField)
			result << "{" << line.effectField << "}";
		else
			result << "{}";

		//result = fmt::format("\{{}\}\{{}\}\{{}\}\{\}\{\}\{\}\{\}",
		//	line.key, line.txt, line.genderField, line.effectField);
	}
	return result;
}

void DialogScripts::SaveToFile(int dlgHandle){
	auto fileEntry = GetDialogFileEntry(dlgHandle);
	if (!fileEntry)
		return;

	std::string newFileName(fmt::format("", fileEntry->filename));
	//auto newFile = fopen("shit.mes", "wb");
	ofstream newFile("shit.mes");

	for (auto i=0; i < fileEntry->lineCount; i++){
		auto line = fileEntry->lines[i];

		if (i && line.IsNpcLine() && line.key < 10000) {
			newFile << std::endl;
			if (!(line.key % 10))
				newFile << std::endl;
		}
		newFile << line << std::endl;
	}
}

bool DialogScripts::GetFileEntryByFilename(const std::string & filename, int &dlgHandleOut){

	DialogFile *&mFileEntries = temple::GetRef<DialogFile*>(0x108ED0CC);
	int &mFileEntryCapacity = temple::GetRef<int>(0x108ED0C8);

	auto oldestFreeHandle = -1;

	for (auto i=0; i < mFileEntryCapacity; i++){

		auto &entry = mFileEntries[i];

		if (!_stricmp(filename.c_str(), entry.filename)){
			dlgHandleOut = i;
			return true;
		}
		if (!entry.refCount){
			if (oldestFreeHandle == -1){
				oldestFreeHandle = i;
			}
			else{
				auto &lastEntry = mFileEntries[oldestFreeHandle];
				if (lastEntry.filename[0]
				&& (!entry.filename[0])
					|| GameTime::Compare(lastEntry.lastTimeLoaded,
						entry.lastTimeLoaded) > 0){
					oldestFreeHandle = i;
			    }

			}
		}
	}

	if (oldestFreeHandle != -1){
		dlgHandleOut = oldestFreeHandle;
		if (mFileEntries[oldestFreeHandle].filename[0])
			Free(oldestFreeHandle);
		return false;
	}

	auto prevCount = mFileEntryCapacity;
	dlgHandleOut = prevCount;
	// allocate 10 more entries
	mFileEntryCapacity += 10;
	mFileEntries = (DialogFile*)realloc(mFileEntries, mFileEntryCapacity * sizeof DialogFile);
	for (auto i=prevCount; i < mFileEntryCapacity; i++){
		auto &entry = mFileEntries[i];
		entry.filename[0] = 0;
		entry.refCount = 0;
	}
	return false;
}

struct DlgParser {
	stringstream ss;
	string lineBuf; // buffer for storing a line's content

	stringstream bracketStream;
	string bracketContent;

	bool GetSingleLine(DialogLineNew &line, int&fileLine);
	bool GetBracketContent(int &fileLine);

	DlgParser(string & fileContents):ss(fileContents){};
};

bool DlgParser::GetSingleLine(DialogLineNew& line, int& fileLine){
	// parse buf for bracket stuff until a line is complete
	if (!GetBracketContent(fileLine))
		return false;
	line.key = atol(bracketContent.c_str());

	if (!GetBracketContent(fileLine)){
		logger->error("Missing text on line: {} (dialog line {})", line.key, fileLine);
		return false;
	}
	line.txt = bracketContent;

	if (!GetBracketContent(fileLine)) {
		logger->error("Missing gender field on line: {} (dialog line {})", line.key, fileLine);
		return false;
	}
	line.genderField = bracketContent;

	if (!GetBracketContent(fileLine)) {
		logger->error("Missing minimum IQ value on line: {} (dialog line {})", line.key, fileLine);
		return false;
	}
	auto minIq = atol(bracketContent.c_str());
	if (!minIq && bracketContent.size()) {
		logger->error("Invalid minimum IQ value on line: {} (dialog line {}). Must be blank (for an NPC) or non-zero (for a PC)", line.key, fileLine);
		return false;
	}
	line.minIq = minIq;

	if (!GetBracketContent(fileLine)) {
		logger->error("Missing test field on line: {} (dialog line {})", line.key, fileLine);
		return false;
	}
	line.testField = bracketContent;

	if (!GetBracketContent(fileLine)) {
		logger->error("Missing response value on line: {} (dialog line {})", line.key, fileLine);
		return false;
	}
	if (bracketContent[0] == '#'){
		logger->error("Saw a # in a response value on line: {} (dialog line {})", line.key, fileLine);
		return 0;
	}
	line.answerLineId = atol(bracketContent.c_str());

	if (!GetBracketContent(fileLine)) {
		logger->error("Missing effect field on line: {} (dialog line {})", line.key, fileLine);
		return false;
	}
	line.effectField = bracketContent;

	// todo check non-blank gender field for NPC lines
	return true;
}

bool DlgParser::GetBracketContent(int &fileLine){
	string brBuf;
	const int MAX_TEXT_SIZE = 1000;

	getline(ss, brBuf, '{');
	if (ss.eof()) { // no new brackets found
		return false;
	}

	// count how many newlines
	for (auto nl = strchr(brBuf.c_str(), '\n'); nl; fileLine++) {
		nl = strchr(nl + 1, '\n');
	}

	// get bracket content
	getline(ss, brBuf, '}');
	if (ss.eof()) {
		logger->error("Unclosed bracket found! Line {}", fileLine);
		return false;
	}
	if (ss.gcount() >= MAX_TEXT_SIZE){
		logger->error("String too long on line: {} (max is {})", fileLine, MAX_TEXT_SIZE);
		return false;
	}
	// count how many newlines inside bracket
	for (auto nl = strchr(brBuf.c_str(), '\n'); nl; fileLine++) {
		nl = strchr(nl + 1, '\n');
	}

	bracketContent = brBuf;
	return true;
}

void DialogFile::GetLinesFromFile()
{
	if (!vfs->FileExists(this->filename))
		return;

	auto fileContents = vfs->ReadAsString(this->filename);
	DlgParser dlgParser(fileContents);

	int fileLine = 1;
	DialogLineNew lineTmp;
	while (dlgParser.GetSingleLine(lineTmp, fileLine)){

		if (this->lineCount == this->lineCapacity){
			this->lineCapacity += 10;
			this->lines = (DialogLine*)realloc(lines, lineCapacity * sizeof DialogLine);
		}
		this->lines[lineCount++] = lineTmp;

	}

	std::sort(this->lines, &this->lines[lineCount-1], [](DialogLine &a, DialogLine &b)->bool{
		return a.key < b.key;
	});
}

bool DialogLineNew::IsPcLine() {
	return minIq != 0;
}

bool DialogLineNew::IsNpcLine(){
	return !IsPcLine();
}
<commit_msg>More minor dlg stuff<commit_after>
#include "stdafx.h"
#include "dialog.h"
#include <fstream>
#include <gamesystems/gamesystems.h>
#include "gamesystems/timeevents.h"
#include "infrastructure/vfs.h"
DialogScripts dialogScripts;

static struct DialogScriptsAddresses : temple::AddressTable {

	bool (__cdecl *GetFilename)(int scriptId, char *filename);

	bool (__cdecl *LoadScript)(const char *filename, int &handleOut);

	void (__cdecl *LoadNpcLine)(DialogState &state, bool force);

	void (__cdecl *FreeScript)(int handle);

	DialogScriptsAddresses() {
		rebase(GetFilename, 0x1007E270);
		rebase(LoadScript, 0x10036600);
		rebase(LoadNpcLine, 0x10038590);
		rebase(FreeScript, 0x100346F0);
	}
} addresses;

class DialogHooks : public TempleFix
{
public:

	void apply() override {

		static BOOL (__cdecl*orgLoadDialogFile)(char*, int*) =
			replaceFunction<BOOL(__cdecl)(char*, int*)>(0x10036600, [](char* filename, int* dlgFileHandle){
			return dialogScripts.Load(filename, *dlgFileHandle)?TRUE:FALSE;
			//return orgLoadDialogFile(filename, dlgFileHandle);
		});

	}
} dialogHooks;

bool DialogLine::IsPcLine(){
	return this->minIq != 0;
}

bool DialogLine::IsNpcLine(){
	return !IsPcLine();
}

DialogLine &DialogLine::operator=(DialogLineNew &src){
	auto &dest = *this;

	dest.minIq = src.minIq;
	dest.answerLineId = src.answerLineId;
	dest.key = src.key;
	dest.txt = _strdup(src.txt.c_str());

	// copy testField if not blank
	auto testFieldOk = false;
	for (auto i = 0u; i < src.testField.size(); i++) {
		if (!isspace(src.testField[i])) {
			testFieldOk = true;
			break;
		}
	}
	dest.testField = testFieldOk ? _strdup(src.testField.c_str()) : nullptr;

	// copy effectfield if not blank
	auto effectFieldOk = false;
	for (auto i = 0u; i < src.effectField.size(); i++) {
		if (!isspace(src.effectField[i])) {
			effectFieldOk = true;
			break;
		}
	}
	dest.effectField = effectFieldOk ? _strdup(src.effectField.c_str()) : nullptr;

	if (src.IsNpcLine())
		dest.genderField = _strdup(src.genderField.c_str());
	else
		dest.genderField = (char*)-1;

	return dest;
}

string DialogScripts::GetFilename(int scriptId) {
	char filename[MAX_PATH];
	if (addresses.GetFilename(scriptId, filename)) {
		return filename;
	} else {
		return string();
	}
}

bool DialogScripts::Load(const string& filename, int& dlgHandle) {
	DialogFile *&mFileEntries = temple::GetRef<DialogFile*>(0x108ED0CC);
	int &mFileEntryCount = temple::GetRef<int>(0x108ED0C4);

	if (GetFileEntryByFilename(filename, dlgHandle)){
		auto &entry = mFileEntries[dlgHandle];
		entry.refCount++;
		entry.lastTimeLoaded = gameSystems->GetTimeEvent().GetTime();
		return true;
	}

	DialogFile newEntry;
	strcpy(newEntry.filename, filename.c_str());
	newEntry.refCount = 1;
	newEntry.lineCapacity = newEntry.lineCount = 0;
	newEntry.lastTimeLoaded = gameSystems->GetTimeEvent().GetTime();
	newEntry.lines = nullptr;
	newEntry.unk11C = 0;

	newEntry.GetLinesFromFile();
	if (newEntry.lineCount ==0)
		return false;

	memcpy(&mFileEntries[dlgHandle], &newEntry, sizeof DialogFile);
	mFileEntryCount++;

	return true;
	//return addresses.LoadScript(filename.c_str(), dlgHandle);
}

void DialogScripts::LoadNpcLine(DialogState& state, bool force) {
	addresses.LoadNpcLine(state, force);
}

void DialogScripts::Free(int dlgHandle) {
	addresses.FreeScript(dlgHandle);
}

DialogFile* DialogScripts::GetDialogFileEntry(int dlgHandle){
	DialogFile *&mFileEntries = temple::GetRef<DialogFile*>(0x108ED0CC);
	int &mFileEntryCount = temple::GetRef<int>(0x108ED0C4);

	if (dlgHandle >= mFileEntryCount || dlgHandle < 0)
		return nullptr;
	return &mFileEntries[dlgHandle];
}

ostream & operator<<(ostream & result, DialogLine &line){
	/*
	{1}{NPC txt}{Gender}{     }{speechId }{        }{}
	{2}{PC txt }{      }{minIq}{testField}{answerId}{effectField}
	*/
	if (line.IsPcLine()) {
		result << "{" << line.key << "}";
		if (line.txt)
			result << "{" << line.txt << "}";
		else
			result << "{}";
		result << "{}"; // blank gender field

		result << "{" << line.minIq << "}";
		if (line.testField)
			result << "{" << line.testField << "}";
		else
			result << "{}";
		result << "{" << line.answerLineId << "}";

		if (line.effectField)
			result << "{" << line.effectField << "}";
		else
			result << "{}";

		//result = fmt::format("\{{}\}\{{}\}\{\}\{{}\}\{{}\}\{{}\}\{{}\}",
		//	line.key, line.txt, line.minIq, line.testField, line.answerLineId, line.effectField );
	}
	else {

		result << "{" << line.key << "}";
		if (line.txt)
			result << "{" << line.txt << "}";
		else
			result << "{}";

		if (line.genderField)
			result << "{" << line.genderField << "}";
		else
			result << "{}";

		result << "{}";
		result << "{}";
		result << "{}";

		if (line.effectField)
			result << "{" << line.effectField << "}";
		else
			result << "{}";

		//result = fmt::format("\{{}\}\{{}\}\{{}\}\{\}\{\}\{\}\{\}",
		//	line.key, line.txt, line.genderField, line.effectField);
	}
	return result;
}

void DialogScripts::SaveToFile(int dlgHandle){
	auto fileEntry = GetDialogFileEntry(dlgHandle);
	if (!fileEntry)
		return;

	std::string newFileName(fmt::format("", fileEntry->filename));
	//auto newFile = fopen("shit.mes", "wb");
	ofstream newFile("shit.mes");

	for (auto i=0; i < fileEntry->lineCount; i++){
		auto line = fileEntry->lines[i];

		if (i && line.IsNpcLine() && line.key < 10000) {
			newFile << std::endl;
			if (!(line.key % 10))
				newFile << std::endl;
		}
		newFile << line << std::endl;
	}
}

bool DialogScripts::GetFileEntryByFilename(const std::string & filename, int &dlgHandleOut){

	DialogFile *&mFileEntries = temple::GetRef<DialogFile*>(0x108ED0CC);
	int &mFileEntryCapacity = temple::GetRef<int>(0x108ED0C8);

	auto oldestFreeHandle = -1;

	for (auto i=0; i < mFileEntryCapacity; i++){

		auto &entry = mFileEntries[i];

		if (!_stricmp(filename.c_str(), entry.filename)){
			dlgHandleOut = i;
			return true;
		}
		if (!entry.refCount){
			if (oldestFreeHandle == -1){
				oldestFreeHandle = i;
			}
			else{
				auto &lastEntry = mFileEntries[oldestFreeHandle];
				if (lastEntry.filename[0]
				&& (!entry.filename[0])
					|| GameTime::Compare(lastEntry.lastTimeLoaded,
						entry.lastTimeLoaded) > 0){
					oldestFreeHandle = i;
			    }

			}
		}
	}

	if (oldestFreeHandle != -1){
		dlgHandleOut = oldestFreeHandle;
		if (mFileEntries[oldestFreeHandle].filename[0])
			Free(oldestFreeHandle);
		return false;
	}

	auto prevCount = mFileEntryCapacity;
	dlgHandleOut = prevCount;
	// allocate 10 more entries
	mFileEntryCapacity += 10;
	mFileEntries = (DialogFile*)realloc(mFileEntries, mFileEntryCapacity * sizeof DialogFile);
	for (auto i=prevCount; i < mFileEntryCapacity; i++){
		auto &entry = mFileEntries[i];
		entry.filename[0] = 0;
		entry.refCount = 0;
	}
	return false;
}

struct DlgParser {
	stringstream ss;
	string lineBuf; // buffer for storing a line's content

	stringstream bracketStream;
	string bracketContent;

	bool GetSingleLine(DialogLineNew &line, int&fileLine);
	bool GetBracketContent(int &fileLine);

	DlgParser(string & fileContents):ss(fileContents){};
};

bool DlgParser::GetSingleLine(DialogLineNew& line, int& fileLine){
	// parse buf for bracket stuff until a line is complete
	if (!GetBracketContent(fileLine))
		return false;
	line.key = atol(bracketContent.c_str());

	if (!GetBracketContent(fileLine)){
		logger->error("Missing text on line: {} (dialog line {})", fileLine, line.key);
		return false;
	}
	line.txt = bracketContent;

	if (!GetBracketContent(fileLine)) {
		logger->error("Missing gender field on line: {} (dialog line {})", fileLine, line.key);
		return false;
	}
	line.genderField = bracketContent;

	if (!GetBracketContent(fileLine)) {
		logger->error("Missing minimum IQ value on line: {} (dialog line {})", fileLine, line.key);
		return false;
	}
	auto minIq = atol(bracketContent.c_str());
	if (!minIq && bracketContent.size()) {
		logger->error("Invalid minimum IQ value on line: {} (dialog line {}). Must be blank (for an NPC) or non-zero (for a PC)", fileLine, line.key);
		return false;
	}
	line.minIq = minIq;

	if (!GetBracketContent(fileLine)) {
		logger->error("Missing test field on line: {} (dialog line {})", fileLine, line.key);
		return false;
	}
	line.testField = bracketContent;

	if (!GetBracketContent(fileLine)) {
		logger->error("Missing response value on line: {} (dialog line {})", fileLine, line.key);
		return false;
	}
	if (bracketContent[0] == '#'){
		logger->error("Saw a # in a response value on line: {} (dialog line {})", fileLine, line.key);
		return 0;
	}
	line.answerLineId = atol(bracketContent.c_str());

	if (!GetBracketContent(fileLine)) {
		logger->error("Missing effect field on line: {} (dialog line {})", fileLine, line.key);
		return false;
	}
	line.effectField = bracketContent;

	// check non-blank gender field for NPC lines
	if (line.IsNpcLine()){

		auto fieldIsBlank= true;
		for (auto i = 0u; i < line.genderField.size(); i++) {
			if (!isspace(line.genderField[i])) {
				fieldIsBlank = false;
				break;
			}
		}

		// if it's blank, check that the txt field isn't also blank (e.g. when using the picker stuff)
		if (fieldIsBlank){

			fieldIsBlank = true;
			for (auto i = 0u; i < line.txt.size(); i++) {
				if (!isspace(line.txt[i])) {
					fieldIsBlank = false;
					break;
				}
			}

			if (!fieldIsBlank)
				logger->warn("Missing NPC response line for females: {} (dialog line {})", fileLine, line.key);
		}
	}

	return true;
}

bool DlgParser::GetBracketContent(int &fileLine){
	string brBuf;
	const int MAX_TEXT_SIZE = 1000;

	getline(ss, brBuf, '{');
	if (ss.eof()) { // no new brackets found
		return false;
	}

	// count how many newlines
	for (auto nl = strchr(brBuf.c_str(), '\n'); nl; fileLine++) {
		nl = strchr(nl + 1, '\n');
	}
	auto rb = strchr(brBuf.c_str(), '}');
	if (rb){
		logger->warn("Possible missing left brace on or before line {}", fileLine);
	}

	// get bracket content
	getline(ss, brBuf, '}');
	if (ss.eof()) {
		logger->error("Unclosed bracket found! Line {}", fileLine);
		return false;
	}
	if (ss.gcount() >= MAX_TEXT_SIZE){
		logger->error("String too long on line: {} (max is {})", fileLine, MAX_TEXT_SIZE);
		return false;
	}
	// count how many newlines inside bracket
	for (auto nl = strchr(brBuf.c_str(), '\n'); nl; fileLine++) {
		nl = strchr(nl + 1, '\n');
	}

	bracketContent = brBuf;
	return true;
}

void DialogFile::GetLinesFromFile()
{
	if (!vfs->FileExists(this->filename))
		return;

	auto fileContents = vfs->ReadAsString(this->filename);
	DlgParser dlgParser(fileContents);

	int fileLine = 1;
	DialogLineNew lineTmp;
	while (dlgParser.GetSingleLine(lineTmp, fileLine)){

		if (this->lineCount == this->lineCapacity){
			this->lineCapacity += 10;
			this->lines = (DialogLine*)realloc(lines, lineCapacity * sizeof DialogLine);
		}
		this->lines[lineCount++] = lineTmp;

	}

	std::sort(this->lines, &this->lines[lineCount-1], [](DialogLine &a, DialogLine &b)->bool{
		return a.key < b.key;
	});
}

bool DialogLineNew::IsPcLine() {
	return minIq != 0;
}

bool DialogLineNew::IsNpcLine(){
	return !IsPcLine();
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * 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: ReportSection.hxx,v $
 * $Revision: 1.6 $
 *
 * 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 REPORT_REPORTSECTION_HXX
#define REPORT_REPORTSECTION_HXX

#include <vcl/window.hxx>
#include "RptPage.hxx"
#include <com/sun/star/beans/NamedValue.hpp>
#include <comphelper/propmultiplex.hxx>
#include "cppuhelper/basemutex.hxx"
#include "ReportDefines.hxx"
#include "dlgedfunc.hxx"
#include <svtools/transfer.hxx>
#include <rtl/ref.hxx>
#include <boost/shared_ptr.hpp>
#include <memory>

namespace rptui
{
    class OReportModel;
    class OReportPage;
    class OSectionView;
    class OViewsWindow;

    class OReportSection :   public Window
                        ,   public ::cppu::BaseMutex
                        ,   public ::comphelper::OPropertyChangeListener
                        ,   public DropTargetHelper
    {
        OReportPage*                        m_pPage;
        OSectionView*                       m_pView;
        OViewsWindow*                       m_pParent;
        ::std::auto_ptr<DlgEdFunc>          m_pFunc;
        ::boost::shared_ptr<OReportModel>   m_pModel;
        ::rtl::Reference< comphelper::OPropertyChangeMultiplexer>                           m_pMulti;
        ::rtl::Reference< comphelper::OPropertyChangeMultiplexer>                           m_pReportListener;
        ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection >              m_xSection;

        DlgEdMode                   m_eMode;
        BOOL                        m_bDialogModelChanged;
        sal_Bool                    m_bInDrag;

        /** fills the section with all control from the report section
        */
        void fill();

        OReportSection(OReportSection&);
        void operator =(OReportSection&);
    protected:
        // DropTargetHelper overridables
        virtual sal_Int8    AcceptDrop( const AcceptDropEvent& _rEvt );
        virtual sal_Int8    ExecuteDrop( const ExecuteDropEvent& _rEvt );

        // window overrides
        virtual void        Paint( const Rectangle& rRect );
        virtual void        MouseMove( const MouseEvent& rMEvt );
        virtual void        Command( const CommandEvent& rCEvt );
        virtual void        LoseFocus();
        virtual void        GetFocus();
        virtual void        Resize();

        // OPropertyChangeListener
        virtual void    _propertyChanged(const ::com::sun::star::beans::PropertyChangeEvent& _rEvent) throw( ::com::sun::star::uno::RuntimeException);
    public:
        OReportSection(OViewsWindow* _pParent,const ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection >& _xSection);
        virtual ~OReportSection();

        // window overrides
        virtual void        MouseButtonDown( const MouseEvent& rMEvt );
        virtual void        MouseButtonUp( const MouseEvent& rMEvt );

        /** copies the current selection in this section
            @param  _rAllreadyCopiedObjects This is an out/in put param which contains all already copied objects.
        */
        void Copy(::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _rAllreadyCopiedObjects);

        void Copy(::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _rAllreadyCopiedObjects,bool _bEraseAnddNoClone);

        /** paste a new control in this section
            @param  _aAllreadyCopiedObjects objects to paste into the section. Only objects are pasted where the name is equal to the section name.
            @param  _bForce If set to <TRUE/> than the objects will be copied into this section. The name is not compared in this case.
        */
        void Paste(const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _aAllreadyCopiedObjects,bool _bForce = false);

        /** Deletes the current selection in this section
        *
        */
        void Delete();

        /** All objects will be marked.
        */
        void SelectAll();

        /** makes the grid visible
        *
        * \param _bVisible when <TRUE/> the grid is made visible
        */
        void SetGridVisible(BOOL _bVisible);

        inline OViewsWindow*        getViewsWindow() const { return m_pParent; }
        inline OSectionView*        getView() const { return m_pView; }
        inline OReportPage*         getPage() const { return m_pPage; }
        inline ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection > getSection() const { return m_xSection; }

        void            SetDialogModelChanged( BOOL bChanged = TRUE ) { m_bDialogModelChanged = bChanged; }
        BOOL            IsDialogModelChanged() const { return m_bDialogModelChanged; }
        DlgEdMode       GetMode() const { return m_eMode; }
        void            SetMode( DlgEdMode m_eMode );

        /** checks if the keycode is known by the child windows
            @param  _rCode  the keycode
            @return <TRUE/> if the keycode is handled otherwise <FALSE/>
        */
        sal_Bool        handleKeyEvent(const KeyEvent& _rEvent);

        /** returns the current control report model or <NULL/>
        */
        ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent > getCurrentControlModel() const;

        /** fills the vector with all selected control models
            /param  _rSelection The vector will be filled and will not be cleared before.
        */
        void fillControlModelSelection(::std::vector< ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > >& _rSelection) const;

        /** creates a default object (custom shape)
        *
        * @param _sType
        */
        void createDefault(const ::rtl::OUString& _sType);

        /** creates a new default custom shape
        *
        * \param _sType
        * \param _pObj
        */
        void createDefault(const ::rtl::OUString& _sType,SdrObject* _pObj);
        void stopScrollTimer();

        /** deactivate the currect active ole object if any
        */
        void    deactivateOle();

        /** returns true when an ole object is currently active
        */
        bool isUiActive() const;
    };
//==================================================================
}   //rptui
//==================================================================
#endif // REPORT_REPORTSECTION_HXX

<commit_msg>INTEGRATION: CWS dba31a (1.5.28); FILE MERGED 2008/07/07 06:38:25 oj 1.5.28.5: #i80200# method to select different types 2008/07/01 07:02:11 oj 1.5.28.4: #i77916# impl zoom and move config data into ext 2008/06/26 14:26:32 oj 1.5.28.3: #i77916# impl zooming in report builder 2008/06/24 12:06:56 oj 1.5.28.2: RESYNC: (1.5-1.6); FILE MERGED 2008/06/13 11:40:19 oj 1.5.28.1: #i88506# impl hyphenation<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: ReportSection.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 REPORT_REPORTSECTION_HXX
#define REPORT_REPORTSECTION_HXX

#include <vcl/window.hxx>
#include "RptPage.hxx"
#include <com/sun/star/beans/NamedValue.hpp>
#include <comphelper/propmultiplex.hxx>
#include "cppuhelper/basemutex.hxx"
#include "ReportDefines.hxx"
#include "dlgedfunc.hxx"
#include <svtools/transfer.hxx>
#include <rtl/ref.hxx>
#include <boost/shared_ptr.hpp>
#include <memory>

namespace rptui
{
    class OReportModel;
    class OReportPage;
    class OSectionView;
    class OSectionWindow;

    class OReportSection :   public Window
                        ,   public ::cppu::BaseMutex
                        ,   public ::comphelper::OPropertyChangeListener
                        ,   public DropTargetHelper
    {
        OReportPage*                        m_pPage;
        OSectionView*                       m_pView;
        OSectionWindow*                     m_pParent;
        ::std::auto_ptr<DlgEdFunc>          m_pFunc;
        ::boost::shared_ptr<OReportModel>   m_pModel;
        ::rtl::Reference< comphelper::OPropertyChangeMultiplexer>                           m_pMulti;
        ::rtl::Reference< comphelper::OPropertyChangeMultiplexer>                           m_pReportListener;
        ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection >              m_xSection;

        DlgEdMode                   m_eMode;
        BOOL                        m_bDialogModelChanged;
        sal_Bool                    m_bInDrag;

        /** fills the section with all control from the report section
        */
        void fill();

        OReportSection(OReportSection&);
        void operator =(OReportSection&);
    protected:
        // DropTargetHelper overridables
        virtual sal_Int8    AcceptDrop( const AcceptDropEvent& _rEvt );
        virtual sal_Int8    ExecuteDrop( const ExecuteDropEvent& _rEvt );

        // window overrides
        virtual void        Paint( const Rectangle& rRect );
        virtual void        MouseMove( const MouseEvent& rMEvt );
        virtual void        Command( const CommandEvent& rCEvt );
        virtual void        Resize();

        // OPropertyChangeListener
        virtual void    _propertyChanged(const ::com::sun::star::beans::PropertyChangeEvent& _rEvent) throw( ::com::sun::star::uno::RuntimeException);
    public:
        OReportSection(OSectionWindow* _pParent,const ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection >& _xSection);
        virtual ~OReportSection();

        // window overrides
        virtual void        MouseButtonDown( const MouseEvent& rMEvt );
        virtual void        MouseButtonUp( const MouseEvent& rMEvt );

        /** copies the current selection in this section
            @param  _rAllreadyCopiedObjects This is an out/in put param which contains all already copied objects.
        */
        void Copy(::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _rAllreadyCopiedObjects);

        void Copy(::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _rAllreadyCopiedObjects,bool _bEraseAnddNoClone);

        /** paste a new control in this section
            @param  _aAllreadyCopiedObjects objects to paste into the section. Only objects are pasted where the name is equal to the section name.
            @param  _bForce If set to <TRUE/> than the objects will be copied into this section. The name is not compared in this case.
        */
        void Paste(const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _aAllreadyCopiedObjects,bool _bForce = false);

        /** Deletes the current selection in this section
        *
        */
        void Delete();

        /** All objects will be marked.
        */
        void SelectAll(const sal_uInt16 _nObjectType);

        /** makes the grid visible
        *
        * \param _bVisible when <TRUE/> the grid is made visible
        */
        void SetGridVisible(BOOL _bVisible);

        inline OSectionWindow*      getSectionWindow() const { return m_pParent; }
        inline OSectionView&        getSectionView() const { return *m_pView; }
        inline OReportPage*         getPage() const { return m_pPage; }
        inline ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection > getSection() const { return m_xSection; }

        void            SetDialogModelChanged( BOOL bChanged = TRUE ) { m_bDialogModelChanged = bChanged; }
        BOOL            IsDialogModelChanged() const { return m_bDialogModelChanged; }
        DlgEdMode       GetMode() const { return m_eMode; }
        void            SetMode( DlgEdMode m_eMode );

        /** checks if the keycode is known by the child windows
            @param  _rCode  the keycode
            @return <TRUE/> if the keycode is handled otherwise <FALSE/>
        */
        sal_Bool        handleKeyEvent(const KeyEvent& _rEvent);

        /** returns the current control report model or <NULL/>
        */
        ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent > getCurrentControlModel() const;

        /** fills the vector with all selected control models
            /param  _rSelection The vector will be filled and will not be cleared before.
        */
        void fillControlModelSelection(::std::vector< ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > >& _rSelection) const;

        /** creates a default object (custom shape)
        *
        * @param _sType
        */
        void createDefault(const ::rtl::OUString& _sType);

        /** creates a new default custom shape
        *
        * \param _sType
        * \param _pObj
        */
        void createDefault(const ::rtl::OUString& _sType,SdrObject* _pObj);
        void stopScrollTimer();

        /** deactivate the currect active ole object if any
        */
        void    deactivateOle();

        /** returns true when an ole object is currently active
        */
        bool isUiActive() const;
    };
//==================================================================
}   //rptui
//==================================================================
#endif // REPORT_REPORTSECTION_HXX

<|endoftext|>


<commit_before>//===-- RecordingMemoryManager.cpp ------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// C Includes
// C++ Includes
// Other libraries and framework includes
#include "llvm/ExecutionEngine/ExecutionEngine.h"
// Project includes
#include "lldb/Expression/RecordingMemoryManager.h"

using namespace lldb_private;

RecordingMemoryManager::RecordingMemoryManager () :
    llvm::JITMemoryManager(),
    m_default_mm_ap (llvm::JITMemoryManager::CreateDefaultMemManager()),
    m_log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS))
{
}

RecordingMemoryManager::~RecordingMemoryManager ()
{
}

void
RecordingMemoryManager::setMemoryWritable ()
{
    m_default_mm_ap->setMemoryWritable();
}

void
RecordingMemoryManager::setMemoryExecutable ()
{
    m_default_mm_ap->setMemoryExecutable();
}

uint8_t *
RecordingMemoryManager::startFunctionBody(const llvm::Function *F,
                     uintptr_t &ActualSize)
{
    return m_default_mm_ap->startFunctionBody(F, ActualSize);
}

uint8_t *
RecordingMemoryManager::allocateStub(const llvm::GlobalValue* F, unsigned StubSize,
                unsigned Alignment)
{
    uint8_t *return_value = m_default_mm_ap->allocateStub(F, StubSize, Alignment);

    Allocation allocation;
    allocation.m_size = StubSize;
    allocation.m_alignment = Alignment;
    allocation.m_local_start = (uintptr_t)return_value;

    if (m_log)
    {
        m_log->Printf("RecordingMemoryManager::allocateStub (F=%p, StubSize=%u, Alignment=%u) = %p",
                      F, StubSize, Alignment, return_value);
        allocation.dump(m_log);
    }

    m_allocations.push_back(allocation);

    return return_value;
}

void
RecordingMemoryManager::endFunctionBody(const llvm::Function *F, uint8_t *FunctionStart,
               uint8_t *FunctionEnd)
{
    m_default_mm_ap->endFunctionBody(F, FunctionStart, FunctionEnd);
}

uint8_t *
RecordingMemoryManager::allocateSpace(intptr_t Size, unsigned Alignment)
{
    uint8_t *return_value = m_default_mm_ap->allocateSpace(Size, Alignment);

    Allocation allocation;
    allocation.m_size = Size;
    allocation.m_alignment = Alignment;
    allocation.m_local_start = (uintptr_t)return_value;

    if (m_log)
    {
        m_log->Printf("RecordingMemoryManager::allocateSpace(Size=%llu, Alignment=%u) = %p",
                      (uint64_t)Size, Alignment, return_value);
        allocation.dump(m_log);
    }

    m_allocations.push_back(allocation);

    return return_value;
}

uint8_t *
RecordingMemoryManager::allocateCodeSection(uintptr_t Size, unsigned Alignment, unsigned SectionID)
{
    uint8_t *return_value = m_default_mm_ap->allocateCodeSection(Size, Alignment, SectionID);

    Allocation allocation;
    allocation.m_size = Size;
    allocation.m_alignment = Alignment;
    allocation.m_local_start = (uintptr_t)return_value;
    allocation.m_section_id = SectionID;
    allocation.m_executable = true;

    if (m_log)
    {
        m_log->Printf("RecordingMemoryManager::allocateCodeSection(Size=0x%llx, Alignment=%u, SectionID=%u) = %p",
                      (uint64_t)Size, Alignment, SectionID, return_value);
        allocation.dump(m_log);
    }

    m_allocations.push_back(allocation);

    return return_value;
}

uint8_t *
RecordingMemoryManager::allocateDataSection(uintptr_t Size, unsigned Alignment, unsigned SectionID)
{
    uint8_t *return_value = m_default_mm_ap->allocateDataSection(Size, Alignment, SectionID);

    Allocation allocation;
    allocation.m_size = Size;
    allocation.m_alignment = Alignment;
    allocation.m_local_start = (uintptr_t)return_value;
    allocation.m_section_id = SectionID;

    if (m_log)
    {
        m_log->Printf("RecordingMemoryManager::allocateDataSection(Size=0x%llx, Alignment=%u, SectionID=%u) = %p",
                      (uint64_t)Size, Alignment, SectionID, return_value);
        allocation.dump(m_log);
    }

    m_allocations.push_back(allocation);

    return return_value;
}

uint8_t *
RecordingMemoryManager::allocateGlobal(uintptr_t Size, unsigned Alignment)
{
    uint8_t *return_value = m_default_mm_ap->allocateGlobal(Size, Alignment);

    Allocation allocation;
    allocation.m_size = Size;
    allocation.m_alignment = Alignment;
    allocation.m_local_start = (uintptr_t)return_value;

    if (m_log)
    {
        m_log->Printf("RecordingMemoryManager::allocateGlobal(Size=0x%llx, Alignment=%u) = %p",
                      (uint64_t)Size, Alignment, return_value);
        allocation.dump(m_log);
    }

    m_allocations.push_back(allocation);

    return return_value;
}

void
RecordingMemoryManager::deallocateFunctionBody(void *Body)
{
    m_default_mm_ap->deallocateFunctionBody(Body);
}

uint8_t*
RecordingMemoryManager::startExceptionTable(const llvm::Function* F,
                       uintptr_t &ActualSize)
{
    return m_default_mm_ap->startExceptionTable(F, ActualSize);
}

void
RecordingMemoryManager::endExceptionTable(const llvm::Function *F, uint8_t *TableStart,
                 uint8_t *TableEnd, uint8_t* FrameRegister)
{
    m_default_mm_ap->endExceptionTable(F, TableStart, TableEnd, FrameRegister);
}

void
RecordingMemoryManager::deallocateExceptionTable(void *ET)
{
    m_default_mm_ap->deallocateExceptionTable (ET);
}

lldb::addr_t
RecordingMemoryManager::GetRemoteAddressForLocal (lldb::addr_t local_address)
{
    for (AllocationList::iterator ai = m_allocations.begin(), ae = m_allocations.end();
         ai != ae;
         ++ai)
    {
        if (local_address >= ai->m_local_start &&
            local_address < ai->m_local_start + ai->m_size)
            return ai->m_remote_start + (local_address - ai->m_local_start);
    }

    return LLDB_INVALID_ADDRESS;
}

RecordingMemoryManager::AddrRange
RecordingMemoryManager::GetRemoteRangeForLocal (lldb::addr_t local_address)
{
    for (AllocationList::iterator ai = m_allocations.begin(), ae = m_allocations.end();
         ai != ae;
         ++ai)
    {
        if (local_address >= ai->m_local_start &&
            local_address < ai->m_local_start + ai->m_size)
            return AddrRange(ai->m_remote_start, ai->m_size);
    }

    return AddrRange (0, 0);
}

bool
RecordingMemoryManager::CommitAllocations (Process &process)
{
    bool ret = true;

    for (AllocationList::iterator ai = m_allocations.begin(), ae = m_allocations.end();
         ai != ae;
         ++ai)
    {
        if (ai->m_allocated)
            continue;

        lldb_private::Error err;

        size_t allocation_size = (ai->m_size ? ai->m_size : 1) + ai->m_alignment - 1;

        if (allocation_size == 0)
            allocation_size = 1;œ

        ai->m_remote_allocation = process.AllocateMemory(
            allocation_size,
            ai->m_executable ? (lldb::ePermissionsReadable | lldb::ePermissionsExecutable)
                             : (lldb::ePermissionsReadable | lldb::ePermissionsWritable),
            err);

        uint64_t mask = ai->m_alignment - 1;

        ai->m_remote_start = (ai->m_remote_allocation + mask) & (~mask);

        if (!err.Success())
        {
            ret = false;
            break;
        }

        ai->m_allocated = true;

        if (m_log)
        {
            m_log->Printf("RecordingMemoryManager::CommitAllocations() committed an allocation");
            ai->dump(m_log);
        }
    }

    if (!ret)
    {
        for (AllocationList::iterator ai = m_allocations.end(), ae = m_allocations.end();
             ai != ae;
             ++ai)
        {
            if (ai->m_allocated)
                process.DeallocateMemory(ai->m_remote_start);
        }
    }

    return ret;
}

void
RecordingMemoryManager::ReportAllocations (llvm::ExecutionEngine &engine)
{
    for (AllocationList::iterator ai = m_allocations.begin(), ae = m_allocations.end();
         ai != ae;
         ++ai)
    {
        if (!ai->m_allocated)
            continue;

        engine.mapSectionAddress((void*)ai->m_local_start, ai->m_remote_start);
    }
}

bool
RecordingMemoryManager::WriteData (Process &process)
{
    for (AllocationList::iterator ai = m_allocations.begin(), ae = m_allocations.end();
         ai != ae;
         ++ai)
    {
        if (!ai->m_allocated)
            return false;

        lldb_private::Error err;

        if (process.WriteMemory(ai->m_remote_start,
                                (void*)ai->m_local_start,
                                ai->m_size,
                                err) != ai->m_size ||
            !err.Success())
            return false;

        if (m_log)
        {
            m_log->Printf("RecordingMemoryManager::CommitAllocations() wrote an allocation");
            ai->dump(m_log);
        }
    }

    return true;
}

void
RecordingMemoryManager::Allocation::dump (lldb::LogSP log)
{
    if (!log)
        return;

    log->Printf("[0x%llx+0x%llx]->0x%llx (alignment %d, section ID %d)",
                (unsigned long long)m_local_start,
                (unsigned long long)m_size,
                (unsigned long long)m_remote_start,
                (unsigned)m_alignment,
                (unsigned)m_section_id);
}
<commit_msg>And remove the control character that somehow found its way into the last checkin...<commit_after>//===-- RecordingMemoryManager.cpp ------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// C Includes
// C++ Includes
// Other libraries and framework includes
#include "llvm/ExecutionEngine/ExecutionEngine.h"
// Project includes
#include "lldb/Expression/RecordingMemoryManager.h"

using namespace lldb_private;

RecordingMemoryManager::RecordingMemoryManager () :
    llvm::JITMemoryManager(),
    m_default_mm_ap (llvm::JITMemoryManager::CreateDefaultMemManager()),
    m_log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS))
{
}

RecordingMemoryManager::~RecordingMemoryManager ()
{
}

void
RecordingMemoryManager::setMemoryWritable ()
{
    m_default_mm_ap->setMemoryWritable();
}

void
RecordingMemoryManager::setMemoryExecutable ()
{
    m_default_mm_ap->setMemoryExecutable();
}

uint8_t *
RecordingMemoryManager::startFunctionBody(const llvm::Function *F,
                     uintptr_t &ActualSize)
{
    return m_default_mm_ap->startFunctionBody(F, ActualSize);
}

uint8_t *
RecordingMemoryManager::allocateStub(const llvm::GlobalValue* F, unsigned StubSize,
                unsigned Alignment)
{
    uint8_t *return_value = m_default_mm_ap->allocateStub(F, StubSize, Alignment);

    Allocation allocation;
    allocation.m_size = StubSize;
    allocation.m_alignment = Alignment;
    allocation.m_local_start = (uintptr_t)return_value;

    if (m_log)
    {
        m_log->Printf("RecordingMemoryManager::allocateStub (F=%p, StubSize=%u, Alignment=%u) = %p",
                      F, StubSize, Alignment, return_value);
        allocation.dump(m_log);
    }

    m_allocations.push_back(allocation);

    return return_value;
}

void
RecordingMemoryManager::endFunctionBody(const llvm::Function *F, uint8_t *FunctionStart,
               uint8_t *FunctionEnd)
{
    m_default_mm_ap->endFunctionBody(F, FunctionStart, FunctionEnd);
}

uint8_t *
RecordingMemoryManager::allocateSpace(intptr_t Size, unsigned Alignment)
{
    uint8_t *return_value = m_default_mm_ap->allocateSpace(Size, Alignment);

    Allocation allocation;
    allocation.m_size = Size;
    allocation.m_alignment = Alignment;
    allocation.m_local_start = (uintptr_t)return_value;

    if (m_log)
    {
        m_log->Printf("RecordingMemoryManager::allocateSpace(Size=%llu, Alignment=%u) = %p",
                      (uint64_t)Size, Alignment, return_value);
        allocation.dump(m_log);
    }

    m_allocations.push_back(allocation);

    return return_value;
}

uint8_t *
RecordingMemoryManager::allocateCodeSection(uintptr_t Size, unsigned Alignment, unsigned SectionID)
{
    uint8_t *return_value = m_default_mm_ap->allocateCodeSection(Size, Alignment, SectionID);

    Allocation allocation;
    allocation.m_size = Size;
    allocation.m_alignment = Alignment;
    allocation.m_local_start = (uintptr_t)return_value;
    allocation.m_section_id = SectionID;
    allocation.m_executable = true;

    if (m_log)
    {
        m_log->Printf("RecordingMemoryManager::allocateCodeSection(Size=0x%llx, Alignment=%u, SectionID=%u) = %p",
                      (uint64_t)Size, Alignment, SectionID, return_value);
        allocation.dump(m_log);
    }

    m_allocations.push_back(allocation);

    return return_value;
}

uint8_t *
RecordingMemoryManager::allocateDataSection(uintptr_t Size, unsigned Alignment, unsigned SectionID)
{
    uint8_t *return_value = m_default_mm_ap->allocateDataSection(Size, Alignment, SectionID);

    Allocation allocation;
    allocation.m_size = Size;
    allocation.m_alignment = Alignment;
    allocation.m_local_start = (uintptr_t)return_value;
    allocation.m_section_id = SectionID;

    if (m_log)
    {
        m_log->Printf("RecordingMemoryManager::allocateDataSection(Size=0x%llx, Alignment=%u, SectionID=%u) = %p",
                      (uint64_t)Size, Alignment, SectionID, return_value);
        allocation.dump(m_log);
    }

    m_allocations.push_back(allocation);

    return return_value;
}

uint8_t *
RecordingMemoryManager::allocateGlobal(uintptr_t Size, unsigned Alignment)
{
    uint8_t *return_value = m_default_mm_ap->allocateGlobal(Size, Alignment);

    Allocation allocation;
    allocation.m_size = Size;
    allocation.m_alignment = Alignment;
    allocation.m_local_start = (uintptr_t)return_value;

    if (m_log)
    {
        m_log->Printf("RecordingMemoryManager::allocateGlobal(Size=0x%llx, Alignment=%u) = %p",
                      (uint64_t)Size, Alignment, return_value);
        allocation.dump(m_log);
    }

    m_allocations.push_back(allocation);

    return return_value;
}

void
RecordingMemoryManager::deallocateFunctionBody(void *Body)
{
    m_default_mm_ap->deallocateFunctionBody(Body);
}

uint8_t*
RecordingMemoryManager::startExceptionTable(const llvm::Function* F,
                       uintptr_t &ActualSize)
{
    return m_default_mm_ap->startExceptionTable(F, ActualSize);
}

void
RecordingMemoryManager::endExceptionTable(const llvm::Function *F, uint8_t *TableStart,
                 uint8_t *TableEnd, uint8_t* FrameRegister)
{
    m_default_mm_ap->endExceptionTable(F, TableStart, TableEnd, FrameRegister);
}

void
RecordingMemoryManager::deallocateExceptionTable(void *ET)
{
    m_default_mm_ap->deallocateExceptionTable (ET);
}

lldb::addr_t
RecordingMemoryManager::GetRemoteAddressForLocal (lldb::addr_t local_address)
{
    for (AllocationList::iterator ai = m_allocations.begin(), ae = m_allocations.end();
         ai != ae;
         ++ai)
    {
        if (local_address >= ai->m_local_start &&
            local_address < ai->m_local_start + ai->m_size)
            return ai->m_remote_start + (local_address - ai->m_local_start);
    }

    return LLDB_INVALID_ADDRESS;
}

RecordingMemoryManager::AddrRange
RecordingMemoryManager::GetRemoteRangeForLocal (lldb::addr_t local_address)
{
    for (AllocationList::iterator ai = m_allocations.begin(), ae = m_allocations.end();
         ai != ae;
         ++ai)
    {
        if (local_address >= ai->m_local_start &&
            local_address < ai->m_local_start + ai->m_size)
            return AddrRange(ai->m_remote_start, ai->m_size);
    }

    return AddrRange (0, 0);
}

bool
RecordingMemoryManager::CommitAllocations (Process &process)
{
    bool ret = true;

    for (AllocationList::iterator ai = m_allocations.begin(), ae = m_allocations.end();
         ai != ae;
         ++ai)
    {
        if (ai->m_allocated)
            continue;

        lldb_private::Error err;

        size_t allocation_size = (ai->m_size ? ai->m_size : 1) + ai->m_alignment - 1;

        if (allocation_size == 0)
            allocation_size = 1;

        ai->m_remote_allocation = process.AllocateMemory(
            allocation_size,
            ai->m_executable ? (lldb::ePermissionsReadable | lldb::ePermissionsExecutable)
                             : (lldb::ePermissionsReadable | lldb::ePermissionsWritable),
            err);

        uint64_t mask = ai->m_alignment - 1;

        ai->m_remote_start = (ai->m_remote_allocation + mask) & (~mask);

        if (!err.Success())
        {
            ret = false;
            break;
        }

        ai->m_allocated = true;

        if (m_log)
        {
            m_log->Printf("RecordingMemoryManager::CommitAllocations() committed an allocation");
            ai->dump(m_log);
        }
    }

    if (!ret)
    {
        for (AllocationList::iterator ai = m_allocations.end(), ae = m_allocations.end();
             ai != ae;
             ++ai)
        {
            if (ai->m_allocated)
                process.DeallocateMemory(ai->m_remote_start);
        }
    }

    return ret;
}

void
RecordingMemoryManager::ReportAllocations (llvm::ExecutionEngine &engine)
{
    for (AllocationList::iterator ai = m_allocations.begin(), ae = m_allocations.end();
         ai != ae;
         ++ai)
    {
        if (!ai->m_allocated)
            continue;

        engine.mapSectionAddress((void*)ai->m_local_start, ai->m_remote_start);
    }
}

bool
RecordingMemoryManager::WriteData (Process &process)
{
    for (AllocationList::iterator ai = m_allocations.begin(), ae = m_allocations.end();
         ai != ae;
         ++ai)
    {
        if (!ai->m_allocated)
            return false;

        lldb_private::Error err;

        if (process.WriteMemory(ai->m_remote_start,
                                (void*)ai->m_local_start,
                                ai->m_size,
                                err) != ai->m_size ||
            !err.Success())
            return false;

        if (m_log)
        {
            m_log->Printf("RecordingMemoryManager::CommitAllocations() wrote an allocation");
            ai->dump(m_log);
        }
    }

    return true;
}

void
RecordingMemoryManager::Allocation::dump (lldb::LogSP log)
{
    if (!log)
        return;

    log->Printf("[0x%llx+0x%llx]->0x%llx (alignment %d, section ID %d)",
                (unsigned long long)m_local_start,
                (unsigned long long)m_size,
                (unsigned long long)m_remote_start,
                (unsigned)m_alignment,
                (unsigned)m_section_id);
}
<|endoftext|>


<commit_before>#include "CommonIntermediatePolyMesh.h"

bool CommonIntermediatePolyMesh::mergeWith(const CommonIntermediatePolyMesh& srcMesh)
{
    ESS_PROFILE_FUNC();
	CommonIntermediatePolyMesh& destMesh = *this;

	//TODO: watch out for the mixing of indexed attributes with nonindexed attributes

	//if(	(destMesh.normalIndexVec.size() == 0 && srcMesh.normalIndexVec.size() > 0) ||
	//	(destMesh.normalIndexVec.size() > 0 && srcMesh.normalIndexVec.size() == 0)) {
	//	ESS_LOG_INFO( "Error: can't mix indexed normals and nonindexed normals." );
	//	return false; //don't allow the mixing of indexed normals with nonindexed normals
	//}

	//if( (destMesh.mUvIndexVec.size() == 0 && srcMesh.mUvIndexVec.size() > 0) ||
	//	(destMesh.mUvIndexVec.size() > 0 && srcMesh.mUvIndexVec.size() == 0)) {
	//	ESS_LOG_INFO( "Error: can't mix indexed UVs and nonindexed UVs." );
	//	return false; //don't allow the mixing of indexed UVs with nonindexed UVs
	//}

	destMesh.bbox.extendBy(srcMesh.bbox);

	Abc::uint32_t amountToOffsetSrcPosIndicesBy = (Abc::uint32_t)destMesh.posVec.size();

	for(int i=0; i<srcMesh.posVec.size(); i++){
		destMesh.posVec.push_back( srcMesh.posVec[i] );
	}

	Abc::uint32_t amountToOffsetSrcNormalIndicesBy = (Abc::uint32_t)destMesh.mIndexedNormals.values.size();

	for(int i=0; i<srcMesh.mIndexedNormals.values.size(); i++){
		destMesh.mIndexedNormals.values.push_back( srcMesh.mIndexedNormals.values[i] );
	}

	for(int i=0; i<srcMesh.mIndexedNormals.indices.size(); i++){
		destMesh.mIndexedNormals.indices.push_back( srcMesh.mIndexedNormals.indices[i] + amountToOffsetSrcNormalIndicesBy );
	}

    //for(int i=0; i<destMesh.mIndexedNormals.indices.size(); i++){
    //   if( destMesh.mIndexedNormals.indices[i] > destMesh.mIndexedNormals.values.size()){
    //       ESS_LOG_WARNING("out of bounds index");
    //   }
    //}

	for(int i=0; i<srcMesh.mFaceCountVec.size(); i++){
		destMesh.mFaceCountVec.push_back( srcMesh.mFaceCountVec[i]);
	}

	for(int i=0; i<srcMesh.mFaceIndicesVec.size(); i++){
		destMesh.mFaceIndicesVec.push_back( srcMesh.mFaceIndicesVec[i] + amountToOffsetSrcPosIndicesBy );
	}

	std::map<std::string,int> uniqueUVNamesMap;
	std::vector<std::string> uniqueUVNames;
	for( int i = 0; i < destMesh.mIndexedUVSet.size(); i ++ ) {
		std::string name = destMesh.mIndexedUVSet[i].name;
		if( uniqueUVNamesMap.find( name ) == uniqueUVNamesMap.end() ) {
			uniqueUVNamesMap.insert( std::map<std::string,int>::value_type( name, 1 ) );
			uniqueUVNames.push_back( name );
		}
	}
	for( int i = 0; i < srcMesh.mIndexedUVSet.size(); i ++ ) {
		std::string name = srcMesh.mIndexedUVSet[i].name;
		if( uniqueUVNamesMap.find( name ) == uniqueUVNamesMap.end() ) {
			uniqueUVNamesMap.insert( std::map<std::string,int>::value_type( name, 1 ) );
			uniqueUVNames.push_back( name );
		}
	}

	for( int i = 0; i < uniqueUVNames.size(); i ++ ) {
		IndexedUVs *pDestIndexedUVs = NULL;
		IndexedUVs const * pSrcIndexedUVs = NULL;
		std::string name = uniqueUVNames[i];
		for( int j = 0; j < srcMesh.mIndexedUVSet.size(); j ++ ) {
			if( name.compare( srcMesh.mIndexedUVSet[i].name ) == 0 ) {
				pSrcIndexedUVs = &(srcMesh.mIndexedUVSet[i]);
			}
		}
		for( int j = 0; j < destMesh.mIndexedUVSet.size(); j ++ ) {
			if( name.compare( destMesh.mIndexedUVSet[i].name ) == 0 ) {
				pDestIndexedUVs = &(destMesh.mIndexedUVSet[i]);
			}
		}
		if( pDestIndexedUVs == NULL ) {
			IndexedUVs newUVs;
			newUVs.name = name;
			destMesh.mIndexedUVSet.push_back( newUVs );
			pDestIndexedUVs = &( destMesh.mIndexedUVSet[ destMesh.mIndexedUVSet.size() - 1] );
			for( int k = 0; k < destMesh.mFaceIndicesVec.size(); k ++ ) {
				pDestIndexedUVs->indices.push_back( 0 );
			}
		}
		if( pSrcIndexedUVs != NULL ) {
			int sourceUVOffset = (int) pDestIndexedUVs->values.size();
			for( int k = 0; k < pSrcIndexedUVs->indices.size(); k ++ ) {
				pDestIndexedUVs->indices.push_back( pSrcIndexedUVs->indices[k] + sourceUVOffset );
			}
			for( int k = 0; k < pSrcIndexedUVs->values.size(); k ++ ) {
				pDestIndexedUVs->values.push_back( pSrcIndexedUVs->values[k] );
			}
		}
		else {
			for( int k = 0; k < srcMesh.mFaceIndicesVec.size(); k ++ ) {
				pDestIndexedUVs->indices.push_back( 0 );
			}
		}
	}

	//Abc::uint32_t amountToOffsetSrcUvIndicesBy = (Abc::uint32_t)destMesh.mUvVec.size();

	//for(int i=0; i<srcMesh.mUvVec.size(); i++){
	//	destMesh.mUvVec.push_back( srcMesh.mUvVec[i] );
	//}

	//for(int i=0; i<srcMesh.mUvIndexVec.size(); i++){
	//	destMesh.mUvIndexVec.push_back( srcMesh.mUvIndexVec[i] + amountToOffsetSrcUvIndicesBy );
	//}

	//3DS MAX merge the faceset maps
	//I assume if that if a key is common, we combine the face lists (this assumption is compatible with
	//our current method of saving out the mapIds and names)
	//for ( facesetmap_cit it=srcMesh.mFaceSetsMap.begin(); it != srcMesh.mFaceSetsMap.end(); it++)
	//{
	//	if( destMesh.mFaceSetsMap.find(it->first) == destMesh.mFaceSetsMap.end() ){ // a new key
	//
	//		destMesh.mFaceSetsMap[it->first] = it->second;
	//	}
	//	else{// the key is common

	//		const facesetmap_vec& srcFaceSetVec = it->second.faceIds;
	//		facesetmap_vec& destFaceSetVec = destMesh.mFaceSetsMap[it->first].faceIds;

	//		for(int i=0; i<srcFaceSetVec.size(); i++){
	//			destFaceSetVec.push_back(srcFaceSetVec[i]);
	//		}
	//	}
	//}

	//for(int i=0; i<srcMesh.mMatIdIndexVec.size(); i++){
	//	destMesh.mMatIdIndexVec.push_back(srcMesh.mMatIdIndexVec[i]);
	//}

	////now rebuilt the matID index array
	//mMatIdIndexVec.resize(destMesh.mFaceSetsMap.size());
	//for ( facesetmap_it it=destMesh.mFaceSetsMap.begin(); it != destMesh.mFaceSetsMap.end(); it++)
	//{
	//	int matId = it->first;
	//	facesetmap_vec& faceSetVec = it->second.faceIds;

	//	for(int i=0; i<faceSetVec.size(); i++)
	//	{
	//		mMatIdIndexVec[faceSetVec[i]] = matId;
	//	}
	//}

	return true;
}

void CommonIntermediatePolyMesh::clear()
{
   //a safer way to clear.
   *this = CommonIntermediatePolyMesh();

 //  bbox = Abc::Box3d();

	//posVec.clear();
	//mFaceCountVec.clear();
	//mFaceIndicesVec.clear();

 //  mVelocitiesVec.clear();

 //  mIndexedNormals.name = std::string();
	//mIndexedNormals.indices.clear();
 //  mIndexedNormals.values.clear();
	//mIndexedUVSet.clear();
	//
 //  //mMatIdIndexVec.clear();

 //  mFaceSets.clear();
 //  mUvOptionsVec.clear();
 //  mBindPoseVec.clear();
 //  bGeomApprox = 0;
}<commit_msg>index i being used where index j should be used (Issue #146)<commit_after>#include "CommonIntermediatePolyMesh.h"

bool CommonIntermediatePolyMesh::mergeWith(const CommonIntermediatePolyMesh& srcMesh)
{
    ESS_PROFILE_FUNC();
	CommonIntermediatePolyMesh& destMesh = *this;

	//TODO: watch out for the mixing of indexed attributes with nonindexed attributes

	//if(	(destMesh.normalIndexVec.size() == 0 && srcMesh.normalIndexVec.size() > 0) ||
	//	(destMesh.normalIndexVec.size() > 0 && srcMesh.normalIndexVec.size() == 0)) {
	//	ESS_LOG_INFO( "Error: can't mix indexed normals and nonindexed normals." );
	//	return false; //don't allow the mixing of indexed normals with nonindexed normals
	//}

	//if( (destMesh.mUvIndexVec.size() == 0 && srcMesh.mUvIndexVec.size() > 0) ||
	//	(destMesh.mUvIndexVec.size() > 0 && srcMesh.mUvIndexVec.size() == 0)) {
	//	ESS_LOG_INFO( "Error: can't mix indexed UVs and nonindexed UVs." );
	//	return false; //don't allow the mixing of indexed UVs with nonindexed UVs
	//}

	destMesh.bbox.extendBy(srcMesh.bbox);

	Abc::uint32_t amountToOffsetSrcPosIndicesBy = (Abc::uint32_t)destMesh.posVec.size();

	for(int i=0; i<srcMesh.posVec.size(); i++){
		destMesh.posVec.push_back( srcMesh.posVec[i] );
	}

	Abc::uint32_t amountToOffsetSrcNormalIndicesBy = (Abc::uint32_t)destMesh.mIndexedNormals.values.size();

	for(int i=0; i<srcMesh.mIndexedNormals.values.size(); i++){
		destMesh.mIndexedNormals.values.push_back( srcMesh.mIndexedNormals.values[i] );
	}

	for(int i=0; i<srcMesh.mIndexedNormals.indices.size(); i++){
		destMesh.mIndexedNormals.indices.push_back( srcMesh.mIndexedNormals.indices[i] + amountToOffsetSrcNormalIndicesBy );
	}

    //for(int i=0; i<destMesh.mIndexedNormals.indices.size(); i++){
    //   if( destMesh.mIndexedNormals.indices[i] > destMesh.mIndexedNormals.values.size()){
    //       ESS_LOG_WARNING("out of bounds index");
    //   }
    //}

	for(int i=0; i<srcMesh.mFaceCountVec.size(); i++){
		destMesh.mFaceCountVec.push_back( srcMesh.mFaceCountVec[i]);
	}

	for(int i=0; i<srcMesh.mFaceIndicesVec.size(); i++){
		destMesh.mFaceIndicesVec.push_back( srcMesh.mFaceIndicesVec[i] + amountToOffsetSrcPosIndicesBy );
	}

	std::map<std::string,int> uniqueUVNamesMap;
	std::vector<std::string> uniqueUVNames;
	for( int i = 0; i < destMesh.mIndexedUVSet.size(); i ++ ) {
		std::string name = destMesh.mIndexedUVSet[i].name;
		if( uniqueUVNamesMap.find( name ) == uniqueUVNamesMap.end() ) {
			uniqueUVNamesMap.insert( std::map<std::string,int>::value_type( name, 1 ) );
			uniqueUVNames.push_back( name );
		}
	}
	for( int i = 0; i < srcMesh.mIndexedUVSet.size(); i ++ ) {
		std::string name = srcMesh.mIndexedUVSet[i].name;
		if( uniqueUVNamesMap.find( name ) == uniqueUVNamesMap.end() ) {
			uniqueUVNamesMap.insert( std::map<std::string,int>::value_type( name, 1 ) );
			uniqueUVNames.push_back( name );
		}
	}

	for( int i = 0; i < uniqueUVNames.size(); i ++ ) {
		IndexedUVs *pDestIndexedUVs = NULL;
		IndexedUVs const * pSrcIndexedUVs = NULL;
		std::string name = uniqueUVNames[i];
		for( int j = 0; j < srcMesh.mIndexedUVSet.size(); j ++ ) {
			if( name.compare( srcMesh.mIndexedUVSet[j].name ) == 0 ) {
				pSrcIndexedUVs = &(srcMesh.mIndexedUVSet[j]);
			}
		}
		for( int j = 0; j < destMesh.mIndexedUVSet.size(); j ++ ) {
			if( name.compare( destMesh.mIndexedUVSet[j].name ) == 0 ) {
				pDestIndexedUVs = &(destMesh.mIndexedUVSet[j]);
			}
		}

      if(pSrcIndexedUVs == NULL && pDestIndexedUVs == NULL){
         //This shoudn't happen, but lets be safe
         continue;
      }

      //there is no map with that name to copy to, so create a new set
      //a uv index is required for each vertex
		if( pDestIndexedUVs == NULL ) {
			IndexedUVs newUVs;
			newUVs.name = name;
			destMesh.mIndexedUVSet.push_back( newUVs );
			pDestIndexedUVs = &( destMesh.mIndexedUVSet[ destMesh.mIndexedUVSet.size() - 1] );
			for( int k = 0; k < destMesh.mFaceIndicesVec.size(); k ++ ) {
				pDestIndexedUVs->indices.push_back( 0 );
			}
		}

		if( pSrcIndexedUVs != NULL ) {
			int sourceUVOffset = (int) pDestIndexedUVs->values.size();
			for( int k = 0; k < pSrcIndexedUVs->indices.size(); k ++ ) {
				pDestIndexedUVs->indices.push_back( pSrcIndexedUVs->indices[k] + sourceUVOffset );
			}
			for( int k = 0; k < pSrcIndexedUVs->values.size(); k ++ ) {
				pDestIndexedUVs->values.push_back( pSrcIndexedUVs->values[k] );
			}
		}
		else {
			for( int k = 0; k < srcMesh.mFaceIndicesVec.size(); k ++ ) {
				pDestIndexedUVs->indices.push_back( 0 );
			}
		}
	}

	//Abc::uint32_t amountToOffsetSrcUvIndicesBy = (Abc::uint32_t)destMesh.mUvVec.size();

	//for(int i=0; i<srcMesh.mUvVec.size(); i++){
	//	destMesh.mUvVec.push_back( srcMesh.mUvVec[i] );
	//}

	//for(int i=0; i<srcMesh.mUvIndexVec.size(); i++){
	//	destMesh.mUvIndexVec.push_back( srcMesh.mUvIndexVec[i] + amountToOffsetSrcUvIndicesBy );
	//}

	//3DS MAX merge the faceset maps
	//I assume if that if a key is common, we combine the face lists (this assumption is compatible with
	//our current method of saving out the mapIds and names)
	//for ( facesetmap_cit it=srcMesh.mFaceSetsMap.begin(); it != srcMesh.mFaceSetsMap.end(); it++)
	//{
	//	if( destMesh.mFaceSetsMap.find(it->first) == destMesh.mFaceSetsMap.end() ){ // a new key
	//
	//		destMesh.mFaceSetsMap[it->first] = it->second;
	//	}
	//	else{// the key is common

	//		const facesetmap_vec& srcFaceSetVec = it->second.faceIds;
	//		facesetmap_vec& destFaceSetVec = destMesh.mFaceSetsMap[it->first].faceIds;

	//		for(int i=0; i<srcFaceSetVec.size(); i++){
	//			destFaceSetVec.push_back(srcFaceSetVec[i]);
	//		}
	//	}
	//}

	//for(int i=0; i<srcMesh.mMatIdIndexVec.size(); i++){
	//	destMesh.mMatIdIndexVec.push_back(srcMesh.mMatIdIndexVec[i]);
	//}

	////now rebuilt the matID index array
	//mMatIdIndexVec.resize(destMesh.mFaceSetsMap.size());
	//for ( facesetmap_it it=destMesh.mFaceSetsMap.begin(); it != destMesh.mFaceSetsMap.end(); it++)
	//{
	//	int matId = it->first;
	//	facesetmap_vec& faceSetVec = it->second.faceIds;

	//	for(int i=0; i<faceSetVec.size(); i++)
	//	{
	//		mMatIdIndexVec[faceSetVec[i]] = matId;
	//	}
	//}

	return true;
}

void CommonIntermediatePolyMesh::clear()
{
   //a safer way to clear.
   *this = CommonIntermediatePolyMesh();

 //  bbox = Abc::Box3d();

	//posVec.clear();
	//mFaceCountVec.clear();
	//mFaceIndicesVec.clear();

 //  mVelocitiesVec.clear();

 //  mIndexedNormals.name = std::string();
	//mIndexedNormals.indices.clear();
 //  mIndexedNormals.values.clear();
	//mIndexedUVSet.clear();
	//
 //  //mMatIdIndexVec.clear();

 //  mFaceSets.clear();
 //  mUvOptionsVec.clear();
 //  mBindPoseVec.clear();
 //  bGeomApprox = 0;
}<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: TypeInfo.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: hr $ $Date: 2006-04-19 13:21:10 $
 *
 *  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 DBAUI_TYPEINFO_HXX
#define DBAUI_TYPEINFO_HXX

#ifndef _RTL_USTRING_
#include <rtl/ustring>
#endif
#ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_
#include <com/sun/star/sdbc/DataType.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_COLUMNSEARCH_HPP_
#include <com/sun/star/sdbc/ColumnSearch.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_
#include <com/sun/star/sdbc/ColumnValue.hpp>
#endif
#include <boost/shared_ptr.hpp>
#include <map>

namespace dbaui
{
//========================================================================
// Anhand dieser Ids werden die sprachabhaengigen ::rtl::OUString aus der Resource geholt
const sal_uInt16 TYPE_UNKNOWN   = 0;
const sal_uInt16 TYPE_TEXT      = 1;
const sal_uInt16 TYPE_NUMERIC   = 2;
const sal_uInt16 TYPE_DATETIME  = 3;
const sal_uInt16 TYPE_DATE      = 4;
const sal_uInt16 TYPE_TIME      = 5;
const sal_uInt16 TYPE_BOOL      = 6;
const sal_uInt16 TYPE_CURRENCY  = 7;
const sal_uInt16 TYPE_MEMO      = 8;
const sal_uInt16 TYPE_COUNTER   = 9;
const sal_uInt16 TYPE_IMAGE     = 10;
const sal_uInt16 TYPE_CHAR      = 11;
const sal_uInt16 TYPE_DECIMAL   = 12;
const sal_uInt16 TYPE_BINARY    = 13;
const sal_uInt16 TYPE_VARBINARY = 14;
const sal_uInt16 TYPE_BIGINT    = 15;
const sal_uInt16 TYPE_DOUBLE    = 16;
const sal_uInt16 TYPE_FLOAT     = 17;
const sal_uInt16 TYPE_REAL      = 18;
const sal_uInt16 TYPE_INTEGER   = 19;
const sal_uInt16 TYPE_SMALLINT  = 20;
const sal_uInt16 TYPE_TINYINT   = 21;
const sal_uInt16 TYPE_SQLNULL   = 22;
const sal_uInt16 TYPE_OBJECT    = 23;
const sal_uInt16 TYPE_DISTINCT  = 24;
const sal_uInt16 TYPE_STRUCT    = 25;
const sal_uInt16 TYPE_ARRAY     = 26;
const sal_uInt16 TYPE_BLOB      = 27;
const sal_uInt16 TYPE_CLOB      = 28;
const sal_uInt16 TYPE_REF       = 29;
const sal_uInt16 TYPE_OTHER     = 30;

    class OTypeInfo
    {
    public:
        ::rtl::OUString aUIName;        // the name which is the user see (a combination of resource text and aTypeName)
        ::rtl::OUString aTypeName;      // Name des Types in der Datenbank
        ::rtl::OUString aLiteralPrefix; // Prefix zum Quoten
        ::rtl::OUString aLiteralSuffix; // Suffix zum Quoten
        ::rtl::OUString aCreateParams;  // Parameter zum Erstellen
        ::rtl::OUString aLocalTypeName;

        sal_Int32       nPrecision;     // Laenge des Types
        sal_Int32       nNumPrecRadix;  // indicating the radix, which is usually 2 or 10
        sal_Int32       nType;          // Datenbanktyp

        sal_Int16       nMaximumScale;  // Nachkommastellen
        sal_Int16       nMinimumScale;  // Min Nachkommastellen

        sal_Int16       nSearchType;    // kann nach dem Typen gesucht werden

        sal_Bool        bCurrency       : 1,    // Waehrung
                        bAutoIncrement  : 1,    // Ist es ein automatisch incrementierendes Feld
                        bNullable       : 1,    // Kann das Feld NULL annehmen
                        bCaseSensitive  : 1,    // Ist der Type Casesensitive
                        bUnsigned       : 1,    // Ist der Type Unsigned
                        bEmpty_1        : 1,    // for later use
                        bEmpty_2        : 1;

        OTypeInfo()
                :bCurrency(sal_False)
                ,bAutoIncrement(sal_False)
                ,bNullable(sal_True)
                ,bCaseSensitive(sal_False)
                ,bUnsigned(sal_False)
                ,nMaximumScale(0)
                ,nMinimumScale(0)
                ,nType(::com::sun::star::sdbc::DataType::OTHER)
                ,nPrecision(0)
                ,nSearchType(::com::sun::star::sdbc::ColumnSearch::FULL)
        {}
        sal_Bool operator == (const OTypeInfo& lh) const { return lh.nType == nType; }
        sal_Bool operator != (const OTypeInfo& lh) const { return lh.nType != nType; }
        inline ::rtl::OUString  getDBName() const { return aTypeName; }

    };

    typedef ::boost::shared_ptr<OTypeInfo>          TOTypeInfoSP;
    typedef ::std::multimap<sal_Int32,TOTypeInfoSP> OTypeInfoMap;
    /** return the most suitable typeinfo for a requested type
        @param  _rTypeInfo      contains a map of type to typeinfo
        @param  _nType          the requested type
        @param  _sTypeName      the typename
        @param  _sCreateParams  the create params
        @param  _nPrecision     the precision
        @param  _nScale         the scale
        @param  _bAutoIncrement if it is a auto increment
        @param  _brForceToType  true when type was found which has some differenes
    */
    TOTypeInfoSP getTypeInfoFromType(const OTypeInfoMap& _rTypeInfo,
                               sal_Int32 _nType,
                               const ::rtl::OUString& _sTypeName,
                               const ::rtl::OUString& _sCreateParams,
                               sal_Int32 _nPrecision,
                               sal_Int32 _nScale,
                               sal_Bool _bAutoIncrement,
                               sal_Bool& _brForceToType);
}

#endif // DBAUI_TYPEINFO_HXX

<commit_msg>INTEGRATION: CWS warnings01 (1.7.48); FILE MERGED 2006/05/29 11:19:12 sb 1.7.48.3: #i53898# Made code warning-free and/or compile at all after resync to SRC680m170. 2006/05/23 23:55:26 sb 1.7.48.2: RESYNC: (1.7-1.8); FILE MERGED 2006/03/24 15:36:17 fs 1.7.48.1: #i57457# warning-free code (unxlngi6/.pro + unxsoli4.pro)<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: TypeInfo.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 03:15:01 $
 *
 *  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 DBAUI_TYPEINFO_HXX
#define DBAUI_TYPEINFO_HXX

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_
#include <com/sun/star/sdbc/DataType.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_COLUMNSEARCH_HPP_
#include <com/sun/star/sdbc/ColumnSearch.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_
#include <com/sun/star/sdbc/ColumnValue.hpp>
#endif
#include <boost/shared_ptr.hpp>
#include <map>

namespace dbaui
{
//========================================================================
// Anhand dieser Ids werden die sprachabhaengigen ::rtl::OUString aus der Resource geholt
const sal_uInt16 TYPE_UNKNOWN   = 0;
const sal_uInt16 TYPE_TEXT      = 1;
const sal_uInt16 TYPE_NUMERIC   = 2;
const sal_uInt16 TYPE_DATETIME  = 3;
const sal_uInt16 TYPE_DATE      = 4;
const sal_uInt16 TYPE_TIME      = 5;
const sal_uInt16 TYPE_BOOL      = 6;
const sal_uInt16 TYPE_CURRENCY  = 7;
const sal_uInt16 TYPE_MEMO      = 8;
const sal_uInt16 TYPE_COUNTER   = 9;
const sal_uInt16 TYPE_IMAGE     = 10;
const sal_uInt16 TYPE_CHAR      = 11;
const sal_uInt16 TYPE_DECIMAL   = 12;
const sal_uInt16 TYPE_BINARY    = 13;
const sal_uInt16 TYPE_VARBINARY = 14;
const sal_uInt16 TYPE_BIGINT    = 15;
const sal_uInt16 TYPE_DOUBLE    = 16;
const sal_uInt16 TYPE_FLOAT     = 17;
const sal_uInt16 TYPE_REAL      = 18;
const sal_uInt16 TYPE_INTEGER   = 19;
const sal_uInt16 TYPE_SMALLINT  = 20;
const sal_uInt16 TYPE_TINYINT   = 21;
const sal_uInt16 TYPE_SQLNULL   = 22;
const sal_uInt16 TYPE_OBJECT    = 23;
const sal_uInt16 TYPE_DISTINCT  = 24;
const sal_uInt16 TYPE_STRUCT    = 25;
const sal_uInt16 TYPE_ARRAY     = 26;
const sal_uInt16 TYPE_BLOB      = 27;
const sal_uInt16 TYPE_CLOB      = 28;
const sal_uInt16 TYPE_REF       = 29;
const sal_uInt16 TYPE_OTHER     = 30;

    class OTypeInfo
    {
    public:
        ::rtl::OUString aUIName;        // the name which is the user see (a combination of resource text and aTypeName)
        ::rtl::OUString aTypeName;      // Name des Types in der Datenbank
        ::rtl::OUString aLiteralPrefix; // Prefix zum Quoten
        ::rtl::OUString aLiteralSuffix; // Suffix zum Quoten
        ::rtl::OUString aCreateParams;  // Parameter zum Erstellen
        ::rtl::OUString aLocalTypeName;

        sal_Int32       nPrecision;     // Laenge des Types
        sal_Int32       nType;          // Datenbanktyp

        sal_Int16       nMaximumScale;  // Nachkommastellen
        sal_Int16       nMinimumScale;  // Min Nachkommastellen

        sal_Int16       nSearchType;    // kann nach dem Typen gesucht werden

        sal_Bool        bCurrency       : 1,    // Waehrung
                        bAutoIncrement  : 1,    // Ist es ein automatisch incrementierendes Feld
                        bNullable       : 1,    // Kann das Feld NULL annehmen
                        bCaseSensitive  : 1,    // Ist der Type Casesensitive
                        bUnsigned       : 1;    // Ist der Type Unsigned

        OTypeInfo()
                :nPrecision(0)
                ,nType(::com::sun::star::sdbc::DataType::OTHER)
                ,nMaximumScale(0)
                ,nMinimumScale(0)
                ,nSearchType(::com::sun::star::sdbc::ColumnSearch::FULL)
                ,bCurrency(sal_False)
                ,bAutoIncrement(sal_False)
                ,bNullable(sal_True)
                ,bCaseSensitive(sal_False)
                ,bUnsigned(sal_False)
        {}
        sal_Bool operator == (const OTypeInfo& lh) const { return lh.nType == nType; }
        sal_Bool operator != (const OTypeInfo& lh) const { return lh.nType != nType; }
        inline ::rtl::OUString  getDBName() const { return aTypeName; }

    };

    typedef ::boost::shared_ptr<OTypeInfo>          TOTypeInfoSP;
    typedef ::std::multimap<sal_Int32,TOTypeInfoSP> OTypeInfoMap;
    /** return the most suitable typeinfo for a requested type
        @param  _rTypeInfo      contains a map of type to typeinfo
        @param  _nType          the requested type
        @param  _sTypeName      the typename
        @param  _sCreateParams  the create params
        @param  _nPrecision     the precision
        @param  _nScale         the scale
        @param  _bAutoIncrement if it is a auto increment
        @param  _brForceToType  true when type was found which has some differenes
    */
    TOTypeInfoSP getTypeInfoFromType(const OTypeInfoMap& _rTypeInfo,
                               sal_Int32 _nType,
                               const ::rtl::OUString& _sTypeName,
                               const ::rtl::OUString& _sCreateParams,
                               sal_Int32 _nPrecision,
                               sal_Int32 _nScale,
                               sal_Bool _bAutoIncrement,
                               sal_Bool& _brForceToType);
}

#endif // DBAUI_TYPEINFO_HXX

<|endoftext|>


<commit_before>// ConsoleApplication1.cpp : R\[ AvP[ṼGg |Cg`܂B
//

#include "stdafx.h"
#include <GL/glut.h>

#define CELLS_NO 51 //Z̑S̐
#define CELL_NEIGHBOR_NO 1 //Z̋ߖT
#define RULE_NO 90 //K
#define TIME_LIM 50 //
#define STATE_NO 2 //Ԑ
#define VIEW_SIZE 2.0 //ʂ̕

void drawSquare(double x, double y, double width, double height) //render square
{
	glBegin(GL_POLYGON);
	glVertex2d(x, y);
	glVertex2d(x + width, y);
	glVertex2d(x + width, y + height);
	glVertex2d(x, y + height);
	glEnd();
}

void drawCell(double x, double y, int state) //render single cell
{
	double width = VIEW_SIZE / CELLS_NO;
	switch (state) {
	case 1:
		glColor3d(1.0, 0.0, 0.0);
		break;
	default:
		glColor3d(0.0, 0.0, 1.0);
		break;
	}
	drawSquare(x, y, width, width);
}

void drawCellsRow(int cells[CELLS_NO], int time) //render cells row
{
	int i;
	double width = VIEW_SIZE / CELLS_NO;
	double x = -VIEW_SIZE / 2.0;
	double y = (TIME_LIM / 2.0 - time) * width;
	for (i = 0; i < CELLS_NO; i++) {
		drawCell(x, y, cells[i]);
		x += width;
	}
}
//TODO
//cell update by rule
int updateCell(int neighborCells[CELL_NEIGHBOR_NO * 2 + 1])
{
	int nextCell=0;
	for (int i = 0; i < CELL_NEIGHBOR_NO * 2 + 1; i++)
	{
		nextCell += neighborCells[i];
	}
	return nextCell% STATE_NO;
}

void display(void)
{
	glClear(GL_COLOR_BUFFER_BIT);
	int cells[CELLS_NO] = { 0 }; //current cells state
	int tmpCells[CELLS_NO] = { 0 }; //temporary cells array
	cells[(int)(CELLS_NO / 2.0)] = 1;
	for (int i = 0; i < TIME_LIM; i++) {
		drawCellsRow(cells, i);
		for (int j = 0; j < CELLS_NO; j++)
		{
			int neighborCells[CELL_NEIGHBOR_NO * 2 + 1] = { 0 };
			for (int l = 0; l < CELL_NEIGHBOR_NO * 2 + 1; l++)
			{
				neighborCells[l] = cells[(j + l - CELL_NEIGHBOR_NO) % CELLS_NO];
			}
			tmpCells[j] = updateCell(neighborCells);
		}
		for (int k = 0; k < CELLS_NO; k++)
		{
			cells[k] = tmpCells[k];
		}
	}
	glFlush();
}

void init(void)
{
	glClearColor(0.0, 0.0, 1.0, 1.0);
}

int main(int argc, char *argv[])
{
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_RGBA);
	glutCreateWindow(argv[0]);
	glutDisplayFunc(display);
	init();
	glutMainLoop();
	return 0;
}

<commit_msg>black and white<commit_after>// ConsoleApplication1.cpp : R\[ AvP[ṼGg |Cg`܂B
//

#include "stdafx.h"
#include <GL/glut.h>

#define CELLS_NO 51 //Z̑S̐
#define CELL_NEIGHBOR_NO 1 //Z̋ߖT
#define RULE_NO 90 //K
#define TIME_LIM 50 //
#define STATE_NO 2 //Ԑ
#define VIEW_SIZE 2.0 //ʂ̕

void drawSquare(double x, double y, double width, double height) //render square
{
	glBegin(GL_POLYGON);
	glVertex2d(x, y);
	glVertex2d(x + width, y);
	glVertex2d(x + width, y + height);
	glVertex2d(x, y + height);
	glEnd();
}

void drawCell(double x, double y, int state) //render single cell
{
	double width = VIEW_SIZE / CELLS_NO;
	glColor3d((STATE_NO - 1 - state) / (double)(STATE_NO - 1), (STATE_NO - 1 - state) / (double)(STATE_NO - 1), (STATE_NO - 1 - state) / (double)(STATE_NO - 1));
	drawSquare(x, y, width, width);
}

void drawCellsRow(int cells[CELLS_NO], int time) //render cells row
{
	int i;
	double width = VIEW_SIZE / CELLS_NO;
	double x = -VIEW_SIZE / 2.0;
	double y = (TIME_LIM / 2.0 - time) * width;
	for (i = 0; i < CELLS_NO; i++) {
		drawCell(x, y, cells[i]);
		x += width;
	}
}
//TODO
//cell update by rule
int updateCell(int neighborCells[CELL_NEIGHBOR_NO * 2 + 1])
{
	int nextCell = 0;
	for (int i = 0; i < CELL_NEIGHBOR_NO * 2 + 1; i++)
	{
		nextCell += neighborCells[i];
	}
	return nextCell% STATE_NO;
}

void display(void)
{
	glClear(GL_COLOR_BUFFER_BIT);
	int cells[CELLS_NO] = { 0 }; //current cells state
	int tmpCells[CELLS_NO] = { 0 }; //temporary cells array
	cells[(int)(CELLS_NO / 2.0)] = 1;
	for (int i = 0; i < TIME_LIM; i++) {
		drawCellsRow(cells, i);
		for (int j = 0; j < CELLS_NO; j++)
		{
			int neighborCells[CELL_NEIGHBOR_NO * 2 + 1] = { 0 };
			for (int l = 0; l < CELL_NEIGHBOR_NO * 2 + 1; l++)
			{
				neighborCells[l] = cells[(j + l - CELL_NEIGHBOR_NO) % CELLS_NO];
			}
			tmpCells[j] = updateCell(neighborCells);
		}
		for (int k = 0; k < CELLS_NO; k++)
		{
			cells[k] = tmpCells[k];
		}
	}
	glFlush();
}

void init(void)
{
	glClearColor(0.0, 0.0, 1.0, 1.0);
}

int main(int argc, char *argv[])
{
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_RGBA);
	glutCreateWindow(argv[0]);
	glutDisplayFunc(display);
	init();
	glutMainLoop();
	return 0;
}

<|endoftext|>