<commit_before>/*
 * Copyright (C) 2011 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 * 1. Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. AND ITS CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GOOGLE INC.
 * OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "core/xml/XMLErrors.h"

#include "HTMLNames.h"
#include "SVGNames.h"
#include "core/dom/Document.h"
#include "core/dom/Element.h"
#include "core/dom/Text.h"
#include "wtf/text/WTFString.h"

namespace WebCore {

using namespace HTMLNames;

const int maxErrors = 25;

XMLErrors::XMLErrors(Document* document)
    : m_document(document)
    , m_errorCount(0)
    , m_lastErrorPosition(TextPosition::belowRangePosition())
{
}

void XMLErrors::handleError(ErrorType type, const char* message, int lineNumber, int columnNumber)
{
    handleError(type, message, TextPosition(OrdinalNumber::fromOneBasedInt(lineNumber), OrdinalNumber::fromOneBasedInt(columnNumber)));
}

void XMLErrors::handleError(ErrorType type, const char* message, TextPosition position)
{
    if (type == fatal || (m_errorCount < maxErrors && m_lastErrorPosition.m_line != position.m_line && m_lastErrorPosition.m_column != position.m_column)) {
        switch (type) {
        case warning:
            appendErrorMessage("warning", position, message);
            break;
        case fatal:
        case nonFatal:
            appendErrorMessage("error", position, message);
        }

        m_lastErrorPosition = position;
        ++m_errorCount;
    }
}

void XMLErrors::appendErrorMessage(const String& typeString, TextPosition position, const char* message)
{
    // <typeString> on line <lineNumber> at column <columnNumber>: <message>
    m_errorMessages.append(typeString);
    m_errorMessages.appendLiteral(" on line ");
    m_errorMessages.appendNumber(position.m_line.oneBasedInt());
    m_errorMessages.appendLiteral(" at column ");
    m_errorMessages.appendNumber(position.m_column.oneBasedInt());
    m_errorMessages.appendLiteral(": ");
    m_errorMessages.append(message);
}

static inline PassRefPtr<Element> createXHTMLParserErrorHeader(Document* doc, const String& errorMessages)
{
    RefPtr<Element> reportElement = doc->createElement(QualifiedName(nullAtom, "parsererror", xhtmlNamespaceURI), true);

    Vector<Attribute> reportAttributes;
    reportAttributes.append(Attribute(styleAttr, "display: block; white-space: pre; border: 2px solid #c77; padding: 0 1em 0 1em; margin: 1em; background-color: #fdd; color: black"));
    reportElement->parserSetAttributes(reportAttributes);

    RefPtr<Element> h3 = doc->createElement(h3Tag, true);
    reportElement->parserAppendChild(h3.get());
    h3->parserAppendChild(doc->createTextNode("This page contains the following errors:"));

    RefPtr<Element> fixed = doc->createElement(divTag, true);
    Vector<Attribute> fixedAttributes;
    fixedAttributes.append(Attribute(styleAttr, "font-family:monospace;font-size:12px"));
    fixed->parserSetAttributes(fixedAttributes);
    reportElement->parserAppendChild(fixed.get());

    fixed->parserAppendChild(doc->createTextNode(errorMessages));

    h3 = doc->createElement(h3Tag, true);
    reportElement->parserAppendChild(h3.get());
    h3->parserAppendChild(doc->createTextNode("Below is a rendering of the page up to the first error."));

    return reportElement.release();
}

void XMLErrors::insertErrorMessageBlock()
{
    // One or more errors occurred during parsing of the code. Display an error block to the user above
    // the normal content (the DOM tree is created manually and includes line/col info regarding
    // where the errors are located)

    // Create elements for display
    RefPtr<Element> documentElement = m_document->documentElement();
    if (!documentElement) {
        RefPtr<Element> rootElement = m_document->createElement(htmlTag, true);
        RefPtr<Element> body = m_document->createElement(bodyTag, true);
        rootElement->parserAppendChild(body);
        m_document->parserAppendChild(rootElement);
        rootElement->lazyAttach();
        documentElement = body.get();
    } else if (documentElement->namespaceURI() == SVGNames::svgNamespaceURI) {
        RefPtr<Element> rootElement = m_document->createElement(htmlTag, true);
        RefPtr<Element> body = m_document->createElement(bodyTag, true);
        rootElement->parserAppendChild(body);

        if (documentElement->attached())
            documentElement->detach();
        m_document->parserRemoveChild(documentElement.get());

        body->parserAppendChild(documentElement);
        m_document->parserAppendChild(rootElement);
        rootElement->lazyAttach();

        documentElement = body.get();
    }

    String errorMessages = m_errorMessages.toString();
    RefPtr<Element> reportElement = createXHTMLParserErrorHeader(m_document, errorMessages);

    if (m_document->transformSourceDocument()) {
        Vector<Attribute> attributes;
        attributes.append(Attribute(styleAttr, "white-space: normal"));
        RefPtr<Element> paragraph = m_document->createElement(pTag, true);
        paragraph->parserSetAttributes(attributes);
        paragraph->parserAppendChild(m_document->createTextNode("This document was created as the result of an XSL transformation. The line and column numbers given are from the transformed result."));
        reportElement->parserAppendChild(paragraph.release());
    }

    Node* firstChild = documentElement->firstChild();
    if (firstChild)
        documentElement->parserInsertBefore(reportElement, documentElement->firstChild());
    else
        documentElement->parserAppendChild(reportElement);

    reportElement->lazyAttach();

    // FIXME: Why do we need to call this manually?
    m_document->updateStyleIfNeeded();
}

} // namespace WebCore
<commit_msg>XMLErrors::insertErrorMessageBlock does not need to call detach<commit_after>/*
 * Copyright (C) 2011 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 * 1. Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. AND ITS CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GOOGLE INC.
 * OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "core/xml/XMLErrors.h"

#include "HTMLNames.h"
#include "SVGNames.h"
#include "core/dom/Document.h"
#include "core/dom/Element.h"
#include "core/dom/Text.h"
#include "wtf/text/WTFString.h"

namespace WebCore {

using namespace HTMLNames;

const int maxErrors = 25;

XMLErrors::XMLErrors(Document* document)
    : m_document(document)
    , m_errorCount(0)
    , m_lastErrorPosition(TextPosition::belowRangePosition())
{
}

void XMLErrors::handleError(ErrorType type, const char* message, int lineNumber, int columnNumber)
{
    handleError(type, message, TextPosition(OrdinalNumber::fromOneBasedInt(lineNumber), OrdinalNumber::fromOneBasedInt(columnNumber)));
}

void XMLErrors::handleError(ErrorType type, const char* message, TextPosition position)
{
    if (type == fatal || (m_errorCount < maxErrors && m_lastErrorPosition.m_line != position.m_line && m_lastErrorPosition.m_column != position.m_column)) {
        switch (type) {
        case warning:
            appendErrorMessage("warning", position, message);
            break;
        case fatal:
        case nonFatal:
            appendErrorMessage("error", position, message);
        }

        m_lastErrorPosition = position;
        ++m_errorCount;
    }
}

void XMLErrors::appendErrorMessage(const String& typeString, TextPosition position, const char* message)
{
    // <typeString> on line <lineNumber> at column <columnNumber>: <message>
    m_errorMessages.append(typeString);
    m_errorMessages.appendLiteral(" on line ");
    m_errorMessages.appendNumber(position.m_line.oneBasedInt());
    m_errorMessages.appendLiteral(" at column ");
    m_errorMessages.appendNumber(position.m_column.oneBasedInt());
    m_errorMessages.appendLiteral(": ");
    m_errorMessages.append(message);
}

static inline PassRefPtr<Element> createXHTMLParserErrorHeader(Document* doc, const String& errorMessages)
{
    RefPtr<Element> reportElement = doc->createElement(QualifiedName(nullAtom, "parsererror", xhtmlNamespaceURI), true);

    Vector<Attribute> reportAttributes;
    reportAttributes.append(Attribute(styleAttr, "display: block; white-space: pre; border: 2px solid #c77; padding: 0 1em 0 1em; margin: 1em; background-color: #fdd; color: black"));
    reportElement->parserSetAttributes(reportAttributes);

    RefPtr<Element> h3 = doc->createElement(h3Tag, true);
    reportElement->parserAppendChild(h3.get());
    h3->parserAppendChild(doc->createTextNode("This page contains the following errors:"));

    RefPtr<Element> fixed = doc->createElement(divTag, true);
    Vector<Attribute> fixedAttributes;
    fixedAttributes.append(Attribute(styleAttr, "font-family:monospace;font-size:12px"));
    fixed->parserSetAttributes(fixedAttributes);
    reportElement->parserAppendChild(fixed.get());

    fixed->parserAppendChild(doc->createTextNode(errorMessages));

    h3 = doc->createElement(h3Tag, true);
    reportElement->parserAppendChild(h3.get());
    h3->parserAppendChild(doc->createTextNode("Below is a rendering of the page up to the first error."));

    return reportElement.release();
}

void XMLErrors::insertErrorMessageBlock()
{
    // One or more errors occurred during parsing of the code. Display an error block to the user above
    // the normal content (the DOM tree is created manually and includes line/col info regarding
    // where the errors are located)

    // Create elements for display
    RefPtr<Element> documentElement = m_document->documentElement();
    if (!documentElement) {
        RefPtr<Element> rootElement = m_document->createElement(htmlTag, true);
        RefPtr<Element> body = m_document->createElement(bodyTag, true);
        rootElement->parserAppendChild(body);
        m_document->parserAppendChild(rootElement);
        rootElement->lazyAttach();
        documentElement = body.get();
    } else if (documentElement->namespaceURI() == SVGNames::svgNamespaceURI) {
        RefPtr<Element> rootElement = m_document->createElement(htmlTag, true);
        RefPtr<Element> body = m_document->createElement(bodyTag, true);
        rootElement->parserAppendChild(body);

        m_document->parserRemoveChild(documentElement.get());

        body->parserAppendChild(documentElement);
        m_document->parserAppendChild(rootElement);
        rootElement->lazyAttach();

        documentElement = body.get();
    }

    String errorMessages = m_errorMessages.toString();
    RefPtr<Element> reportElement = createXHTMLParserErrorHeader(m_document, errorMessages);

    if (m_document->transformSourceDocument()) {
        Vector<Attribute> attributes;
        attributes.append(Attribute(styleAttr, "white-space: normal"));
        RefPtr<Element> paragraph = m_document->createElement(pTag, true);
        paragraph->parserSetAttributes(attributes);
        paragraph->parserAppendChild(m_document->createTextNode("This document was created as the result of an XSL transformation. The line and column numbers given are from the transformed result."));
        reportElement->parserAppendChild(paragraph.release());
    }

    Node* firstChild = documentElement->firstChild();
    if (firstChild)
        documentElement->parserInsertBefore(reportElement, documentElement->firstChild());
    else
        documentElement->parserAppendChild(reportElement);

    reportElement->lazyAttach();

    // FIXME: Why do we need to call this manually?
    m_document->updateStyleIfNeeded();
}

} // namespace WebCore
<|endoftext|>


<commit_before>#include <core/stdafx.h>
#include <core/smartview/AdditionalRenEntryIDs.h>
#include <core/interpret/flags.h>
#include <core/mapi/extraPropTags.h>

namespace smartview
{
	PersistElement::PersistElement(std::shared_ptr<binaryParser> parser)
	{
		wElementID = blockT<WORD>::parse(parser);
		wElementDataSize = blockT<WORD>::parse(parser);
		if (wElementID != PersistElement::ELEMENT_SENTINEL)
		{
			// Since this is a word, the size will never be too large
			lpbElementData = blockBytes::parse(parser, wElementDataSize->getData());
		}
	}

	void AdditionalRenEntryIDs::Parse()
	{
		WORD wPersistDataCount = 0;
		// Run through the parser once to count the number of PersistData structs
		while (m_Parser->RemainingBytes() >= 2 * sizeof(WORD))
		{
			const auto& wPersistID = blockT<WORD>::parse(m_Parser);
			const auto& wDataElementSize = blockT<WORD>::parse(m_Parser);
			// Must have at least wDataElementSize bytes left to be a valid data element
			if (m_Parser->RemainingBytes() < wDataElementSize->getData()) break;

			m_Parser->advance(wDataElementSize->getData());
			wPersistDataCount++;
			if (wPersistID == PersistData::PERISIST_SENTINEL) break;
		}

		// Now we parse for real
		m_Parser->rewind();

		if (wPersistDataCount && wPersistDataCount < _MaxEntriesSmall)
		{
			m_ppdPersistData.reserve(wPersistDataCount);
			for (WORD iPersistElement = 0; iPersistElement < wPersistDataCount; iPersistElement++)
			{
				m_ppdPersistData.emplace_back(std::make_shared<PersistData>(m_Parser));
			}
		}
	}

	PersistData::PersistData(std::shared_ptr<binaryParser> parser)
	{
		WORD wDataElementCount = 0;
		wPersistID = blockT<WORD>::parse(parser);
		wDataElementsSize = blockT<WORD>::parse(parser);

		if (wPersistID != PERISIST_SENTINEL && parser->RemainingBytes() >= wDataElementsSize->getData())
		{
			// Build a new parser to preread and count our elements
			// This new parser will only contain as much space as suggested in wDataElementsSize
			auto DataElementParser =
				std::make_shared<binaryParser>(wDataElementsSize->getData(), parser->GetCurrentAddress());
			for (;;)
			{
				if (DataElementParser->RemainingBytes() < 2 * sizeof(WORD)) break;
				const auto& wElementID = blockT<WORD>::parse(DataElementParser);
				const auto& wElementDataSize = blockT<WORD>::parse(DataElementParser);
				// Must have at least wElementDataSize bytes left to be a valid element data
				if (DataElementParser->RemainingBytes() < wElementDataSize->getData()) break;

				DataElementParser->advance(wElementDataSize->getData());
				wDataElementCount++;
				if (wElementID == PersistElement::ELEMENT_SENTINEL) break;
			}
		}

		if (wDataElementCount && wDataElementCount < _MaxEntriesSmall)
		{
			ppeDataElement.reserve(wDataElementCount);
			for (WORD iDataElement = 0; iDataElement < wDataElementCount; iDataElement++)
			{
				ppeDataElement.emplace_back(std::make_shared<PersistElement>(parser));
			}
		}

		// We'll trust wDataElementsSize to dictate our record size.
		// Count the 2 WORD size header fields too.
		const auto cbRecordSize = wDataElementsSize->getData() + sizeof(WORD) * 2;

		// Junk data remains - can't use GetRemainingData here since it would eat the whole buffer
		if (parser->GetCurrentOffset() < cbRecordSize)
		{
			JunkData = blockBytes::parse(parser, cbRecordSize - parser->GetCurrentOffset());
		}
	}

	void AdditionalRenEntryIDs::ParseBlocks()
	{
		setRoot(L"Additional Ren Entry IDs\r\n");
		addHeader(L"PersistDataCount = %1!d!", m_ppdPersistData.size());

		if (!m_ppdPersistData.empty())
		{
			auto iPersistElement = 0;
			for (const auto& persistData : m_ppdPersistData)
			{
				terminateBlock();
				addBlankLine();
				auto element = std::make_shared<block>();
				element->setText(L"Persist Element %1!d!:\r\n", iPersistElement);
				element->addChild(
					persistData->wPersistID,
					L"PersistID = 0x%1!04X! = %2!ws!\r\n",
					persistData->wPersistID->getData(),
					flags::InterpretFlags(flagPersistID, persistData->wPersistID->getData()).c_str());
				element->addChild(
					persistData->wDataElementsSize,
					L"DataElementsSize = 0x%1!04X!",
					persistData->wDataElementsSize->getData());

				if (!persistData->ppeDataElement.empty())
				{
					auto iDataElement = 0;
					for (const auto& dataElement : persistData->ppeDataElement)
					{
						element->terminateBlock();
						element->addHeader(L"DataElement: %1!d!\r\n", iDataElement);

						element->addChild(
							dataElement->wElementID,
							L"\tElementID = 0x%1!04X! = %2!ws!\r\n",
							dataElement->wElementID->getData(),
							flags::InterpretFlags(flagElementID, dataElement->wElementID->getData()).c_str());

						element->addChild(
							dataElement->wElementDataSize,
							L"\tElementDataSize = 0x%1!04X!\r\n",
							dataElement->wElementDataSize->getData());

						element->addHeader(L"\tElementData = ");
						element->addChild(dataElement->lpbElementData);
						iDataElement++;
					}
				}

				if (!persistData->JunkData->empty())
				{
					element->terminateBlock();
					element->addHeader(L"Unparsed data size = 0x%1!08X!\r\n", persistData->JunkData->size());
					element->addChild(persistData->JunkData);
				}

				addChild(element);
				iPersistElement++;
			}
		}
	}
} // namespace smartview<commit_msg>Slight tweaks to AdditionalRenEntryIDs<commit_after>#include <core/stdafx.h>
#include <core/smartview/AdditionalRenEntryIDs.h>
#include <core/interpret/flags.h>
#include <core/mapi/extraPropTags.h>

namespace smartview
{
	PersistElement::PersistElement(std::shared_ptr<binaryParser> parser)
	{
		wElementID = blockT<WORD>::parse(parser);
		wElementDataSize = blockT<WORD>::parse(parser);
		if (wElementID != PersistElement::ELEMENT_SENTINEL)
		{
			// Since this is a word, the size will never be too large
			lpbElementData = blockBytes::parse(parser, wElementDataSize->getData());
		}
	}

	void AdditionalRenEntryIDs::Parse()
	{
		WORD wPersistDataCount = 0;
		// Run through the parser once to count the number of PersistData structs
		while (m_Parser->RemainingBytes() >= 2 * sizeof(WORD))
		{
			const auto& wPersistID = blockT<WORD>::parse(m_Parser);
			const auto& wDataElementSize = blockT<WORD>::parse(m_Parser);
			// Must have at least wDataElementSize bytes left to be a valid data element
			if (m_Parser->RemainingBytes() < *wDataElementSize) break;

			m_Parser->advance(*wDataElementSize);
			wPersistDataCount++;
			if (wPersistID == PersistData::PERISIST_SENTINEL) break;
		}

		// Now we parse for real
		m_Parser->rewind();

		if (wPersistDataCount && wPersistDataCount < _MaxEntriesSmall)
		{
			m_ppdPersistData.reserve(wPersistDataCount);
			for (WORD iPersistElement = 0; iPersistElement < wPersistDataCount; iPersistElement++)
			{
				m_ppdPersistData.emplace_back(std::make_shared<PersistData>(m_Parser));
			}
		}
	}

	PersistData::PersistData(std::shared_ptr<binaryParser> parser)
	{
		WORD wDataElementCount = 0;
		wPersistID = blockT<WORD>::parse(parser);
		wDataElementsSize = blockT<WORD>::parse(parser);

		if (wPersistID != PERISIST_SENTINEL && parser->RemainingBytes() >= *wDataElementsSize)
		{
			// Build a new parser to preread and count our elements
			// This new parser will only contain as much space as suggested in wDataElementsSize
			auto DataElementParser = std::make_shared<binaryParser>(*wDataElementsSize, parser->GetCurrentAddress());
			for (;;)
			{
				if (DataElementParser->RemainingBytes() < 2 * sizeof(WORD)) break;
				const auto& wElementID = blockT<WORD>::parse(DataElementParser);
				const auto& wElementDataSize = blockT<WORD>::parse(DataElementParser);
				// Must have at least wElementDataSize bytes left to be a valid element data
				if (DataElementParser->RemainingBytes() < *wElementDataSize) break;

				DataElementParser->advance(*wElementDataSize);
				wDataElementCount++;
				if (wElementID == PersistElement::ELEMENT_SENTINEL) break;
			}
		}

		if (wDataElementCount && wDataElementCount < _MaxEntriesSmall)
		{
			ppeDataElement.reserve(wDataElementCount);
			for (WORD iDataElement = 0; iDataElement < wDataElementCount; iDataElement++)
			{
				ppeDataElement.emplace_back(std::make_shared<PersistElement>(parser));
			}
		}

		// We'll trust wDataElementsSize to dictate our record size.
		// Count the 2 WORD size header fields too.
		const auto cbRecordSize = *wDataElementsSize + sizeof(WORD) * 2;

		// Junk data remains - can't use GetRemainingData here since it would eat the whole buffer
		if (parser->GetCurrentOffset() < cbRecordSize)
		{
			JunkData = blockBytes::parse(parser, cbRecordSize - parser->GetCurrentOffset());
		}
	}

	void AdditionalRenEntryIDs::ParseBlocks()
	{
		setRoot(L"Additional Ren Entry IDs\r\n");
		addHeader(L"PersistDataCount = %1!d!", m_ppdPersistData.size());

		if (!m_ppdPersistData.empty())
		{
			auto iPersistElement = 0;
			for (const auto& persistData : m_ppdPersistData)
			{
				terminateBlock();
				addBlankLine();
				auto element = std::make_shared<block>();
				addChild(element);

				element->setText(L"Persist Element %1!d!:\r\n", iPersistElement);
				element->addChild(
					persistData->wPersistID,
					L"PersistID = 0x%1!04X! = %2!ws!\r\n",
					persistData->wPersistID->getData(),
					flags::InterpretFlags(flagPersistID, persistData->wPersistID->getData()).c_str());
				element->addChild(
					persistData->wDataElementsSize,
					L"DataElementsSize = 0x%1!04X!",
					persistData->wDataElementsSize->getData());

				if (!persistData->ppeDataElement.empty())
				{
					auto iDataElement = 0;
					for (const auto& dataElement : persistData->ppeDataElement)
					{
						element->terminateBlock();
						element->addHeader(L"DataElement: %1!d!\r\n", iDataElement);

						element->addChild(
							dataElement->wElementID,
							L"\tElementID = 0x%1!04X! = %2!ws!\r\n",
							dataElement->wElementID->getData(),
							flags::InterpretFlags(flagElementID, dataElement->wElementID->getData()).c_str());

						element->addChild(
							dataElement->wElementDataSize,
							L"\tElementDataSize = 0x%1!04X!\r\n",
							dataElement->wElementDataSize->getData());

						element->addHeader(L"\tElementData = ");
						element->addChild(dataElement->lpbElementData);
						iDataElement++;
					}
				}

				if (!persistData->JunkData->empty())
				{
					element->terminateBlock();
					element->addHeader(L"Unparsed data size = 0x%1!08X!\r\n", persistData->JunkData->size());
					element->addChild(persistData->JunkData);
				}

				iPersistElement++;
			}
		}
	}
} // namespace smartview<|endoftext|>


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

#include "Application.hpp"

#include <QMessageBox>

#include <QDir>
#include <QFileInfo>
#include <QFileInfoList>

Application::Application(int& argc, char** argv) :
	QApplication(argc, argv)
{
	if (argc > 1) {
		QStringList args{QCoreApplication::arguments()};

		if (args[1] == "compile") {
			if (args[2] == "theme") {
				if (!compile(args[3], args[4] + QLatin1String(".snthm")))
					QMessageBox::critical(nullptr,
										  QApplication::tr("Error"),
										  QApplication::tr("Failed to compile theme: ") + m_errors);
				else
					QMessageBox::information(nullptr,
											 QApplication::tr("Success"),
											 QApplication::tr("Theme compiled with success"));
			}
			else
				QMessageBox::critical(nullptr,
									  QApplication::tr("Error"),
									  QApplication::tr("%1 is not a valid Sielo format").arg(args[2]));
		}
		else if (args[1] == "decompile") {
			if (!decompile(args[2], args[3]))
				QMessageBox::critical(nullptr,
									  QApplication::tr("Error"),
									  QApplication::tr("Failed to decompile: ") + m_errors);
			else if (args.count() == 5) {
				QMessageBox::information(nullptr, QApplication::tr("Success"), args[4]);
			}
		}
		else
			QMessageBox::critical(nullptr,
								  QApplication::tr("Error"),
								  QApplication::tr("The action you want to do is unknown..."));
	}

	QCoreApplication::instance()->exit(0);
}

Application::~Application()
{
	// Empty
}

bool Application::compile(const QString& srcFolder, const QString& fileDestination)
{
	QDir src{srcFolder};

	if (!src.exists()) {
		m_errors = QApplication::tr("The folder to compile doesn't exist.");
		return false;
	}

	m_file.setFileName(fileDestination);

	if (!m_file.open(QIODevice::WriteOnly)) {
		m_errors = QApplication::tr("The destination file can't be open.");
		return false;
	}

	m_stream.setDevice(&m_file);

	bool success{compress(srcFolder, "")};

	m_file.close();

	return success;

}

bool Application::decompile(const QString& srcFile, const QString& filesDestination)
{
	QFile src{srcFile};
	QFileInfo name{};

	if (!src.exists()) {
		m_errors = QApplication::tr("Sources to decompile don't exists.");
		return false;
	}

	QDir dir{};

	if (!dir.mkpath(filesDestination)) {
		m_errors = QApplication::tr("Can't create folder to receive decompiled files");
		return false;
	}

	if (!src.open(QIODevice::ReadOnly)) {
		m_errors = QApplication::tr("Failed to read compiled file.");
		return false;
	}

	QDataStream stream{&src};

	while (!stream.atEnd()) {
		QString fileName{};
		QByteArray data{};

		stream >> fileName >> data;

		QString subFolder{};

		for (int i{fileName.length() - 1}; i > 0; --i) {
			if ((QString(fileName[i]) == QString("\\")) || (QString(fileName[i]) == QString("/"))) {
				subFolder = fileName.left(i);
				dir.mkpath(filesDestination + QLatin1Char('/') + subFolder);

				break;
			}
		}

		QFile outFile{filesDestination + QLatin1Char('/') + fileName};

		if (!outFile.open(QIODevice::WriteOnly)) {
			src.close();
			m_errors = QApplication::tr("Failed to write decompiled files.");
			return false;
		}

		outFile.write(qUncompress(data));
		outFile.close();
	}

	src.close();

	return true;
}

bool Application::compress(const QString& srcFolder, const QString& prefexe)
{
	QDir dir{srcFolder};

	dir.setFilter(QDir::NoDotAndDotDot | QDir::Dirs);

	QFileInfoList folderList{dir.entryInfoList()};

	for (int i{0}; i < folderList.length(); ++i) {
		QString folderName{folderList[i].fileName()};
		QString folderPath{dir.absolutePath() + QLatin1Char('/') + folderName};
		QString newPrefexe{prefexe + QLatin1Char('/') + folderName};

		compress(folderPath, newPrefexe);
	}

	dir.setFilter(QDir::NoDotAndDotDot | QDir::Files);

	QFileInfoList filesList{dir.entryInfoList()};

	for (int i{0}; i < filesList.length(); ++i) {
		QFile file{dir.absolutePath() + QLatin1Char('/') + filesList[i].fileName()};

		if (!file.open(QIODevice::ReadOnly)) {
			m_errors = QApplication::tr("Failed to read ") + filesList[i].fileName();
			return false;
		}

		m_stream << QString(prefexe + QLatin1Char('/') + filesList[i].fileName());
		m_stream << qCompress(file.readAll());

		file.close();
	}

	return true;
}<commit_msg>[Add] An help argument to sielo-compiler<commit_after>/***********************************************************************************
** MIT License                                                                    **
**                                                                                **
** Copyright (c) 2018 Victor DENIS (victordenis01@gmail.com)                      **
**                                                                                **
** Permission is hereby granted, free of charge, to any person obtaining a copy   **
** of this software and associated documentation files (the "Software"), to deal  **
** in the Software without restriction, including without limitation the rights   **
** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell      **
** copies of the Software, and to permit persons to whom the Software is          **
** furnished to do so, subject to the following conditions:                       **
**                                                                                **
** The above copyright notice and this permission notice shall be included in all **
** copies or substantial portions of the Software.                                **
**                                                                                **
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR     **
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,       **
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE    **
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER         **
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,  **
** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE  **
** SOFTWARE.                                                                      **
***********************************************************************************/

#include "Application.hpp"

#include <QMessageBox>

#include <QDir>
#include <QFileInfo>
#include <QFileInfoList>

#include <iostream>

Application::Application(int& argc, char** argv) :
	QApplication(argc, argv)
{
	if (argc > 1) {
		QStringList args{QCoreApplication::arguments()};

		if (args[1] == "compile") {
			if (args[2] == "theme") {
				if (!compile(args[3], args[4] + QLatin1String(".snthm")))
					QMessageBox::critical(nullptr,
										  QApplication::tr("Error"),
										  QApplication::tr("Failed to compile theme: ") + m_errors);
				else
					QMessageBox::information(nullptr,
											 QApplication::tr("Success"),
											 QApplication::tr("Theme compiled with success"));
			}
			else
				QMessageBox::critical(nullptr,
									  QApplication::tr("Error"),
									  QApplication::tr("%1 is not a valid Sielo format").arg(args[2]));
		}
		else if (args[1] == "decompile") {
			if (!decompile(args[2], args[3]))
				QMessageBox::critical(nullptr,
									  QApplication::tr("Error"),
									  QApplication::tr("Failed to decompile: ") + m_errors);
			else if (args.count() == 5) {
				QMessageBox::information(nullptr, QApplication::tr("Success"), args[4]);
			}
		}
		else if (args[1] == "-h" || args[1] == "--help") {
			std::cout << QApplication::tr("Their is two ways to use this command:").toStdString() << std::endl << std::endl;
			std::cout << QApplication::tr("$ sielo-compiler compile theme (path to the theme folder) (name of the theme)").toStdString() << std::endl;
			std::cout << " -> " << QApplication::tr("This will compile your theme in a basic \".sntm\" file. The output is in the theme folder directory.").toStdString() << std::endl << std::endl;
			std::cout << QApplication::tr("$ sielo-compiler decompile (path to the theme file) (path where the theme must be decompiled)").toStdString() << std::endl;
			std::cout << " -> " << QApplication::tr("This will decompile your theme in the directory you choose.").toStdString() << std::endl << std::endl;

		}
		else
			QMessageBox::critical(nullptr,
								  QApplication::tr("Error"),
								  QApplication::tr("The action you want to do is unknown..."));
	}

	QCoreApplication::instance()->exit(0);
}

Application::~Application()
{
	// Empty
}

bool Application::compile(const QString& srcFolder, const QString& fileDestination)
{
	QDir src{srcFolder};

	if (!src.exists()) {
		m_errors = QApplication::tr("The folder to compile doesn't exist.");
		return false;
	}

	m_file.setFileName(fileDestination);

	if (!m_file.open(QIODevice::WriteOnly)) {
		m_errors = QApplication::tr("The destination file can't be open.");
		return false;
	}

	m_stream.setDevice(&m_file);

	bool success{compress(srcFolder, "")};

	m_file.close();

	return success;

}

bool Application::decompile(const QString& srcFile, const QString& filesDestination)
{
	QFile src{srcFile};
	QFileInfo name{};

	if (!src.exists()) {
		m_errors = QApplication::tr("Sources to decompile don't exists.");
		return false;
	}

	QDir dir{};

	if (!dir.mkpath(filesDestination)) {
		m_errors = QApplication::tr("Can't create folder to receive decompiled files");
		return false;
	}

	if (!src.open(QIODevice::ReadOnly)) {
		m_errors = QApplication::tr("Failed to read compiled file.");
		return false;
	}

	QDataStream stream{&src};

	while (!stream.atEnd()) {
		QString fileName{};
		QByteArray data{};

		stream >> fileName >> data;

		QString subFolder{};

		for (int i{fileName.length() - 1}; i > 0; --i) {
			if ((QString(fileName[i]) == QString("\\")) || (QString(fileName[i]) == QString("/"))) {
				subFolder = fileName.left(i);
				dir.mkpath(filesDestination + QLatin1Char('/') + subFolder);

				break;
			}
		}

		QFile outFile{filesDestination + QLatin1Char('/') + fileName};

		if (!outFile.open(QIODevice::WriteOnly)) {
			src.close();
			m_errors = QApplication::tr("Failed to write decompiled files.");
			return false;
		}

		outFile.write(qUncompress(data));
		outFile.close();
	}

	src.close();

	return true;
}

bool Application::compress(const QString& srcFolder, const QString& prefexe)
{
	QDir dir{srcFolder};

	dir.setFilter(QDir::NoDotAndDotDot | QDir::Dirs);

	QFileInfoList folderList{dir.entryInfoList()};

	for (int i{0}; i < folderList.length(); ++i) {
		QString folderName{folderList[i].fileName()};
		QString folderPath{dir.absolutePath() + QLatin1Char('/') + folderName};
		QString newPrefexe{prefexe + QLatin1Char('/') + folderName};

		compress(folderPath, newPrefexe);
	}

	dir.setFilter(QDir::NoDotAndDotDot | QDir::Files);

	QFileInfoList filesList{dir.entryInfoList()};

	for (int i{0}; i < filesList.length(); ++i) {
		QFile file{dir.absolutePath() + QLatin1Char('/') + filesList[i].fileName()};

		if (!file.open(QIODevice::ReadOnly)) {
			m_errors = QApplication::tr("Failed to read ") + filesList[i].fileName();
			return false;
		}

		m_stream << QString(prefexe + QLatin1Char('/') + filesList[i].fileName());
		m_stream << qCompress(file.readAll());

		file.close();
	}

	return true;
}<|endoftext|>


<commit_before>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/framework/register_types.h"

#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/logging.h"

namespace tensorflow {

bool DeviceType::operator<(const DeviceType& other) const {
  return type_ < other.type_;
}

bool DeviceType::operator==(const DeviceType& other) const {
  return type_ == other.type_;
}

std::ostream& operator<<(std::ostream& os, const DeviceType& d) {
  os << d.type();
  return os;
}

const char* const DEVICE_CPU = "CPU";
const char* const DEVICE_GPU = "GPU";
const char* const DEVICE_SYCL = "SYCL";

string DataTypeString(DataType dtype) {
  if (IsRefType(dtype)) {
    DataType non_ref = static_cast<DataType>(dtype - kDataTypeRefOffset);
    return strings::StrCat(DataTypeString(non_ref), "_ref");
  }
  switch (dtype) {
    case DT_INVALID:
      return "INVALID";
    case DT_FLOAT:
      return "float";
    case DT_DOUBLE:
      return "double";
    case DT_INT32:
      return "int32";
    case DT_UINT8:
      return "uint8";
    case DT_UINT16:
      return "uint16";
    case DT_INT16:
      return "int16";
    case DT_INT8:
      return "int8";
    case DT_STRING:
      return "string";
    case DT_COMPLEX64:
      return "complex64";
    case DT_COMPLEX128:
      return "complex128";
    case DT_INT64:
      return "int64";
    case DT_BOOL:
      return "bool";
    case DT_QINT8:
      return "qint8";
    case DT_QUINT8:
      return "quint8";
    case DT_QUINT16:
      return "quint16";
    case DT_QINT16:
      return "qint16";
    case DT_QINT32:
      return "qint32";
    case DT_BFLOAT16:
      return "bfloat16";
    case DT_HALF:
      return "half";
    case DT_RESOURCE:
      return "resource";
    default:
      LOG(FATAL) << "Unrecognized DataType enum value " << dtype;
      return "";
  }
}

bool DataTypeFromString(StringPiece sp, DataType* dt) {
  if (sp.ends_with("_ref")) {
    sp.remove_suffix(4);
    DataType non_ref;
    if (DataTypeFromString(sp, &non_ref) && !IsRefType(non_ref)) {
      *dt = static_cast<DataType>(non_ref + kDataTypeRefOffset);
      return true;
    } else {
      return false;
    }
  }

  if (sp == "float" || sp == "float32") {
    *dt = DT_FLOAT;
    return true;
  } else if (sp == "double" || sp == "float64") {
    *dt = DT_DOUBLE;
    return true;
  } else if (sp == "int32") {
    *dt = DT_INT32;
    return true;
  } else if (sp == "uint8") {
    *dt = DT_UINT8;
    return true;
  } else if (sp == "uint16") {
    *dt = DT_UINT16;
    return true;
  } else if (sp == "int16") {
    *dt = DT_INT16;
    return true;
  } else if (sp == "int8") {
    *dt = DT_INT8;
    return true;
  } else if (sp == "string") {
    *dt = DT_STRING;
    return true;
  } else if (sp == "complex64") {
    *dt = DT_COMPLEX64;
    return true;
  } else if (sp == "complex128") {
    *dt = DT_COMPLEX128;
    return true;
  } else if (sp == "int64") {
    *dt = DT_INT64;
    return true;
  } else if (sp == "bool") {
    *dt = DT_BOOL;
    return true;
  } else if (sp == "qint8") {
    *dt = DT_QINT8;
    return true;
  } else if (sp == "quint8") {
    *dt = DT_QUINT8;
    return true;
  } else if (sp == "qint16") {
    *dt = DT_QINT16;
    return true;
  } else if (sp == "quint16") {
    *dt = DT_QUINT16;
    return true;
  } else if (sp == "qint32") {
    *dt = DT_QINT32;
    return true;
  } else if (sp == "bfloat16") {
    *dt = DT_BFLOAT16;
    return true;
  } else if (sp == "half" || sp == "float16") {
    *dt = DT_HALF;
    return true;
  } else if (sp == "resource") {
    *dt = DT_RESOURCE;
    return true;
  }
  return false;
}

string DeviceTypeString(DeviceType device_type) { return device_type.type(); }

string DataTypeSliceString(const DataTypeSlice types) {
  string out;
  for (auto it = types.begin(); it != types.end(); ++it) {
    strings::StrAppend(&out, ((it == types.begin()) ? "" : ", "),
                       DataTypeString(*it));
  }
  return out;
}

DataTypeVector AllTypes() {
  return {DT_FLOAT,   DT_DOUBLE, DT_INT32,  DT_UINT8,     DT_INT16,
          DT_UINT16,  DT_INT8,   DT_STRING, DT_COMPLEX64, DT_COMPLEX128,
          DT_INT64,   DT_BOOL,   DT_QINT8,  DT_QUINT8,    DT_QINT16,
          DT_QUINT16, DT_QINT32, DT_HALF,   DT_RESOURCE};
}

#if !defined(IS_MOBILE_PLATFORM) || defined(SUPPORT_SELECTIVE_REGISTRATION)

DataTypeVector RealNumberTypes() {
  return {DT_FLOAT, DT_DOUBLE, DT_INT32,  DT_INT64, DT_UINT8,
          DT_INT16, DT_INT8,   DT_UINT16, DT_HALF};
}

DataTypeVector QuantizedTypes() {
  return {DT_QINT8, DT_QUINT8, DT_QINT16, DT_QUINT16, DT_QINT32};
}

DataTypeVector RealAndQuantizedTypes() {
  return {DT_FLOAT,  DT_DOUBLE,  DT_INT32,  DT_INT64, DT_UINT8,
          DT_UINT16, DT_UINT16,  DT_INT8,   DT_QINT8, DT_QUINT8,
          DT_QINT16, DT_QUINT16, DT_QINT32, DT_HALF};
}

DataTypeVector NumberTypes() {
  return {DT_FLOAT,  DT_DOUBLE, DT_INT64,  DT_INT32,     DT_UINT8,
          DT_UINT16, DT_INT16,  DT_INT8,   DT_COMPLEX64, DT_COMPLEX128,
          DT_QINT8,  DT_QUINT8, DT_QINT32, DT_HALF};
}

#elif defined(__ANDROID_TYPES_FULL__)

DataTypeVector RealNumberTypes() {
  return {DT_FLOAT, DT_INT32, DT_INT64, DT_HALF};
}

DataTypeVector NumberTypes() {
  return {DT_FLOAT,  DT_INT32,  DT_INT64, DT_QINT8,
          DT_QUINT8, DT_QINT32, DT_HALF};
}

DataTypeVector QuantizedTypes() {
  return {DT_QINT8, DT_QUINT8, DT_QINT16, DT_QUINT16, DT_QINT32};
}

DataTypeVector RealAndQuantizedTypes() {
  return {DT_FLOAT,  DT_INT32,   DT_INT64,  DT_QINT8, DT_QUINT8,
          DT_QINT16, DT_QUINT16, DT_QINT32, DT_HALF};
}

#else  // defined(IS_MOBILE_PLATFORM) && !defined(__ANDROID_TYPES_FULL__)

DataTypeVector RealNumberTypes() { return {DT_FLOAT, DT_INT32}; }

DataTypeVector NumberTypes() {
  return {DT_FLOAT, DT_INT32, DT_QINT8, DT_QUINT8, DT_QINT32};
}

DataTypeVector QuantizedTypes() {
  return {DT_QINT8, DT_QUINT8, DT_QINT16, DT_QUINT16, DT_QINT32};
}

DataTypeVector RealAndQuantizedTypes() {
  return {DT_FLOAT,  DT_INT32,   DT_QINT8, DT_QUINT8,
          DT_QINT16, DT_QUINT16, DT_QINT32};
}

#endif  // defined(IS_MOBILE_PLATFORM)

// TODO(jeff): Maybe unify this with Tensor::CanUseDMA, or the underlying
// is_simple<T> in tensor.cc (and possible choose a more general name?)
bool DataTypeCanUseMemcpy(DataType dt) {
  switch (dt) {
    case DT_FLOAT:
    case DT_DOUBLE:
    case DT_INT32:
    case DT_UINT8:
    case DT_UINT16:
    case DT_INT16:
    case DT_INT8:
    case DT_COMPLEX64:
    case DT_COMPLEX128:
    case DT_INT64:
    case DT_BOOL:
    case DT_QINT8:
    case DT_QUINT8:
    case DT_QINT16:
    case DT_QUINT16:
    case DT_QINT32:
    case DT_BFLOAT16:
    case DT_HALF:
      return true;
    default:
      return false;
  }
}

bool DataTypeIsQuantized(DataType dt) {
  switch (dt) {
    case DT_QINT8:
    case DT_QUINT8:
    case DT_QINT16:
    case DT_QUINT16:
    case DT_QINT32:
      return true;
    default:
      return false;
  }
}

bool DataTypeIsInteger(DataType dt) {
  switch (dt) {
    case DT_INT8:
    case DT_UINT8:
    case DT_INT16:
    case DT_UINT16:
    case DT_INT32:
    case DT_INT64:
      return true;
    default:
      return false;
  }
}

int DataTypeSize(DataType dt) {
#define CASE(T)                  \
  case DataTypeToEnum<T>::value: \
    return sizeof(T);
  switch (dt) {
    TF_CALL_POD_TYPES(CASE);
    TF_CALL_QUANTIZED_TYPES(CASE);
    default:
      return 0;
  }
#undef CASE
}

}  // namespace tensorflow
<commit_msg>Don't FATAL when asked for the name of an unknown type. (Leaving it as an error for now while I check some of the invocations to see if there's really a need for the diagnostic message). Current fatal prevents some helpful error messages from propagating back to the caller. Change: 142870362<commit_after>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/framework/register_types.h"

#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/logging.h"

namespace tensorflow {

bool DeviceType::operator<(const DeviceType& other) const {
  return type_ < other.type_;
}

bool DeviceType::operator==(const DeviceType& other) const {
  return type_ == other.type_;
}

std::ostream& operator<<(std::ostream& os, const DeviceType& d) {
  os << d.type();
  return os;
}

const char* const DEVICE_CPU = "CPU";
const char* const DEVICE_GPU = "GPU";
const char* const DEVICE_SYCL = "SYCL";

string DataTypeString(DataType dtype) {
  if (IsRefType(dtype)) {
    DataType non_ref = static_cast<DataType>(dtype - kDataTypeRefOffset);
    return strings::StrCat(DataTypeString(non_ref), "_ref");
  }
  switch (dtype) {
    case DT_INVALID:
      return "INVALID";
    case DT_FLOAT:
      return "float";
    case DT_DOUBLE:
      return "double";
    case DT_INT32:
      return "int32";
    case DT_UINT8:
      return "uint8";
    case DT_UINT16:
      return "uint16";
    case DT_INT16:
      return "int16";
    case DT_INT8:
      return "int8";
    case DT_STRING:
      return "string";
    case DT_COMPLEX64:
      return "complex64";
    case DT_COMPLEX128:
      return "complex128";
    case DT_INT64:
      return "int64";
    case DT_BOOL:
      return "bool";
    case DT_QINT8:
      return "qint8";
    case DT_QUINT8:
      return "quint8";
    case DT_QUINT16:
      return "quint16";
    case DT_QINT16:
      return "qint16";
    case DT_QINT32:
      return "qint32";
    case DT_BFLOAT16:
      return "bfloat16";
    case DT_HALF:
      return "half";
    case DT_RESOURCE:
      return "resource";
    default:
      LOG(ERROR) << "Unrecognized DataType enum value " << dtype;
      return strings::StrCat("unknown dtype enum (", dtype, ")");
  }
}

bool DataTypeFromString(StringPiece sp, DataType* dt) {
  if (sp.ends_with("_ref")) {
    sp.remove_suffix(4);
    DataType non_ref;
    if (DataTypeFromString(sp, &non_ref) && !IsRefType(non_ref)) {
      *dt = static_cast<DataType>(non_ref + kDataTypeRefOffset);
      return true;
    } else {
      return false;
    }
  }

  if (sp == "float" || sp == "float32") {
    *dt = DT_FLOAT;
    return true;
  } else if (sp == "double" || sp == "float64") {
    *dt = DT_DOUBLE;
    return true;
  } else if (sp == "int32") {
    *dt = DT_INT32;
    return true;
  } else if (sp == "uint8") {
    *dt = DT_UINT8;
    return true;
  } else if (sp == "uint16") {
    *dt = DT_UINT16;
    return true;
  } else if (sp == "int16") {
    *dt = DT_INT16;
    return true;
  } else if (sp == "int8") {
    *dt = DT_INT8;
    return true;
  } else if (sp == "string") {
    *dt = DT_STRING;
    return true;
  } else if (sp == "complex64") {
    *dt = DT_COMPLEX64;
    return true;
  } else if (sp == "complex128") {
    *dt = DT_COMPLEX128;
    return true;
  } else if (sp == "int64") {
    *dt = DT_INT64;
    return true;
  } else if (sp == "bool") {
    *dt = DT_BOOL;
    return true;
  } else if (sp == "qint8") {
    *dt = DT_QINT8;
    return true;
  } else if (sp == "quint8") {
    *dt = DT_QUINT8;
    return true;
  } else if (sp == "qint16") {
    *dt = DT_QINT16;
    return true;
  } else if (sp == "quint16") {
    *dt = DT_QUINT16;
    return true;
  } else if (sp == "qint32") {
    *dt = DT_QINT32;
    return true;
  } else if (sp == "bfloat16") {
    *dt = DT_BFLOAT16;
    return true;
  } else if (sp == "half" || sp == "float16") {
    *dt = DT_HALF;
    return true;
  } else if (sp == "resource") {
    *dt = DT_RESOURCE;
    return true;
  }
  return false;
}

string DeviceTypeString(DeviceType device_type) { return device_type.type(); }

string DataTypeSliceString(const DataTypeSlice types) {
  string out;
  for (auto it = types.begin(); it != types.end(); ++it) {
    strings::StrAppend(&out, ((it == types.begin()) ? "" : ", "),
                       DataTypeString(*it));
  }
  return out;
}

DataTypeVector AllTypes() {
  return {DT_FLOAT,   DT_DOUBLE, DT_INT32,  DT_UINT8,     DT_INT16,
          DT_UINT16,  DT_INT8,   DT_STRING, DT_COMPLEX64, DT_COMPLEX128,
          DT_INT64,   DT_BOOL,   DT_QINT8,  DT_QUINT8,    DT_QINT16,
          DT_QUINT16, DT_QINT32, DT_HALF,   DT_RESOURCE};
}

#if !defined(IS_MOBILE_PLATFORM) || defined(SUPPORT_SELECTIVE_REGISTRATION)

DataTypeVector RealNumberTypes() {
  return {DT_FLOAT, DT_DOUBLE, DT_INT32,  DT_INT64, DT_UINT8,
          DT_INT16, DT_INT8,   DT_UINT16, DT_HALF};
}

DataTypeVector QuantizedTypes() {
  return {DT_QINT8, DT_QUINT8, DT_QINT16, DT_QUINT16, DT_QINT32};
}

DataTypeVector RealAndQuantizedTypes() {
  return {DT_FLOAT,  DT_DOUBLE,  DT_INT32,  DT_INT64, DT_UINT8,
          DT_UINT16, DT_UINT16,  DT_INT8,   DT_QINT8, DT_QUINT8,
          DT_QINT16, DT_QUINT16, DT_QINT32, DT_HALF};
}

DataTypeVector NumberTypes() {
  return {DT_FLOAT,  DT_DOUBLE, DT_INT64,  DT_INT32,     DT_UINT8,
          DT_UINT16, DT_INT16,  DT_INT8,   DT_COMPLEX64, DT_COMPLEX128,
          DT_QINT8,  DT_QUINT8, DT_QINT32, DT_HALF};
}

#elif defined(__ANDROID_TYPES_FULL__)

DataTypeVector RealNumberTypes() {
  return {DT_FLOAT, DT_INT32, DT_INT64, DT_HALF};
}

DataTypeVector NumberTypes() {
  return {DT_FLOAT,  DT_INT32,  DT_INT64, DT_QINT8,
          DT_QUINT8, DT_QINT32, DT_HALF};
}

DataTypeVector QuantizedTypes() {
  return {DT_QINT8, DT_QUINT8, DT_QINT16, DT_QUINT16, DT_QINT32};
}

DataTypeVector RealAndQuantizedTypes() {
  return {DT_FLOAT,  DT_INT32,   DT_INT64,  DT_QINT8, DT_QUINT8,
          DT_QINT16, DT_QUINT16, DT_QINT32, DT_HALF};
}

#else  // defined(IS_MOBILE_PLATFORM) && !defined(__ANDROID_TYPES_FULL__)

DataTypeVector RealNumberTypes() { return {DT_FLOAT, DT_INT32}; }

DataTypeVector NumberTypes() {
  return {DT_FLOAT, DT_INT32, DT_QINT8, DT_QUINT8, DT_QINT32};
}

DataTypeVector QuantizedTypes() {
  return {DT_QINT8, DT_QUINT8, DT_QINT16, DT_QUINT16, DT_QINT32};
}

DataTypeVector RealAndQuantizedTypes() {
  return {DT_FLOAT,  DT_INT32,   DT_QINT8, DT_QUINT8,
          DT_QINT16, DT_QUINT16, DT_QINT32};
}

#endif  // defined(IS_MOBILE_PLATFORM)

// TODO(jeff): Maybe unify this with Tensor::CanUseDMA, or the underlying
// is_simple<T> in tensor.cc (and possible choose a more general name?)
bool DataTypeCanUseMemcpy(DataType dt) {
  switch (dt) {
    case DT_FLOAT:
    case DT_DOUBLE:
    case DT_INT32:
    case DT_UINT8:
    case DT_UINT16:
    case DT_INT16:
    case DT_INT8:
    case DT_COMPLEX64:
    case DT_COMPLEX128:
    case DT_INT64:
    case DT_BOOL:
    case DT_QINT8:
    case DT_QUINT8:
    case DT_QINT16:
    case DT_QUINT16:
    case DT_QINT32:
    case DT_BFLOAT16:
    case DT_HALF:
      return true;
    default:
      return false;
  }
}

bool DataTypeIsQuantized(DataType dt) {
  switch (dt) {
    case DT_QINT8:
    case DT_QUINT8:
    case DT_QINT16:
    case DT_QUINT16:
    case DT_QINT32:
      return true;
    default:
      return false;
  }
}

bool DataTypeIsInteger(DataType dt) {
  switch (dt) {
    case DT_INT8:
    case DT_UINT8:
    case DT_INT16:
    case DT_UINT16:
    case DT_INT32:
    case DT_INT64:
      return true;
    default:
      return false;
  }
}

int DataTypeSize(DataType dt) {
#define CASE(T)                  \
  case DataTypeToEnum<T>::value: \
    return sizeof(T);
  switch (dt) {
    TF_CALL_POD_TYPES(CASE);
    TF_CALL_QUANTIZED_TYPES(CASE);
    default:
      return 0;
  }
#undef CASE
}

}  // namespace tensorflow
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkTransformFeedback.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#include "vtkTransformFeedback.h"

#include "vtkObjectFactory.h"
#include "vtkOpenGLError.h"
#include "vtkShaderProgram.h"

#include "vtk_glew.h"

vtkStandardNewMacro(vtkTransformFeedback)

//------------------------------------------------------------------------------
void vtkTransformFeedback::PrintSelf(std::ostream &os,
                                     vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
}

//------------------------------------------------------------------------------
size_t vtkTransformFeedback::GetBytesPerVertex() const
{
  size_t result = 0;

  typedef std::vector<VaryingMetaData>::const_iterator IterT;
  for (IterT it = this->Varyings.begin(), itEnd = this->Varyings.end();
       it != itEnd; ++it)
    {
    result += this->GetBytesPerVertex(it->Role);
    }

  return result;
}

//------------------------------------------------------------------------------
void vtkTransformFeedback::ClearVaryings()
{
  this->Varyings.clear();
  this->VaryingsBound = false;
}

//------------------------------------------------------------------------------
void vtkTransformFeedback::AddVarying(VaryingRole role,
                                      const std::string &var)
{
  this->Varyings.push_back(VaryingMetaData(role, var));
  this->VaryingsBound = false;
}

//------------------------------------------------------------------------------
void vtkTransformFeedback::SetNumberOfVertices(int drawMode,
                                               size_t inputVerts)
{
  switch (static_cast<GLenum>(drawMode))
    {
    case GL_POINTS:
      this->SetNumberOfVertices(inputVerts);
      this->SetPrimitiveMode(GL_POINTS);
      return;
    case GL_LINE_STRIP:
      this->SetNumberOfVertices(inputVerts < 2 ? 0 : (2 * (inputVerts - 1)));
      this->SetPrimitiveMode(GL_LINES);
      return;
    case GL_LINE_LOOP:
      this->SetNumberOfVertices(2 * inputVerts);
      this->SetPrimitiveMode(GL_LINES);
      return;
    case GL_LINES:
      this->SetNumberOfVertices(inputVerts);
      this->SetPrimitiveMode(GL_LINES);
      return;
    case GL_TRIANGLE_STRIP:
      this->SetNumberOfVertices(inputVerts < 3 ? 0 : (3 * (inputVerts - 2)));
      this->SetPrimitiveMode(GL_TRIANGLES);
      return;
    case GL_TRIANGLE_FAN:
      this->SetNumberOfVertices(inputVerts < 3 ? 0 : (3 * (inputVerts - 2)));
      this->SetPrimitiveMode(GL_TRIANGLES);
      return;
    case GL_TRIANGLES:
      this->SetNumberOfVertices(inputVerts);
      this->SetPrimitiveMode(GL_TRIANGLES);
      return;
    }

  vtkErrorMacro("Unknown draw mode enum value: " << drawMode);
  this->SetNumberOfVertices(0);
  this->SetPrimitiveMode(GL_POINTS);
}

//------------------------------------------------------------------------------
size_t vtkTransformFeedback::GetBufferSize() const
{
  return this->GetBytesPerVertex() * this->NumberOfVertices;
}

//------------------------------------------------------------------------------
void vtkTransformFeedback::BindVaryings(vtkShaderProgram *prog)
{
  if (this->Varyings.empty())
    {
    vtkErrorMacro(<<"No capture varyings specified.");
    return;
    }

  vtkOpenGLClearErrorMacro();

  std::vector<const char*> vars;
  vars.reserve(this->Varyings.size());
  for (size_t i = 0; i < this->Varyings.size(); ++i)
    {
    vars.push_back(this->Varyings[i].Identifier.c_str());
    }

  glTransformFeedbackVaryings(static_cast<GLuint>(prog->GetHandle()),
                              static_cast<GLsizei>(vars.size()),
                              &vars[0], static_cast<GLenum>(this->BufferMode));

  this->VaryingsBound = true;

  vtkOpenGLCheckErrorMacro("OpenGL errors detected after "
                           "glTransformFeedbackVaryings.");
}

//------------------------------------------------------------------------------
void vtkTransformFeedback::BindBuffer()
{
  if (!this->VaryingsBound)
    {
    vtkErrorMacro("Varyings not yet bound!");
    return;
    }

  vtkOpenGLClearErrorMacro();
  this->ReleaseGraphicsResources();

  GLuint tbo;
  glGenBuffers(1, &tbo);
  this->BufferHandle = static_cast<int>(tbo);
  glBindBuffer(GL_ARRAY_BUFFER, tbo);
  glBufferData(GL_ARRAY_BUFFER, static_cast<GLsizeiptr>(this->GetBufferSize()),
               NULL, GL_STATIC_READ);
  glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, tbo);
  glBeginTransformFeedback(static_cast<GLenum>(this->PrimitiveMode));

  vtkOpenGLCheckErrorMacro("OpenGL errors detected.");
}

//------------------------------------------------------------------------------
void vtkTransformFeedback::ReadBuffer()
{
  if (this->BufferHandle == 0)
    {
    vtkErrorMacro("BufferHandle not set by BindBuffer().");
    return;
    }

  glEndTransformFeedback();
  glFlush();

  size_t bufferSize = this->GetBufferSize();
  this->ReleaseBufferData();
  this->BufferData = new unsigned char[bufferSize];

  glGetBufferSubData(GL_TRANSFORM_FEEDBACK_BUFFER, 0, bufferSize,
                     static_cast<void*>(this->BufferData));

  this->ReleaseGraphicsResources();

  vtkOpenGLCheckErrorMacro("OpenGL errors detected.");
}

//------------------------------------------------------------------------------
void vtkTransformFeedback::ReleaseGraphicsResources()
{
  if (this->BufferHandle)
    {
    GLuint tbo = static_cast<GLuint>(this->BufferHandle);
    glDeleteBuffers(1, &tbo);
    this->BufferHandle = 0;
    }
}

//------------------------------------------------------------------------------
void vtkTransformFeedback::ReleaseBufferData(bool freeBuffer)
{
  if (freeBuffer)
    {
    delete [] this->BufferData;
    }
  this->BufferData = NULL;
}

//------------------------------------------------------------------------------
vtkTransformFeedback::vtkTransformFeedback()
  : VaryingsBound(false),
    Varyings(),
    NumberOfVertices(0),
    BufferMode(GL_INTERLEAVED_ATTRIBS),
    BufferHandle(0),
    PrimitiveMode(GL_POINTS),
    BufferData(NULL)
{
}

//------------------------------------------------------------------------------
vtkTransformFeedback::~vtkTransformFeedback()
{
  this->ReleaseGraphicsResources();
  this->ReleaseBufferData();
}
<commit_msg>Disable vtkTransformFeedback on ES 2.0.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkTransformFeedback.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#include "vtkTransformFeedback.h"

#include "vtkObjectFactory.h"
#include "vtkOpenGLError.h"
#include "vtkShaderProgram.h"

#include "vtk_glew.h"

// Many of the OpenGL features used here are available in ES3, but not ES2.
// All non-embedded OpenGL versions for this backend should support this class.
#if !defined(GL_ES_VERSION_2_0) || defined(GL_ES_VERSION_3_0)
#define GL_SUPPORTED // Not on an embedded system, or ES >= 3.0
#endif

#ifdef GL_SUPPORTED
vtkStandardNewMacro(vtkTransformFeedback)
#else // GL_SUPPORTED
vtkTransformFeedback* vtkTransformFeedback::New()
{
  // We return null on non-supported platforms. Since we only instantiate
  // this class when an instance of vtkOpenGLGL2PSHelper exists and no valid
  // implementation of that class exists on embedded systems, this shouldn't
  // cause problems.
  vtkGenericWarningMacro("TransformFeedback is unsupported on this platform.");
  return NULL;
}
#endif // GL_SUPPORTED

//------------------------------------------------------------------------------
void vtkTransformFeedback::PrintSelf(std::ostream &os,
                                     vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
}

//------------------------------------------------------------------------------
size_t vtkTransformFeedback::GetBytesPerVertex() const
{
  size_t result = 0;

  typedef std::vector<VaryingMetaData>::const_iterator IterT;
  for (IterT it = this->Varyings.begin(), itEnd = this->Varyings.end();
       it != itEnd; ++it)
    {
    result += this->GetBytesPerVertex(it->Role);
    }

  return result;
}

//------------------------------------------------------------------------------
void vtkTransformFeedback::ClearVaryings()
{
  this->Varyings.clear();
  this->VaryingsBound = false;
}

//------------------------------------------------------------------------------
void vtkTransformFeedback::AddVarying(VaryingRole role,
                                      const std::string &var)
{
  this->Varyings.push_back(VaryingMetaData(role, var));
  this->VaryingsBound = false;
}

//------------------------------------------------------------------------------
void vtkTransformFeedback::SetNumberOfVertices(int drawMode,
                                               size_t inputVerts)
{
#ifdef GL_SUPPORTED
  switch (static_cast<GLenum>(drawMode))
    {
    case GL_POINTS:
      this->SetNumberOfVertices(inputVerts);
      this->SetPrimitiveMode(GL_POINTS);
      return;
    case GL_LINE_STRIP:
      this->SetNumberOfVertices(inputVerts < 2 ? 0 : (2 * (inputVerts - 1)));
      this->SetPrimitiveMode(GL_LINES);
      return;
    case GL_LINE_LOOP:
      this->SetNumberOfVertices(2 * inputVerts);
      this->SetPrimitiveMode(GL_LINES);
      return;
    case GL_LINES:
      this->SetNumberOfVertices(inputVerts);
      this->SetPrimitiveMode(GL_LINES);
      return;
    case GL_TRIANGLE_STRIP:
      this->SetNumberOfVertices(inputVerts < 3 ? 0 : (3 * (inputVerts - 2)));
      this->SetPrimitiveMode(GL_TRIANGLES);
      return;
    case GL_TRIANGLE_FAN:
      this->SetNumberOfVertices(inputVerts < 3 ? 0 : (3 * (inputVerts - 2)));
      this->SetPrimitiveMode(GL_TRIANGLES);
      return;
    case GL_TRIANGLES:
      this->SetNumberOfVertices(inputVerts);
      this->SetPrimitiveMode(GL_TRIANGLES);
      return;
    }

  vtkErrorMacro("Unknown draw mode enum value: " << drawMode);
  this->SetNumberOfVertices(0);
  this->SetPrimitiveMode(GL_POINTS);
#else // GL_SUPPORTED
  (void)drawMode;
  (void)inputVerts;
#endif // GL_SUPPORTED
}

//------------------------------------------------------------------------------
size_t vtkTransformFeedback::GetBufferSize() const
{
  return this->GetBytesPerVertex() * this->NumberOfVertices;
}

//------------------------------------------------------------------------------
void vtkTransformFeedback::BindVaryings(vtkShaderProgram *prog)
{
#ifdef GL_SUPPORTED
  if (this->Varyings.empty())
    {
    vtkErrorMacro(<<"No capture varyings specified.");
    return;
    }

  vtkOpenGLClearErrorMacro();

  std::vector<const char*> vars;
  vars.reserve(this->Varyings.size());
  for (size_t i = 0; i < this->Varyings.size(); ++i)
    {
    vars.push_back(this->Varyings[i].Identifier.c_str());
    }

  glTransformFeedbackVaryings(static_cast<GLuint>(prog->GetHandle()),
                              static_cast<GLsizei>(vars.size()),
                              &vars[0], static_cast<GLenum>(this->BufferMode));

  this->VaryingsBound = true;

  vtkOpenGLCheckErrorMacro("OpenGL errors detected after "
                           "glTransformFeedbackVaryings.");
#else // GL_SUPPORTED
  (void)prog;
#endif // GL_SUPPORTED
}

//------------------------------------------------------------------------------
void vtkTransformFeedback::BindBuffer()
{
#ifdef GL_SUPPORTED
  if (!this->VaryingsBound)
    {
    vtkErrorMacro("Varyings not yet bound!");
    return;
    }

  vtkOpenGLClearErrorMacro();
  this->ReleaseGraphicsResources();

  GLuint tbo;
  glGenBuffers(1, &tbo);
  this->BufferHandle = static_cast<int>(tbo);
  glBindBuffer(GL_ARRAY_BUFFER, tbo);
  glBufferData(GL_ARRAY_BUFFER, static_cast<GLsizeiptr>(this->GetBufferSize()),
               NULL, GL_STATIC_READ);
  glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, tbo);
  glBeginTransformFeedback(static_cast<GLenum>(this->PrimitiveMode));

  vtkOpenGLCheckErrorMacro("OpenGL errors detected.");
#endif // GL_SUPPORTED
}

//------------------------------------------------------------------------------
void vtkTransformFeedback::ReadBuffer()
{
#ifdef GL_SUPPORTED
  if (this->BufferHandle == 0)
    {
    vtkErrorMacro("BufferHandle not set by BindBuffer().");
    return;
    }

  glEndTransformFeedback();
  glFlush();

  size_t bufferSize = this->GetBufferSize();
  this->ReleaseBufferData();
  this->BufferData = new unsigned char[bufferSize];

  glGetBufferSubData(GL_TRANSFORM_FEEDBACK_BUFFER, 0, bufferSize,
                     static_cast<void*>(this->BufferData));

  this->ReleaseGraphicsResources();

  vtkOpenGLCheckErrorMacro("OpenGL errors detected.");
#endif // GL_SUPPORTED
}

//------------------------------------------------------------------------------
void vtkTransformFeedback::ReleaseGraphicsResources()
{
#ifdef GL_SUPPORTED
  if (this->BufferHandle)
    {
    GLuint tbo = static_cast<GLuint>(this->BufferHandle);
    glDeleteBuffers(1, &tbo);
    this->BufferHandle = 0;
    }
#endif // GL_SUPPORTED
}

//------------------------------------------------------------------------------
void vtkTransformFeedback::ReleaseBufferData(bool freeBuffer)
{
  if (freeBuffer)
    {
    delete [] this->BufferData;
    }
  this->BufferData = NULL;
}

//------------------------------------------------------------------------------
vtkTransformFeedback::vtkTransformFeedback()
  : VaryingsBound(false),
    Varyings(),
    NumberOfVertices(0),
#ifdef GL_SUPPORTED
    BufferMode(GL_INTERLEAVED_ATTRIBS),
#else // GL_SUPPORTED
    BufferMode(0),
#endif // GL_SUPPORTED
    BufferHandle(0),
    PrimitiveMode(GL_POINTS),
    BufferData(NULL)
{
}

//------------------------------------------------------------------------------
vtkTransformFeedback::~vtkTransformFeedback()
{
  this->ReleaseGraphicsResources();
  this->ReleaseBufferData();
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkSampleFunction.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkSampleFunction.h"

#include "vtkDoubleArray.h"
#include "vtkFloatArray.h"
#include "vtkGarbageCollector.h"
#include "vtkImageData.h"
#include "vtkImplicitFunction.h"
#include "vtkMath.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkPointData.h"

vtkCxxRevisionMacro(vtkSampleFunction, "1.74");
vtkStandardNewMacro(vtkSampleFunction);
vtkCxxSetObjectMacro(vtkSampleFunction,ImplicitFunction,vtkImplicitFunction);

// Construct with ModelBounds=(-1,1,-1,1,-1,1), SampleDimensions=(50,50,50),
// Capping turned off, and normal generation on.
vtkSampleFunction::vtkSampleFunction()
{
  this->ModelBounds[0] = -1.0;
  this->ModelBounds[1] = 1.0;
  this->ModelBounds[2] = -1.0;
  this->ModelBounds[3] = 1.0;
  this->ModelBounds[4] = -1.0;
  this->ModelBounds[5] = 1.0;

  this->SampleDimensions[0] = 50;
  this->SampleDimensions[1] = 50;
  this->SampleDimensions[2] = 50;

  this->Capping = 0;
  this->CapValue = VTK_LARGE_FLOAT;

  this->ImplicitFunction = NULL;

  this->ComputeNormals = 1;
  this->OutputScalarType = VTK_DOUBLE;

  this->SetNumberOfInputPorts(0);
}

vtkSampleFunction::~vtkSampleFunction()
{
  this->SetImplicitFunction(NULL);
}

// Specify the dimensions of the data on which to sample.
void vtkSampleFunction::SetSampleDimensions(int i, int j, int k)
{
  int dim[3];

  dim[0] = i;
  dim[1] = j;
  dim[2] = k;

  this->SetSampleDimensions(dim);
}

// Specify the dimensions of the data on which to sample.
void vtkSampleFunction::SetSampleDimensions(int dim[3])
{
  vtkDebugMacro(<< " setting SampleDimensions to (" << dim[0] << "," << dim[1] << "," << dim[2] << ")");

  if ( dim[0] != this->SampleDimensions[0] ||
       dim[1] != this->SampleDimensions[1] ||
       dim[2] != this->SampleDimensions[2] )
    {
    for ( int i=0; i<3; i++)
      {
      this->SampleDimensions[i] = (dim[i] > 0 ? dim[i] : 1);
      }
    this->Modified();
    }
}

int vtkSampleFunction::RequestInformation (
  vtkInformation * vtkNotUsed(request),
  vtkInformationVector ** vtkNotUsed( inputVector ),
  vtkInformationVector *outputVector)
{
  // get the info objects
  vtkInformation* outInfo = outputVector->GetInformationObject(0);

  int i;
  double ar[3], origin[3];

  int wExt[6];
  wExt[0] = 0; wExt[2] = 0; wExt[4] = 0;
  wExt[1] = this->SampleDimensions[0]-1;
  wExt[3] = this->SampleDimensions[1]-1;
  wExt[5] = this->SampleDimensions[2]-1;

  outInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), wExt, 6);

  for (i=0; i < 3; i++)
    {
    origin[i] = this->ModelBounds[2*i];
    if ( this->SampleDimensions[i] <= 1 )
      {
      ar[i] = 1;
      }
    else
      {
      ar[i] = (this->ModelBounds[2*i+1] - this->ModelBounds[2*i])
        / (this->SampleDimensions[i] - 1);
      }
    }
  outInfo->Set(vtkDataObject::ORIGIN(),origin,3);
  outInfo->Set(vtkDataObject::SPACING(),ar,3);

  vtkDataObject::SetPointDataActiveScalarInfo(outInfo, VTK_DOUBLE, 1);
  return 1;
}

void vtkSampleFunction::ExecuteData(vtkDataObject *outp)
{
  vtkIdType idx, i, j, k;
  vtkFloatArray *newNormals=NULL;
  vtkIdType numPts;
  double p[3], s;
  vtkImageData *output=this->GetOutput();

  output->SetExtent(output->GetUpdateExtent());
  output = this->AllocateOutputData(outp);
  vtkDoubleArray *newScalars =
    vtkDoubleArray::SafeDownCast(output->GetPointData()->GetScalars());

  vtkDebugMacro(<< "Sampling implicit function");

  // Initialize self; create output objects
  //
  if ( !this->ImplicitFunction )
    {
    vtkErrorMacro(<<"No implicit function specified");
    return;
    }

  numPts = newScalars->GetNumberOfTuples();

  // Traverse all points evaluating implicit function at each point
  //
  int extent[6];
  output->GetUpdateExtent(extent);
  double spacing[3];
  output->GetSpacing(spacing);

  for ( idx=0, k=extent[4]; k <= extent[5]; k++ )
    {
    p[2] = this->ModelBounds[4] + k*spacing[2];
    for ( j=extent[2]; j <= extent[3]; j++ )
      {
      p[1] = this->ModelBounds[2] + j*spacing[1];
      for ( i=extent[0]; i <= extent[1]; i++ )
        {
        p[0] = this->ModelBounds[0] + i*spacing[0];
        s = this->ImplicitFunction->FunctionValue(p);
        newScalars->SetTuple1(idx++,s);
        }
      }
    }

  // If normal computation turned on, compute them
  //
  if ( this->ComputeNormals )
    {
    double n[3];
    newNormals = vtkFloatArray::New();
    newNormals->SetNumberOfComponents(3);
    newNormals->SetNumberOfTuples(numPts);
    for ( idx=0, k=extent[4]; k <= extent[5]; k++ )
      {
      p[2] = this->ModelBounds[4] + k*spacing[2];
      for ( j=extent[2]; j <= extent[3]; j++ )
        {
        p[1] = this->ModelBounds[2] + j*spacing[1];
        for ( i=extent[0]; i <= extent[1]; i++ )
          {
          p[0] = this->ModelBounds[0] + i*spacing[0];
          this->ImplicitFunction->FunctionGradient(p, n);
          n[0] *= -1;
          n[1] *= -1;
          n[2] *= -1;
          vtkMath::Normalize(n);
          newNormals->SetTuple(idx++,n);
          }
        }
      }
    }

  // If capping is turned on, set the distances of the outside of the volume
  // to the CapValue.
  //
  if ( this->Capping )
    {
    this->Cap(newScalars);
    }

  // Update self
  //
  if (newNormals)
    {
    output->GetPointData()->SetNormals(newNormals);
    newNormals->Delete();
    }
}

unsigned long vtkSampleFunction::GetMTime()
{
  unsigned long mTime=this->Superclass::GetMTime();
  unsigned long impFuncMTime;

  if ( this->ImplicitFunction != NULL )
    {
    impFuncMTime = this->ImplicitFunction->GetMTime();
    mTime = ( impFuncMTime > mTime ? impFuncMTime : mTime );
    }

  return mTime;
}

void vtkSampleFunction::Cap(vtkDataArray *s)
{
  int i,j,k,extent[6];
  vtkIdType idx;
  int d01=this->SampleDimensions[0]*this->SampleDimensions[1];
  vtkImageData *output = this->GetOutput();
  output->GetUpdateExtent(extent);

  // i-j planes
  //k = extent[4];
  for (j=extent[2]; j<=extent[3]; j++)
    {
    for (i=extent[0]; i<=extent[1]; i++)
      {
      s->SetComponent(i+j*this->SampleDimensions[0], 0, this->CapValue);
      }
    }

  k = extent[5];
  idx = k*d01;
  for (j=extent[2]; j<=extent[3]; j++)
    {
    for (i=extent[0]; i<=extent[1]; i++)
      {
      s->SetComponent(idx+i+j*this->SampleDimensions[0], 0, this->CapValue);
      }
    }

  // j-k planes
  //i = extent[0];
  for (k=extent[4]; k<=extent[5]; k++)
    {
    for (j=extent[2]; j<=extent[3]; j++)
      {
      s->SetComponent(j*this->SampleDimensions[0]+k*d01, 0, this->CapValue);
      }
    }

  i = extent[1];
  for (k=extent[4]; k<=extent[5]; k++)
    {
    for (j=extent[2]; j<=extent[3]; j++)
      {
      s->SetComponent(i+j*this->SampleDimensions[0]+k*d01, 0, this->CapValue);
      }
    }

  // i-k planes
  //j = extent[2];
  for (k=extent[4]; k<=extent[5]; k++)
    {
    for (i=extent[0]; i<=extent[1]; i++)
      {
      s->SetComponent(i+k*d01, 0, this->CapValue);
      }
    }

  j = extent[3];
  idx = j*this->SampleDimensions[0];
  for (k=extent[4]; k<=extent[5]; k++)
    {
    for (i=extent[0]; i<=extent[1]; i++)
      {
      s->SetComponent(idx+i+k*d01, 0, this->CapValue);
      }
    }
}

void vtkSampleFunction::SetScalars(vtkDataArray *da)
{
  if (da)
    {
    this->SetOutputScalarType(da->GetDataType());
    }
}

void vtkSampleFunction::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "Sample Dimensions: (" << this->SampleDimensions[0] << ", "
               << this->SampleDimensions[1] << ", "
               << this->SampleDimensions[2] << ")\n";
  os << indent << "ModelBounds: \n";
  os << indent << "  Xmin,Xmax: (" << this->ModelBounds[0]
     << ", " << this->ModelBounds[1] << ")\n";
  os << indent << "  Ymin,Ymax: (" << this->ModelBounds[2]
     << ", " << this->ModelBounds[3] << ")\n";
  os << indent << "  Zmin,Zmax: (" << this->ModelBounds[4]
     << ", " << this->ModelBounds[5] << ")\n";

  os << indent << "OutputScalarType: " << this->OutputScalarType << "\n";

  if ( this->ImplicitFunction )
    {
    os << indent << "Implicit Function: " << this->ImplicitFunction << "\n";
    }
  else
    {
    os << indent << "No Implicit function defined\n";
    }

  os << indent << "Capping: " << (this->Capping ? "On\n" : "Off\n");
  os << indent << "Cap Value: " << this->CapValue << "\n";

  os << indent << "Compute Normals: " << (this->ComputeNormals ? "On\n" : "Off\n");
}

//----------------------------------------------------------------------------
void vtkSampleFunction::ReportReferences(vtkGarbageCollector* collector)
{
  this->Superclass::ReportReferences(collector);
  vtkGarbageCollectorReport(collector, this->ImplicitFunction,
                            "ImplicitFunction");
}
<commit_msg>BUG:Fixed a line missed by the convertion to double.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkSampleFunction.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkSampleFunction.h"

#include "vtkDoubleArray.h"
#include "vtkFloatArray.h"
#include "vtkGarbageCollector.h"
#include "vtkImageData.h"
#include "vtkImplicitFunction.h"
#include "vtkMath.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkPointData.h"

vtkCxxRevisionMacro(vtkSampleFunction, "1.75");
vtkStandardNewMacro(vtkSampleFunction);
vtkCxxSetObjectMacro(vtkSampleFunction,ImplicitFunction,vtkImplicitFunction);

vtkSampleFunction::vtkSampleFunction()
{
  this->ModelBounds[0] = -1.0;
  this->ModelBounds[1] = 1.0;
  this->ModelBounds[2] = -1.0;
  this->ModelBounds[3] = 1.0;
  this->ModelBounds[4] = -1.0;
  this->ModelBounds[5] = 1.0;

  this->SampleDimensions[0] = 50;
  this->SampleDimensions[1] = 50;
  this->SampleDimensions[2] = 50;

  this->Capping = 0;
  this->CapValue = VTK_DOUBLE_MAX;

  this->ImplicitFunction = NULL;

  this->ComputeNormals = 1;
  this->OutputScalarType = VTK_DOUBLE;

  this->SetNumberOfInputPorts(0);
}

vtkSampleFunction::~vtkSampleFunction()
{
  this->SetImplicitFunction(NULL);
}

// Specify the dimensions of the data on which to sample.
void vtkSampleFunction::SetSampleDimensions(int i, int j, int k)
{
  int dim[3];

  dim[0] = i;
  dim[1] = j;
  dim[2] = k;

  this->SetSampleDimensions(dim);
}

// Specify the dimensions of the data on which to sample.
void vtkSampleFunction::SetSampleDimensions(int dim[3])
{
  vtkDebugMacro(<< " setting SampleDimensions to (" << dim[0] << "," << dim[1] << "," << dim[2] << ")");

  if ( dim[0] != this->SampleDimensions[0] ||
       dim[1] != this->SampleDimensions[1] ||
       dim[2] != this->SampleDimensions[2] )
    {
    for ( int i=0; i<3; i++)
      {
      this->SampleDimensions[i] = (dim[i] > 0 ? dim[i] : 1);
      }
    this->Modified();
    }
}

int vtkSampleFunction::RequestInformation (
  vtkInformation * vtkNotUsed(request),
  vtkInformationVector ** vtkNotUsed( inputVector ),
  vtkInformationVector *outputVector)
{
  // get the info objects
  vtkInformation* outInfo = outputVector->GetInformationObject(0);

  int i;
  double ar[3], origin[3];

  int wExt[6];
  wExt[0] = 0; wExt[2] = 0; wExt[4] = 0;
  wExt[1] = this->SampleDimensions[0]-1;
  wExt[3] = this->SampleDimensions[1]-1;
  wExt[5] = this->SampleDimensions[2]-1;

  outInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), wExt, 6);

  for (i=0; i < 3; i++)
    {
    origin[i] = this->ModelBounds[2*i];
    if ( this->SampleDimensions[i] <= 1 )
      {
      ar[i] = 1;
      }
    else
      {
      ar[i] = (this->ModelBounds[2*i+1] - this->ModelBounds[2*i])
        / (this->SampleDimensions[i] - 1);
      }
    }
  outInfo->Set(vtkDataObject::ORIGIN(),origin,3);
  outInfo->Set(vtkDataObject::SPACING(),ar,3);

  vtkDataObject::SetPointDataActiveScalarInfo(outInfo, VTK_DOUBLE, 1);
  return 1;
}

void vtkSampleFunction::ExecuteData(vtkDataObject *outp)
{
  vtkIdType idx, i, j, k;
  vtkFloatArray *newNormals=NULL;
  vtkIdType numPts;
  double p[3], s;
  vtkImageData *output=this->GetOutput();

  output->SetExtent(output->GetUpdateExtent());
  output = this->AllocateOutputData(outp);
  vtkDoubleArray *newScalars =
    vtkDoubleArray::SafeDownCast(output->GetPointData()->GetScalars());

  vtkDebugMacro(<< "Sampling implicit function");

  // Initialize self; create output objects
  //
  if ( !this->ImplicitFunction )
    {
    vtkErrorMacro(<<"No implicit function specified");
    return;
    }

  numPts = newScalars->GetNumberOfTuples();

  // Traverse all points evaluating implicit function at each point
  //
  int extent[6];
  output->GetUpdateExtent(extent);
  double spacing[3];
  output->GetSpacing(spacing);

  for ( idx=0, k=extent[4]; k <= extent[5]; k++ )
    {
    p[2] = this->ModelBounds[4] + k*spacing[2];
    for ( j=extent[2]; j <= extent[3]; j++ )
      {
      p[1] = this->ModelBounds[2] + j*spacing[1];
      for ( i=extent[0]; i <= extent[1]; i++ )
        {
        p[0] = this->ModelBounds[0] + i*spacing[0];
        s = this->ImplicitFunction->FunctionValue(p);
        newScalars->SetTuple1(idx++,s);
        }
      }
    }

  // If normal computation turned on, compute them
  //
  if ( this->ComputeNormals )
    {
    double n[3];
    newNormals = vtkFloatArray::New();
    newNormals->SetNumberOfComponents(3);
    newNormals->SetNumberOfTuples(numPts);
    for ( idx=0, k=extent[4]; k <= extent[5]; k++ )
      {
      p[2] = this->ModelBounds[4] + k*spacing[2];
      for ( j=extent[2]; j <= extent[3]; j++ )
        {
        p[1] = this->ModelBounds[2] + j*spacing[1];
        for ( i=extent[0]; i <= extent[1]; i++ )
          {
          p[0] = this->ModelBounds[0] + i*spacing[0];
          this->ImplicitFunction->FunctionGradient(p, n);
          n[0] *= -1;
          n[1] *= -1;
          n[2] *= -1;
          vtkMath::Normalize(n);
          newNormals->SetTuple(idx++,n);
          }
        }
      }
    }

  // If capping is turned on, set the distances of the outside of the volume
  // to the CapValue.
  //
  if ( this->Capping )
    {
    this->Cap(newScalars);
    }

  // Update self
  //
  if (newNormals)
    {
    output->GetPointData()->SetNormals(newNormals);
    newNormals->Delete();
    }
}

unsigned long vtkSampleFunction::GetMTime()
{
  unsigned long mTime=this->Superclass::GetMTime();
  unsigned long impFuncMTime;

  if ( this->ImplicitFunction != NULL )
    {
    impFuncMTime = this->ImplicitFunction->GetMTime();
    mTime = ( impFuncMTime > mTime ? impFuncMTime : mTime );
    }

  return mTime;
}

void vtkSampleFunction::Cap(vtkDataArray *s)
{
  int i,j,k,extent[6];
  vtkIdType idx;
  int d01=this->SampleDimensions[0]*this->SampleDimensions[1];
  vtkImageData *output = this->GetOutput();
  output->GetUpdateExtent(extent);

  // i-j planes
  //k = extent[4];
  for (j=extent[2]; j<=extent[3]; j++)
    {
    for (i=extent[0]; i<=extent[1]; i++)
      {
      s->SetComponent(i+j*this->SampleDimensions[0], 0, this->CapValue);
      }
    }

  k = extent[5];
  idx = k*d01;
  for (j=extent[2]; j<=extent[3]; j++)
    {
    for (i=extent[0]; i<=extent[1]; i++)
      {
      s->SetComponent(idx+i+j*this->SampleDimensions[0], 0, this->CapValue);
      }
    }

  // j-k planes
  //i = extent[0];
  for (k=extent[4]; k<=extent[5]; k++)
    {
    for (j=extent[2]; j<=extent[3]; j++)
      {
      s->SetComponent(j*this->SampleDimensions[0]+k*d01, 0, this->CapValue);
      }
    }

  i = extent[1];
  for (k=extent[4]; k<=extent[5]; k++)
    {
    for (j=extent[2]; j<=extent[3]; j++)
      {
      s->SetComponent(i+j*this->SampleDimensions[0]+k*d01, 0, this->CapValue);
      }
    }

  // i-k planes
  //j = extent[2];
  for (k=extent[4]; k<=extent[5]; k++)
    {
    for (i=extent[0]; i<=extent[1]; i++)
      {
      s->SetComponent(i+k*d01, 0, this->CapValue);
      }
    }

  j = extent[3];
  idx = j*this->SampleDimensions[0];
  for (k=extent[4]; k<=extent[5]; k++)
    {
    for (i=extent[0]; i<=extent[1]; i++)
      {
      s->SetComponent(idx+i+k*d01, 0, this->CapValue);
      }
    }
}

void vtkSampleFunction::SetScalars(vtkDataArray *da)
{
  if (da)
    {
    this->SetOutputScalarType(da->GetDataType());
    }
}

void vtkSampleFunction::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "Sample Dimensions: (" << this->SampleDimensions[0] << ", "
               << this->SampleDimensions[1] << ", "
               << this->SampleDimensions[2] << ")\n";
  os << indent << "ModelBounds: \n";
  os << indent << "  Xmin,Xmax: (" << this->ModelBounds[0]
     << ", " << this->ModelBounds[1] << ")\n";
  os << indent << "  Ymin,Ymax: (" << this->ModelBounds[2]
     << ", " << this->ModelBounds[3] << ")\n";
  os << indent << "  Zmin,Zmax: (" << this->ModelBounds[4]
     << ", " << this->ModelBounds[5] << ")\n";

  os << indent << "OutputScalarType: " << this->OutputScalarType << "\n";

  if ( this->ImplicitFunction )
    {
    os << indent << "Implicit Function: " << this->ImplicitFunction << "\n";
    }
  else
    {
    os << indent << "No Implicit function defined\n";
    }

  os << indent << "Capping: " << (this->Capping ? "On\n" : "Off\n");
  os << indent << "Cap Value: " << this->CapValue << "\n";

  os << indent << "Compute Normals: " << (this->ComputeNormals ? "On\n" : "Off\n");
}

//----------------------------------------------------------------------------
void vtkSampleFunction::ReportReferences(vtkGarbageCollector* collector)
{
  this->Superclass::ReportReferences(collector);
  vtkGarbageCollectorReport(collector, this->ImplicitFunction,
                            "ImplicitFunction");
}
<|endoftext|>


<commit_before>//
//  JdCoreL2.h
//  Jigidesign
//
//  Created by Steven Massey on 9/4/15.
//  Copyright (c) 2015 Jigidesign. All rights reserved.
//

#ifndef __Jigidesign__JdCoreL2__
#define __Jigidesign__JdCoreL2__

#include <sstream>

#include "JdNucleus.hpp"

namespace Jd
{
	i32 HashCString31 (const char *i_string);
	u64 HashString64 (const string & i_string);

	template <class X>
	X* SingletonHelper (bool i_create)
	{
		static X * lonely = new X;
		static i64 usageCount = 0;

		if (i_create)
		{
			++usageCount;
		}
		else
		{
			if (--usageCount <= 0)
			{
				delete lonely;
				lonely = nullptr;
				usageCount = 0;
			}
		}

		return lonely;
	}

	template <class X>
	X* AcquireSingleton () // X * should be subsequently released with the ReleaseSingleton () call, if you want the singleton to be eventually shutdown
	{
		return SingletonHelper <X> (true);
	}
}

#endif /* defined(__Jigidesign__JdCoreL2__) */
<commit_msg>no message<commit_after>//
//  JdCoreL2.h
//  Jigidesign
//
//  Created by Steven Massey on 9/4/15.
//  Copyright (c) 2015 Jigidesign. All rights reserved.
//

#ifndef __Jigidesign__JdCoreL2__
#define __Jigidesign__JdCoreL2__

#include <sstream>

#include "JdNucleus.hpp"

namespace Jd
{
	i32 HashCString31 (const char *i_string);
	u64 HashString64 (const string & i_string);

	template <class X>
	X* SingletonHelper (bool i_create)
	{
		static X * lonely = new X;
		static i64 usageCount = 0;

		if (i_create)
		{
			++usageCount;
		}
		else
		{
			if (--usageCount <= 0)
			{
				delete lonely;
				lonely = nullptr;
				usageCount = 0;
			}
		}

		return lonely;
	}

	template <class X>
	X* AcquireSingleton () // X * should be subsequently released with the ReleaseSingleton () call, if you want the singleton to be eventually shutdown
	{
		return SingletonHelper <X> (true);
	}

	template <class X>
	void ReleaseSingleton (X * i_singleton)
	{
		if (i_singleton)
			SingletonHelper <X> (false);
	}

	template <typename X>
	struct Singleton
	{
		Singleton ()
		{
			m_lonely = Jd::AcquireSingleton <X> ();
		}

		~Singleton ()
		{
			Jd::ReleaseSingleton (m_lonely);
		}

		X * operator -> () const
		{
			return m_lonely;
		}

		operator X * () const
		{
			return m_lonely;
		}

		X * m_lonely;
	};
}

#endif /* defined(__Jigidesign__JdCoreL2__) */
<|endoftext|>


<commit_before>
#include "precompiled.h"

void WarpZone::setDistination(ofVec2f& pos) {
	destPos_ = pos;

	x_.animateFromTo(pos_.x, destPos_.x);
	y_.animateFromTo(pos_.y, destPos_.y);

	x_.setDuration(1);
	y_.setDuration(1);

	x_.setCurve(EASE_IN);
	y_.setCurve(EASE_IN);
}

WarpZone::WarpZone() {
	name_ = "WarpZone";
	tag_ = WARPZONE;
	color_ = ofFloatColor(1, 0, 0);
	size_ = ofVec2f(40, 40);
}

void WarpZone::setup() {
	enableCollision();
}

void WarpZone::update(float deltaTime) {
	x_.update(deltaTime);
	y_.update(deltaTime);

	player_->setPos(ofVec2f(x_, y_));
	if (destPos_ == ofVec2f(x_, y_)) {
		destroy();
	}
}

void WarpZone::draw() {
	ofSetColor(color_);
	ofDrawRectangle(getRectangle());
}

void WarpZone::onCollision(Actor* c_actor) {
	if (c_actor->getTag() == PLAYER) {
		color_ = ofFloatColor(0, 0, 0, 0);
		player_ = dynamic_cast<Player*>(c_actor);
		enableUpdate();
	}
}<commit_msg>warpZone.cpp update()とonCollision()を少し書き換えました<commit_after>
#include "precompiled.h"

void WarpZone::setDistination(ofVec2f& pos) {
	destPos_ = pos;

	x_.animateFromTo(pos_.x, destPos_.x);
	y_.animateFromTo(pos_.y, destPos_.y);

	x_.setDuration(1);
	y_.setDuration(1);

	x_.setCurve(EASE_IN);
	y_.setCurve(EASE_IN);
}

WarpZone::WarpZone() {
	name_ = "WarpZone";
	tag_ = WARPZONE;
	color_ = ofFloatColor(1, 0, 0);
	size_ = ofVec2f(40, 40);
}

void WarpZone::setup() {
	enableCollision();
}

void WarpZone::update(float deltaTime) {
	if (!player_) { return; }
	x_.update(deltaTime);
	y_.update(deltaTime);

	player_->setPos(ofVec2f(x_, y_));
	if (destPos_ == ofVec2f(x_, y_)) {
		destroy();
	}
}

void WarpZone::draw() {
	ofSetColor(color_);
	ofDrawRectangle(getRectangle());
}

void WarpZone::onCollision(Actor* c_actor) {
	if (player_) { return; }
	if (c_actor->getTag() == PLAYER) {
		color_ = ofFloatColor(0, 0, 0, 0);
		player_ = dynamic_cast<Player*>(c_actor);
		enableUpdate();
	}
}<|endoftext|>


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

#include "layout.h++"

#include <utility>

namespace skui
{
  namespace gui
  {
    layout::~layout() = default;

    layout::layout(element_ptrs children)
      : children{std::move(children)}
      , spacing{0}
    {
      spacing.value_changed.connect(this, &element::invalidate);
    }

    void layout::draw(graphics::canvas& canvas, const graphics::scalar_position& position) const
    {
      auto child_offsets = calculate_child_offsets(canvas);

      for(std::size_t i = 0; i < children.size(); ++i)
      {
        children[i]->draw(canvas, position + child_offsets[i]);
      }
    }
  }
}
<commit_msg>Take padding into account in layout<commit_after>/**
 * The MIT License (MIT)
 *
 * Copyright © 2018 Ruben Van Boxem
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 **/

#include "layout.h++"

#include <utility>

namespace skui
{
  namespace gui
  {
    layout::~layout() = default;

    layout::layout(element_ptrs children)
      : children{std::move(children)}
      , spacing{0}
    {
      spacing.value_changed.connect(this, &element::invalidate);
    }

    void layout::draw(graphics::canvas& canvas, const graphics::scalar_position& position) const
    {
      auto child_offsets = calculate_child_offsets(canvas);
      const auto padded_position = position + graphics::scalar_position{padding.left, padding.right};
      std::for_each(child_offsets.begin(), child_offsets.end(),
                    [&padded_position](auto& offset) { offset += padded_position; });

      for(std::size_t i = 0; i < children.size(); ++i)
      {
        children[i]->draw(canvas, child_offsets[i]);
      }
    }
  }
}
<|endoftext|>