<commit_before>/*************************************************************************
 *
 *  $RCSfile: countermain.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: kz $ $Date: 2006-11-06 15:07:28 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  the BSD license.
 *
 *  Copyright (c) 2003 by Sun Microsystems, 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.
 *  3. Neither the name of Sun Microsystems, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND 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 THE
 *  COPYRIGHT OWNER OR 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.
 *
 *************************************************************************/

/*************************************************************************
 *************************************************************************
 *
 * simple client application registering and using the counter component.
 *
 *************************************************************************
 *************************************************************************/

#include <stdio.h>

#include <rtl/ustring.hxx>

#include <osl/diagnose.h>

#include <cppuhelper/bootstrap.hxx>

// generated c++ interfaces
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/registry/XImplementationRegistration.hpp>
#include <foo/XCountable.hpp>

using namespace foo;
using namespace cppu;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::registry;

using namespace ::rtl;

//=======================================================================
int SAL_CALL main(int argc, char **argv)
{
    Reference< XSimpleRegistry > xReg = createSimpleRegistry();
    OSL_ENSURE( xReg.is(), "### cannot get service instance of \"com.sun.star.regiystry.SimpleRegistry\"!" );

    xReg->open(OUString::createFromAscii("counter.uno.rdb"), sal_False, sal_False);
    OSL_ENSURE( xReg->isValid(), "### cannot open test registry \"counter.uno.rdb\"!" );

    Reference< XComponentContext > xContext = bootstrap_InitialComponentContext(xReg);
    OSL_ENSURE( xContext.is(), "### cannot creage intial component context!" );

    Reference< XMultiComponentFactory > xMgr = xContext->getServiceManager();
    OSL_ENSURE( xMgr.is(), "### cannot get initial service manager!" );

    // register my counter component
    Reference< XImplementationRegistration > xImplReg(
        xMgr->createInstanceWithContext(OUString::createFromAscii("com.sun.star.registry.ImplementationRegistration"), xContext), UNO_QUERY);
    OSL_ENSURE( xImplReg.is(), "### cannot get service instance of \"com.sun.star.registry.ImplementationRegistration\"!" );

    if (xImplReg.is())
    {
        xImplReg->registerImplementation(
            OUString::createFromAscii("com.sun.star.loader.SharedLibrary"), // loader for component
#ifdef UNX
#ifdef MACOSX
            OUString::createFromAscii("counter.uno.dylib"),     // component location
#else
            OUString::createFromAscii("counter.uno.so"),        // component location
#endif
#else
            OUString::createFromAscii("counter.uno.dll"),       // component location
#endif
            Reference< XSimpleRegistry >()   // registry omitted,
                                             // defaulting to service manager registry used
            );

        // get a counter instance
        Reference< XInterface > xx ;
        xx = xMgr->createInstanceWithContext(OUString::createFromAscii("foo.Counter"), xContext);
        Reference< XCountable > xCount( xx, UNO_QUERY );
        OSL_ENSURE( xCount.is(), "### cannot get service instance of \"foo.Counter\"!" );

        if (xCount.is())
        {
            xCount->setCount( 42 );
            fprintf( stdout , "%d," , xCount->getCount() );
            fprintf( stdout , "%d," , xCount->increment() );
            fprintf( stdout , "%d\n" , xCount->decrement() );
        }
    }

    Reference< XComponent >::query( xContext )->dispose();
    return 0;
}
<commit_msg>INTEGRATION: CWS jsc20 (1.8.84); FILE MERGED 2008/01/03 15:23:32 jsc 1.8.84.1: #i84966# add missing include<commit_after>/*************************************************************************
 *
 *  $RCSfile: countermain.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: vg $ $Date: 2008-01-28 16:30:31 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  the BSD license.
 *
 *  Copyright (c) 2003 by Sun Microsystems, 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.
 *  3. Neither the name of Sun Microsystems, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND 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 THE
 *  COPYRIGHT OWNER OR 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.
 *
 *************************************************************************/

/*************************************************************************
 *************************************************************************
 *
 * simple client application registering and using the counter component.
 *
 *************************************************************************
 *************************************************************************/

#include <stdio.h>

#include <rtl/ustring.hxx>

#include <osl/diagnose.h>

#include <cppuhelper/bootstrap.hxx>

// generated c++ interfaces
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XMultiComponentFactory.hpp>
#include <com/sun/star/registry/XImplementationRegistration.hpp>
#include <foo/XCountable.hpp>

using namespace foo;
using namespace cppu;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::registry;

using namespace ::rtl;

//=======================================================================
int SAL_CALL main(int argc, char **argv)
{
    Reference< XSimpleRegistry > xReg = createSimpleRegistry();
    OSL_ENSURE( xReg.is(), "### cannot get service instance of \"com.sun.star.regiystry.SimpleRegistry\"!" );

    xReg->open(OUString::createFromAscii("counter.uno.rdb"), sal_False, sal_False);
    OSL_ENSURE( xReg->isValid(), "### cannot open test registry \"counter.uno.rdb\"!" );

    Reference< XComponentContext > xContext = bootstrap_InitialComponentContext(xReg);
    OSL_ENSURE( xContext.is(), "### cannot creage intial component context!" );

    Reference< XMultiComponentFactory > xMgr = xContext->getServiceManager();
    OSL_ENSURE( xMgr.is(), "### cannot get initial service manager!" );

    // register my counter component
    Reference< XImplementationRegistration > xImplReg(
        xMgr->createInstanceWithContext(OUString::createFromAscii("com.sun.star.registry.ImplementationRegistration"), xContext), UNO_QUERY);
    OSL_ENSURE( xImplReg.is(), "### cannot get service instance of \"com.sun.star.registry.ImplementationRegistration\"!" );

    if (xImplReg.is())
    {
        xImplReg->registerImplementation(
            OUString::createFromAscii("com.sun.star.loader.SharedLibrary"), // loader for component
#ifdef UNX
#ifdef MACOSX
            OUString::createFromAscii("counter.uno.dylib"),     // component location
#else
            OUString::createFromAscii("counter.uno.so"),        // component location
#endif
#else
            OUString::createFromAscii("counter.uno.dll"),       // component location
#endif
            Reference< XSimpleRegistry >()   // registry omitted,
                                             // defaulting to service manager registry used
            );

        // get a counter instance
        Reference< XInterface > xx ;
        xx = xMgr->createInstanceWithContext(OUString::createFromAscii("foo.Counter"), xContext);
        Reference< XCountable > xCount( xx, UNO_QUERY );
        OSL_ENSURE( xCount.is(), "### cannot get service instance of \"foo.Counter\"!" );

        if (xCount.is())
        {
            xCount->setCount( 42 );
            fprintf( stdout , "%d," , xCount->getCount() );
            fprintf( stdout , "%d," , xCount->increment() );
            fprintf( stdout , "%d\n" , xCount->decrement() );
        }
    }

    Reference< XComponent >::query( xContext )->dispose();
    return 0;
}
<|endoftext|>


<commit_before>#include "MemoryAllocator.h"

#include <iostream>

const int SIZE_BLOCK = 22;

void roundUp(size_t&);

MemoryAllocator::MemoryAllocator() {
	this->pBlock = new (std::nothrow) value_type[SIZE_BLOCK];

	*pBlock = SIZE_BLOCK * 8 - 8 - 8; // header
	*(pBlock + SIZE_BLOCK - 1) = SIZE_BLOCK * 8 - 8 - 8; // footer

	pStartBlock = pBlock;
	pEndBlock = (pBlock + SIZE_BLOCK - 1);

	//for (int i = 0; i < 50; i++) {
	//	std::cout << "pBlock[" << i << "] = " << pBlock[i] << std::endl;
	//}
}

MemoryAllocator::~MemoryAllocator() {
	for (int i = 0; i < SIZE_BLOCK; i++) {
		std::cout << "pBlock[" << i << "] = " << pBlock[i] << std::endl;
	}

	delete this->pBlock;
}

value_type* MemoryAllocator::MyMalloc(size_t bytes) {
	value_type* startPointerBlock = this->pBlock;

	roundUp(bytes);

	if (bytes > SIZE_BLOCK * 8 - 8 - 8) {
		std::cerr << "ERROR! There is not enough memory." << std::endl;
		return NULL;
	}

	if (*startPointerBlock % 8 == 0) {
		value_type* pUserBlock = startPointerBlock + 1;

		size_t newHeaderBytes = bytes;
		newHeaderBytes |= 1; // set the bit to 1
		size_t oldHeaderBytes = *startPointerBlock;
		*startPointerBlock = newHeaderBytes;
		startPointerBlock += bytes / 8 + 1;
		*startPointerBlock = bytes;
		startPointerBlock += 1;
		*startPointerBlock = oldHeaderBytes - bytes - 8 - 8;
		startPointerBlock += *startPointerBlock / 8 + 1;
		*startPointerBlock = oldHeaderBytes - bytes - 8 - 8;

		return pUserBlock;
	}
	else {
		while (*startPointerBlock % 8 != 0 && startPointerBlock >= pStartBlock && startPointerBlock <= pEndBlock) {
			startPointerBlock += *startPointerBlock / 8 + 2;
		}
		bool isLastAvailableBlock = false;
		if (*startPointerBlock / 8 + 2) {
			isLastAvailableBlock = true;
		}

		if ((bytes + 8 + 8 > *startPointerBlock && ! isLastAvailableBlock) || *startPointerBlock % 8 != 0 || *startPointerBlock == 0) {
			std::cerr << "ERROR! There is not enough memory." << std::endl;
			return NULL;
		}

		value_type* pUserBlock = startPointerBlock + 1;

		if (isLastAvailableBlock && bytes == *startPointerBlock) {
			size_t newHeaderBytes = bytes;
			newHeaderBytes |= 1; // set the bit to 1
			size_t oldHeaderBytes = *startPointerBlock;
			*startPointerBlock = newHeaderBytes;
			startPointerBlock += bytes / 8 + 1;
			*startPointerBlock = bytes;
		}
		else {
			if (isLastAvailableBlock && bytes + 8 + 8 > *startPointerBlock) {
				std::cerr << "ERROR! There is not enough memory." << std::endl;
				return NULL;
			}
			size_t newHeaderBytes = bytes;
			newHeaderBytes |= 1; // set the bit to 1
			size_t oldHeaderBytes = *startPointerBlock;
			*startPointerBlock = newHeaderBytes;
			startPointerBlock += bytes / 8 + 1;
			*startPointerBlock = bytes;
			startPointerBlock += 1;
			*startPointerBlock = oldHeaderBytes - bytes - 8 - 8;
			startPointerBlock += *startPointerBlock / 8 + 1;
			*startPointerBlock = oldHeaderBytes - bytes - 8 - 8;
		}

		return pUserBlock;

	}

	return NULL;
}

void MemoryAllocator::MyFree(value_type* pBlock) {
	if (pBlock == NULL) {
		std::cerr << "ERROR! Wrong address." << std::endl;
		return;
	}

	value_type* currentHeader = pBlock - 1;
	//std::cout << "currentHeader: " << *currentHeader << std::endl;

	value_type* leftHeader = currentHeader - (*(currentHeader - 1) / 8) - 2;
	//std::cout << "leftHeader: " << *leftHeader << std::endl;

	value_type* rightHeader = currentHeader + *currentHeader / 8 + 2;
	//std::cout << "rightHeader: " << *rightHeader << std::endl;

	if (currentHeader < pStartBlock || currentHeader > pEndBlock) {
		std::cerr << "ERROR! Wrong address." << std::endl;
		return;
	}

	if (*leftHeader % 8 != 0 && *rightHeader % 8 != 0 && leftHeader >= pStartBlock && rightHeader <= pEndBlock) {
		std::cout << "-----first case" << std::endl;
		*currentHeader &= ~1;
	}
	else if (*leftHeader % 8 == 0 && *rightHeader % 8 == 0 && leftHeader >= pStartBlock && rightHeader <= pEndBlock) {
		std::cout << "-----fourth case" << std::endl;
		*currentHeader &= ~1;
		size_t newHeaderBytes = *currentHeader + *leftHeader + 8 + 8 + *rightHeader + 8 + 8;
		currentHeader -= 1;
		currentHeader -= (*currentHeader / 8 + 1);
		*currentHeader = newHeaderBytes;
		currentHeader += *currentHeader / 8 + 1;
		*currentHeader = newHeaderBytes;
	}
	else if (*rightHeader % 8 == 0 && rightHeader <= pEndBlock) {
		std::cout << "-----second case" << std::endl;
		*currentHeader &= ~1;
		size_t newHeaderBytes = *currentHeader + *rightHeader + 8 + 8;
		*currentHeader = newHeaderBytes;
		currentHeader += *currentHeader / 8 + 1;
		*currentHeader = newHeaderBytes;

	}
	else if (*leftHeader % 8 == 0 && leftHeader >= pStartBlock) {
		std::cout << "-----third case" << std::endl;
		*currentHeader &= ~1;
		size_t newHeaderBytes = *currentHeader + *leftHeader + 8 + 8;
		currentHeader -= 1;
		currentHeader -= (*currentHeader / 8 + 1);
		*currentHeader = newHeaderBytes;
		currentHeader += *currentHeader / 8 + 1;
		*currentHeader = newHeaderBytes;

	}
	else {
		std::cout << "fifth case" << std::endl;

		if (leftHeader < pStartBlock && *rightHeader % 8 != 0) {
			*currentHeader &= ~1;
		}

		if (rightHeader > pEndBlock && *leftHeader % 8 != 0) {
			*currentHeader &= ~1;
		}
	}

}

void roundUp(size_t& bytes) {
	if (bytes % 8 != 0) {
		bytes = bytes - (bytes % 8) + 8;
	}
}<commit_msg>Add BLOCK_ALIGNMENT constant.<commit_after>#include "MemoryAllocator.h"

#include <iostream>

const int SIZE_BLOCK = 22;
const int BLOCK_ALIGNMENT = 8;

void roundUp(size_t&);

MemoryAllocator::MemoryAllocator() {
	this->pBlock = new (std::nothrow) value_type[SIZE_BLOCK];

	*pBlock = SIZE_BLOCK * BLOCK_ALIGNMENT - BLOCK_ALIGNMENT - BLOCK_ALIGNMENT; // header
	*(pBlock + SIZE_BLOCK - 1) = SIZE_BLOCK * BLOCK_ALIGNMENT - BLOCK_ALIGNMENT - BLOCK_ALIGNMENT; // footer

	pStartBlock = pBlock;
	pEndBlock = (pBlock + SIZE_BLOCK - 1);

	//for (int i = 0; i < 50; i++) {
	//	std::cout << "pBlock[" << i << "] = " << pBlock[i] << std::endl;
	//}
}

MemoryAllocator::~MemoryAllocator() {
	for (int i = 0; i < SIZE_BLOCK; i++) {
		std::cout << "pBlock[" << i << "] = " << pBlock[i] << std::endl;
	}

	delete this->pBlock;
}

value_type* MemoryAllocator::MyMalloc(size_t bytes) {
	value_type* startPointerBlock = this->pBlock;

	roundUp(bytes);

	if (bytes > SIZE_BLOCK * BLOCK_ALIGNMENT - BLOCK_ALIGNMENT - BLOCK_ALIGNMENT) {
		std::cerr << "ERROR! There is not enough memory." << std::endl;
		return NULL;
	}

	if (*startPointerBlock % BLOCK_ALIGNMENT == 0) {
		value_type* pUserBlock = startPointerBlock + 1;

		size_t newHeaderBytes = bytes;
		newHeaderBytes |= 1; // set the bit to 1
		size_t oldHeaderBytes = *startPointerBlock;
		*startPointerBlock = newHeaderBytes;
		startPointerBlock += bytes / BLOCK_ALIGNMENT + 1;
		*startPointerBlock = bytes;
		startPointerBlock += 1;
		*startPointerBlock = oldHeaderBytes - bytes - BLOCK_ALIGNMENT - BLOCK_ALIGNMENT;
		startPointerBlock += *startPointerBlock / BLOCK_ALIGNMENT + 1;
		*startPointerBlock = oldHeaderBytes - bytes - BLOCK_ALIGNMENT - BLOCK_ALIGNMENT;

		return pUserBlock;
	}
	else {
		while (*startPointerBlock % BLOCK_ALIGNMENT != 0 && startPointerBlock >= pStartBlock && startPointerBlock <= pEndBlock) {
			startPointerBlock += *startPointerBlock / BLOCK_ALIGNMENT + 2;
		}
		bool isLastAvailableBlock = false;
		if (*startPointerBlock / BLOCK_ALIGNMENT + 2) {
			isLastAvailableBlock = true;
		}

		if ((bytes + BLOCK_ALIGNMENT + BLOCK_ALIGNMENT > *startPointerBlock && !isLastAvailableBlock) || *startPointerBlock % BLOCK_ALIGNMENT != 0 || *startPointerBlock == 0) {
			std::cerr << "ERROR! There is not enough memory." << std::endl;
			return NULL;
		}

		value_type* pUserBlock = startPointerBlock + 1;

		if (isLastAvailableBlock && bytes == *startPointerBlock) {
			size_t newHeaderBytes = bytes;
			newHeaderBytes |= 1; // set the bit to 1
			size_t oldHeaderBytes = *startPointerBlock;
			*startPointerBlock = newHeaderBytes;
			startPointerBlock += bytes / BLOCK_ALIGNMENT + 1;
			*startPointerBlock = bytes;
		}
		else {
			if (isLastAvailableBlock && bytes + BLOCK_ALIGNMENT + BLOCK_ALIGNMENT > *startPointerBlock) {
				std::cerr << "ERROR! There is not enough memory." << std::endl;
				return NULL;
			}
			size_t newHeaderBytes = bytes;
			newHeaderBytes |= 1; // set the bit to 1
			size_t oldHeaderBytes = *startPointerBlock;
			*startPointerBlock = newHeaderBytes;
			startPointerBlock += bytes / BLOCK_ALIGNMENT + 1;
			*startPointerBlock = bytes;
			startPointerBlock += 1;
			*startPointerBlock = oldHeaderBytes - bytes - BLOCK_ALIGNMENT - BLOCK_ALIGNMENT;
			startPointerBlock += *startPointerBlock / BLOCK_ALIGNMENT + 1;
			*startPointerBlock = oldHeaderBytes - bytes - BLOCK_ALIGNMENT - BLOCK_ALIGNMENT;
		}

		return pUserBlock;

	}

	return NULL;
}

void MemoryAllocator::MyFree(value_type* pBlock) {
	if (pBlock == NULL) {
		std::cerr << "ERROR! Wrong address." << std::endl;
		return;
	}

	value_type* currentHeader = pBlock - 1;
	//std::cout << "currentHeader: " << *currentHeader << std::endl;

	value_type* leftHeader = currentHeader - (*(currentHeader - 1) / BLOCK_ALIGNMENT) - 2;
	//std::cout << "leftHeader: " << *leftHeader << std::endl;

	value_type* rightHeader = currentHeader + *currentHeader / BLOCK_ALIGNMENT + 2;
	//std::cout << "rightHeader: " << *rightHeader << std::endl;

	if (currentHeader < pStartBlock || currentHeader > pEndBlock) {
		std::cerr << "ERROR! Wrong address." << std::endl;
		return;
	}

	if (*leftHeader % BLOCK_ALIGNMENT != 0 && *rightHeader % BLOCK_ALIGNMENT != 0 && leftHeader >= pStartBlock && rightHeader <= pEndBlock) {
		std::cout << "-----first case" << std::endl;
		*currentHeader &= ~1;
	}
	else if (*leftHeader % BLOCK_ALIGNMENT == 0 && *rightHeader % BLOCK_ALIGNMENT == 0 && leftHeader >= pStartBlock && rightHeader <= pEndBlock) {
		std::cout << "-----fourth case" << std::endl;
		*currentHeader &= ~1;
		size_t newHeaderBytes = *currentHeader + *leftHeader + BLOCK_ALIGNMENT + BLOCK_ALIGNMENT + *rightHeader + BLOCK_ALIGNMENT + BLOCK_ALIGNMENT;
		currentHeader -= 1;
		currentHeader -= (*currentHeader / BLOCK_ALIGNMENT + 1);
		*currentHeader = newHeaderBytes;
		currentHeader += *currentHeader / BLOCK_ALIGNMENT + 1;
		*currentHeader = newHeaderBytes;
	}
	else if (*rightHeader % BLOCK_ALIGNMENT == 0 && rightHeader <= pEndBlock) {
		std::cout << "-----second case" << std::endl;
		*currentHeader &= ~1;
		size_t newHeaderBytes = *currentHeader + *rightHeader + BLOCK_ALIGNMENT + BLOCK_ALIGNMENT;
		*currentHeader = newHeaderBytes;
		currentHeader += *currentHeader / BLOCK_ALIGNMENT + 1;
		*currentHeader = newHeaderBytes;

	}
	else if (*leftHeader % BLOCK_ALIGNMENT == 0 && leftHeader >= pStartBlock) {
		std::cout << "-----third case" << std::endl;
		*currentHeader &= ~1;
		size_t newHeaderBytes = *currentHeader + *leftHeader + BLOCK_ALIGNMENT + BLOCK_ALIGNMENT;
		currentHeader -= 1;
		currentHeader -= (*currentHeader / BLOCK_ALIGNMENT + 1);
		*currentHeader = newHeaderBytes;
		currentHeader += *currentHeader / BLOCK_ALIGNMENT + 1;
		*currentHeader = newHeaderBytes;

	}
	else {
		std::cout << "fifth case" << std::endl;

		if (leftHeader < pStartBlock && *rightHeader % BLOCK_ALIGNMENT != 0) {
			*currentHeader &= ~1;
		}

		if (rightHeader > pEndBlock && *leftHeader % BLOCK_ALIGNMENT != 0) {
			*currentHeader &= ~1;
		}
	}

}

void roundUp(size_t& bytes) {
	if (bytes % BLOCK_ALIGNMENT != 0) {
		bytes = bytes - (bytes % BLOCK_ALIGNMENT) + BLOCK_ALIGNMENT;
	}
}<|endoftext|>


<commit_before>#include <stdlib.h>
#include "license-generator.h"

int main(int argc, const char *argv[]) {
	 //license::LicenseGenerator lic;
	 return license::LicenseGenerator::generateLicense(argc, argv);

}

<commit_msg>cleanup<commit_after>#include <stdlib.h>
#include "license-generator.h"

int main(int argc, const char *argv[]) {
	 return license::LicenseGenerator::generateLicense(argc, argv);

}

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015 Samsung Electronics Co., Ltd.
 *
 * 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 <dali-toolkit/dali-toolkit.h>

using namespace Dali;
using Dali::Toolkit::Model3dView;

namespace
{
const int MODEL_NUMBER(3);

const char * const MODEL_FILE[] = {
    DEMO_MODEL_DIR "Dino.obj",
    DEMO_MODEL_DIR "ToyRobot-Metal.obj",
    DEMO_MODEL_DIR "Toyrobot-Plastic.obj"
};

const char * const MATERIAL_FILE[] = {
    DEMO_MODEL_DIR "Dino.mtl",
    DEMO_MODEL_DIR "ToyRobot-Metal.mtl",
    DEMO_MODEL_DIR "Toyrobot-Plastic.mtl"
};

const char * const IMAGE_PATH( DEMO_IMAGE_DIR "" );

const char * BACKGROUND_IMAGE( DEMO_IMAGE_DIR "background-1.jpg");

}

/*
 * This example shows how to create and display a model3d-view control.
 * The application can cycle between 3 different models, and 3 different shaders.
 * There are two animations running, one is a rotation for the model, one is a light that
 * goes from one side of the model to the other.
 * There are dedicated buttons for changing the models, the shaders and pausing the animations.
 * The animations can also be paused, resumed with the space key
 * A double tap in the model3d-view will make zoom-in/out of the zone clicked
 */

class Model3dViewController : public ConnectionTracker
{
public:

  Model3dViewController( Application& application )
  : mApplication( application )
  {
    // Connect to the Application's Init signal
    mApplication.InitSignal().Connect( this, &Model3dViewController::Create );
  }

  ~Model3dViewController()
  {
    // Nothing to do here;
  }

  // The Init signal is received once (only) during the Application lifetime
  void Create( Application& application )
  {
    // Get a handle to the stage
    Stage stage = Stage::GetCurrent();
    Vector2 screenSize = stage.GetSize();

    //Add background
    Toolkit::ImageView backView = Toolkit::ImageView::New(BACKGROUND_IMAGE);
    backView.SetAnchorPoint( AnchorPoint::TOP_LEFT );
    stage.Add(backView);

    //Add 3D model control
    m3DLayer = Layer::New();
    stage.GetRootLayer().Add(m3DLayer);

    //3D models require 3D based rendering method, so it can use depth buffer, etc.
    m3DLayer.SetBehavior(Layer::LAYER_3D);
    m3DLayer.SetParentOrigin( ParentOrigin::CENTER );
    m3DLayer.SetAnchorPoint( AnchorPoint::CENTER );

    mModelCounter = 0;

    mModel3dView = Model3dView::New( MODEL_FILE[0], MATERIAL_FILE[0], IMAGE_PATH );
    mModel3dView.SetParentOrigin( ParentOrigin::CENTER );
    mModel3dView.SetAnchorPoint( AnchorPoint::CENTER );
    mModel3dView.SetName( "model3dViewControl" );
    mModel3dView.SetResizePolicy(ResizePolicy::FIXED, Dimension::ALL_DIMENSIONS);
    mModel3dView.SetSize(screenSize);

    mModel3dView.SetProperty(Model3dView::Property::LIGHT_POSITION, Vector3(5,10.,0));

    m3DLayer.Add( mModel3dView );

    mIlluminationShader = Model3dView::IlluminationType(mModel3dView.GetProperty<int>(Model3dView::Property::ILLUMINATION_TYPE));

    mButtonLayer = Layer::New();
    mButtonLayer.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS );
    mButtonLayer.SetParentOrigin( ParentOrigin::CENTER );
    mButtonLayer.SetAnchorPoint( AnchorPoint::CENTER );
    stage.GetRootLayer().Add(mButtonLayer);

    // Create button for model changing
    Toolkit::PushButton editButton = Toolkit::PushButton::New();
    editButton.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::ALL_DIMENSIONS );
    editButton.ClickedSignal().Connect( this, &Model3dViewController::OnChangeModelClicked);
    editButton.SetParentOrigin( ParentOrigin::TOP_LEFT );
    editButton.SetAnchorPoint( AnchorPoint::TOP_LEFT );
    editButton.SetLabelText( "Change Model" );
    mButtonLayer.Add( editButton  );

    // Create button for shader changing
    editButton = Toolkit::PushButton::New();
    editButton.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::ALL_DIMENSIONS );
    editButton.ClickedSignal().Connect( this, &Model3dViewController::OnChangeLightingClicked);
    editButton.SetParentOrigin( ParentOrigin::TOP_RIGHT );
    editButton.SetAnchorPoint( AnchorPoint::TOP_RIGHT );
    editButton.SetLabelText( "Change Shader" );
    mButtonLayer.Add( editButton  );

    // Create button for pause/resume animation
    editButton = Toolkit::PushButton::New();
    editButton.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::ALL_DIMENSIONS );
    editButton.ClickedSignal().Connect( this, &Model3dViewController::OnPauseAnimationsClicked);
    editButton.SetParentOrigin( ParentOrigin::BOTTOM_CENTER );
    editButton.SetAnchorPoint( AnchorPoint::BOTTOM_CENTER );
    editButton.SetLabelText( "Pause Animations" );
    mButtonLayer.Add( editButton  );

    //Create animations
    mLightAnimation = Animation::New(6.f);
    mLightAnimation.AnimateTo(Property(mModel3dView, Model3dView::Property::LIGHT_POSITION), Vector3(-5,10.0,0), TimePeriod( 0.0f, 3.0f ));
    mLightAnimation.AnimateTo(Property(mModel3dView, Model3dView::Property::LIGHT_POSITION), Vector3(5,10.0,0), TimePeriod( 3.0f, 3.0f ));
    mLightAnimation.SetLooping(true);
    mLightAnimation.Play();

    mRotationAnimation = Animation::New(15.f);
    mRotationAnimation.AnimateBy(Property(mModel3dView, Actor::Property::ORIENTATION), Quaternion(Degree(0.f), Degree(360.f), Degree(0.f)) );
    mRotationAnimation.SetLooping(true);
    mRotationAnimation.Play();

    mPlaying = true;
    mScaled = false;

    // Respond to a click anywhere on the stage
    stage.KeyEventSignal().Connect(this, &Model3dViewController::OnKeyEvent);

    //Create a tap gesture detector for zoom
    mTapDetector = TapGestureDetector::New( 2 );
    mTapDetector.DetectedSignal().Connect(this, &Model3dViewController::OnTap);

    mTapDetector.Attach( backView );
  }

  /**
   * Main Tap event handler
   */
  void OnTap( Actor actor, const TapGesture& tap )
  {
    if (mScaled)
    {
      mModel3dView.SetScale(1.0);
      mModel3dView.SetPosition(0,0,0);
      mScaled = false;
    }
    else
    {
      Stage stage = Stage::GetCurrent();
      Vector2 screenSize = stage.GetSize();

      Vector2 position;
      position.x = tap.screenPoint.x - screenSize.x * 0.5;
      position.y = tap.screenPoint.y - screenSize.y * 0.5;

      float size = 2.5;

      mModel3dView.SetScale(size);
      mModel3dView.SetPosition(-position.x * size,-position.y * size, 0);
      mScaled = true;
    }
  }

  /**
   * Change models button signal function
   */
  bool OnChangeModelClicked(Toolkit::Button button)
  {
    mModelCounter = (mModelCounter + 1) % MODEL_NUMBER;
    mModel3dView.SetProperty(Model3dView::Property::GEOMETRY_URL, MODEL_FILE[mModelCounter]);
    mModel3dView.SetProperty(Model3dView::Property::MATERIAL_URL, MATERIAL_FILE[mModelCounter]);
    mModel3dView.SetProperty(Model3dView::Property::IMAGES_URL, IMAGE_PATH);

    return true;
  }

  /**
   * Change shader button signal function
   */
  bool OnChangeLightingClicked(Toolkit::Button button)
  {
    if( mIlluminationShader == Model3dView::DIFFUSE_WITH_NORMAL_MAP )
    {
      mModel3dView.SetProperty(Model3dView::Property::ILLUMINATION_TYPE, Model3dView::DIFFUSE_WITH_TEXTURE);
      mIlluminationShader = Model3dView::IlluminationType(mModel3dView.GetProperty<int>(Model3dView::Property::ILLUMINATION_TYPE));
    }
    else if( mIlluminationShader == Model3dView::DIFFUSE_WITH_TEXTURE )
    {
      mModel3dView.SetProperty(Model3dView::Property::ILLUMINATION_TYPE, Model3dView::DIFFUSE);
      mIlluminationShader = Model3dView::IlluminationType(mModel3dView.GetProperty<int>(Model3dView::Property::ILLUMINATION_TYPE));
   }
    else if( mIlluminationShader == Model3dView::DIFFUSE )
    {
      mModel3dView.SetProperty(Model3dView::Property::ILLUMINATION_TYPE, Model3dView::DIFFUSE_WITH_NORMAL_MAP);
      mIlluminationShader = Model3dView::IlluminationType(mModel3dView.GetProperty<int>(Model3dView::Property::ILLUMINATION_TYPE));
   }

    return true;
  }

  /**
   * Function to pause resume all animations
   */
  void PauseAnimations()
  {
    if( mPlaying )
    {
      mRotationAnimation.Pause();
      mLightAnimation.Pause();

      mPlaying = false;
    }
    else
    {
      mRotationAnimation.Play();
      mLightAnimation.Play();

      mPlaying = true;
    }
  }

  /**
   * Pause button signal function
   */
  bool OnPauseAnimationsClicked(Toolkit::Button button)
  {
    PauseAnimations();

    return true;
  }

  /**
   * Main key event handler
   */
  void OnKeyEvent(const KeyEvent& event)
  {
    if(event.state == KeyEvent::Down)
    {
      if( IsKey( event, Dali::DALI_KEY_ESCAPE) || IsKey( event, Dali::DALI_KEY_BACK) )
      {
        mApplication.Quit();
      }
      else
      {
        PauseAnimations();
      }
    }
  }

private:
  Application&  mApplication;

  int mModelCounter;
  Model3dView mModel3dView;

  Layer m3DLayer;
  Layer mButtonLayer;
  TapGestureDetector mTapDetector;

  Model3dView::IlluminationType mIlluminationShader;

  Animation mRotationAnimation;
  Animation mLightAnimation;
  bool mPlaying;

  bool mScaled;
};

void RunTest( Application& application )
{
  Model3dViewController test( application );

  application.MainLoop();
}

// Entry point for Linux & Tizen applications
//
int DALI_EXPORT_API main( int argc, char **argv )
{
  Application application = Application::New( &argc, &argv );

  RunTest( application );

  return 0;
}
<commit_msg>Model3DView does not need to set IMAGES_URL when changing model<commit_after>/*
 * Copyright (c) 2015 Samsung Electronics Co., Ltd.
 *
 * 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 <dali-toolkit/dali-toolkit.h>

using namespace Dali;
using Dali::Toolkit::Model3dView;

namespace
{
const int MODEL_NUMBER(3);

const char * const MODEL_FILE[] = {
    DEMO_MODEL_DIR "Dino.obj",
    DEMO_MODEL_DIR "ToyRobot-Metal.obj",
    DEMO_MODEL_DIR "Toyrobot-Plastic.obj"
};

const char * const MATERIAL_FILE[] = {
    DEMO_MODEL_DIR "Dino.mtl",
    DEMO_MODEL_DIR "ToyRobot-Metal.mtl",
    DEMO_MODEL_DIR "Toyrobot-Plastic.mtl"
};

const char * const IMAGE_PATH( DEMO_IMAGE_DIR "" );

const char * BACKGROUND_IMAGE( DEMO_IMAGE_DIR "background-1.jpg");

}

/*
 * This example shows how to create and display a model3d-view control.
 * The application can cycle between 3 different models, and 3 different shaders.
 * There are two animations running, one is a rotation for the model, one is a light that
 * goes from one side of the model to the other.
 * There are dedicated buttons for changing the models, the shaders and pausing the animations.
 * The animations can also be paused, resumed with the space key
 * A double tap in the model3d-view will make zoom-in/out of the zone clicked
 */

class Model3dViewController : public ConnectionTracker
{
public:

  Model3dViewController( Application& application )
  : mApplication( application )
  {
    // Connect to the Application's Init signal
    mApplication.InitSignal().Connect( this, &Model3dViewController::Create );
  }

  ~Model3dViewController()
  {
    // Nothing to do here;
  }

  // The Init signal is received once (only) during the Application lifetime
  void Create( Application& application )
  {
    // Get a handle to the stage
    Stage stage = Stage::GetCurrent();
    Vector2 screenSize = stage.GetSize();

    //Add background
    Toolkit::ImageView backView = Toolkit::ImageView::New(BACKGROUND_IMAGE);
    backView.SetAnchorPoint( AnchorPoint::TOP_LEFT );
    stage.Add(backView);

    //Add 3D model control
    m3DLayer = Layer::New();
    stage.GetRootLayer().Add(m3DLayer);

    //3D models require 3D based rendering method, so it can use depth buffer, etc.
    m3DLayer.SetBehavior(Layer::LAYER_3D);
    m3DLayer.SetParentOrigin( ParentOrigin::CENTER );
    m3DLayer.SetAnchorPoint( AnchorPoint::CENTER );

    mModelCounter = 0;

    mModel3dView = Model3dView::New( MODEL_FILE[0], MATERIAL_FILE[0], IMAGE_PATH );
    mModel3dView.SetParentOrigin( ParentOrigin::CENTER );
    mModel3dView.SetAnchorPoint( AnchorPoint::CENTER );
    mModel3dView.SetName( "model3dViewControl" );
    mModel3dView.SetResizePolicy(ResizePolicy::FIXED, Dimension::ALL_DIMENSIONS);
    mModel3dView.SetSize(screenSize);

    mModel3dView.SetProperty(Model3dView::Property::LIGHT_POSITION, Vector3(5,10.,0));

    m3DLayer.Add( mModel3dView );

    mIlluminationShader = Model3dView::IlluminationType(mModel3dView.GetProperty<int>(Model3dView::Property::ILLUMINATION_TYPE));

    mButtonLayer = Layer::New();
    mButtonLayer.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS );
    mButtonLayer.SetParentOrigin( ParentOrigin::CENTER );
    mButtonLayer.SetAnchorPoint( AnchorPoint::CENTER );
    stage.GetRootLayer().Add(mButtonLayer);

    // Create button for model changing
    Toolkit::PushButton editButton = Toolkit::PushButton::New();
    editButton.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::ALL_DIMENSIONS );
    editButton.ClickedSignal().Connect( this, &Model3dViewController::OnChangeModelClicked);
    editButton.SetParentOrigin( ParentOrigin::TOP_LEFT );
    editButton.SetAnchorPoint( AnchorPoint::TOP_LEFT );
    editButton.SetLabelText( "Change Model" );
    mButtonLayer.Add( editButton  );

    // Create button for shader changing
    editButton = Toolkit::PushButton::New();
    editButton.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::ALL_DIMENSIONS );
    editButton.ClickedSignal().Connect( this, &Model3dViewController::OnChangeLightingClicked);
    editButton.SetParentOrigin( ParentOrigin::TOP_RIGHT );
    editButton.SetAnchorPoint( AnchorPoint::TOP_RIGHT );
    editButton.SetLabelText( "Change Shader" );
    mButtonLayer.Add( editButton  );

    // Create button for pause/resume animation
    editButton = Toolkit::PushButton::New();
    editButton.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::ALL_DIMENSIONS );
    editButton.ClickedSignal().Connect( this, &Model3dViewController::OnPauseAnimationsClicked);
    editButton.SetParentOrigin( ParentOrigin::BOTTOM_CENTER );
    editButton.SetAnchorPoint( AnchorPoint::BOTTOM_CENTER );
    editButton.SetLabelText( "Pause Animations" );
    mButtonLayer.Add( editButton  );

    //Create animations
    mLightAnimation = Animation::New(6.f);
    mLightAnimation.AnimateTo(Property(mModel3dView, Model3dView::Property::LIGHT_POSITION), Vector3(-5,10.0,0), TimePeriod( 0.0f, 3.0f ));
    mLightAnimation.AnimateTo(Property(mModel3dView, Model3dView::Property::LIGHT_POSITION), Vector3(5,10.0,0), TimePeriod( 3.0f, 3.0f ));
    mLightAnimation.SetLooping(true);
    mLightAnimation.Play();

    mRotationAnimation = Animation::New(15.f);
    mRotationAnimation.AnimateBy(Property(mModel3dView, Actor::Property::ORIENTATION), Quaternion(Degree(0.f), Degree(360.f), Degree(0.f)) );
    mRotationAnimation.SetLooping(true);
    mRotationAnimation.Play();

    mPlaying = true;
    mScaled = false;

    // Respond to a click anywhere on the stage
    stage.KeyEventSignal().Connect(this, &Model3dViewController::OnKeyEvent);

    //Create a tap gesture detector for zoom
    mTapDetector = TapGestureDetector::New( 2 );
    mTapDetector.DetectedSignal().Connect(this, &Model3dViewController::OnTap);

    mTapDetector.Attach( backView );
  }

  /**
   * Main Tap event handler
   */
  void OnTap( Actor actor, const TapGesture& tap )
  {
    if (mScaled)
    {
      mModel3dView.SetScale(1.0);
      mModel3dView.SetPosition(0,0,0);
      mScaled = false;
    }
    else
    {
      Stage stage = Stage::GetCurrent();
      Vector2 screenSize = stage.GetSize();

      Vector2 position;
      position.x = tap.screenPoint.x - screenSize.x * 0.5;
      position.y = tap.screenPoint.y - screenSize.y * 0.5;

      float size = 2.5;

      mModel3dView.SetScale(size);
      mModel3dView.SetPosition(-position.x * size,-position.y * size, 0);
      mScaled = true;
    }
  }

  /**
   * Change models button signal function
   */
  bool OnChangeModelClicked(Toolkit::Button button)
  {
    mModelCounter = (mModelCounter + 1) % MODEL_NUMBER;
    mModel3dView.SetProperty(Model3dView::Property::GEOMETRY_URL, MODEL_FILE[mModelCounter]);
    mModel3dView.SetProperty(Model3dView::Property::MATERIAL_URL, MATERIAL_FILE[mModelCounter]);
    return true;
  }

  /**
   * Change shader button signal function
   */
  bool OnChangeLightingClicked(Toolkit::Button button)
  {
    if( mIlluminationShader == Model3dView::DIFFUSE_WITH_NORMAL_MAP )
    {
      mModel3dView.SetProperty(Model3dView::Property::ILLUMINATION_TYPE, Model3dView::DIFFUSE_WITH_TEXTURE);
      mIlluminationShader = Model3dView::IlluminationType(mModel3dView.GetProperty<int>(Model3dView::Property::ILLUMINATION_TYPE));
    }
    else if( mIlluminationShader == Model3dView::DIFFUSE_WITH_TEXTURE )
    {
      mModel3dView.SetProperty(Model3dView::Property::ILLUMINATION_TYPE, Model3dView::DIFFUSE);
      mIlluminationShader = Model3dView::IlluminationType(mModel3dView.GetProperty<int>(Model3dView::Property::ILLUMINATION_TYPE));
   }
    else if( mIlluminationShader == Model3dView::DIFFUSE )
    {
      mModel3dView.SetProperty(Model3dView::Property::ILLUMINATION_TYPE, Model3dView::DIFFUSE_WITH_NORMAL_MAP);
      mIlluminationShader = Model3dView::IlluminationType(mModel3dView.GetProperty<int>(Model3dView::Property::ILLUMINATION_TYPE));
   }

    return true;
  }

  /**
   * Function to pause resume all animations
   */
  void PauseAnimations()
  {
    if( mPlaying )
    {
      mRotationAnimation.Pause();
      mLightAnimation.Pause();

      mPlaying = false;
    }
    else
    {
      mRotationAnimation.Play();
      mLightAnimation.Play();

      mPlaying = true;
    }
  }

  /**
   * Pause button signal function
   */
  bool OnPauseAnimationsClicked(Toolkit::Button button)
  {
    PauseAnimations();

    return true;
  }

  /**
   * Main key event handler
   */
  void OnKeyEvent(const KeyEvent& event)
  {
    if(event.state == KeyEvent::Down)
    {
      if( IsKey( event, Dali::DALI_KEY_ESCAPE) || IsKey( event, Dali::DALI_KEY_BACK) )
      {
        mApplication.Quit();
      }
      else
      {
        PauseAnimations();
      }
    }
  }

private:
  Application&  mApplication;

  int mModelCounter;
  Model3dView mModel3dView;

  Layer m3DLayer;
  Layer mButtonLayer;
  TapGestureDetector mTapDetector;

  Model3dView::IlluminationType mIlluminationShader;

  Animation mRotationAnimation;
  Animation mLightAnimation;
  bool mPlaying;

  bool mScaled;
};

void RunTest( Application& application )
{
  Model3dViewController test( application );

  application.MainLoop();
}

// Entry point for Linux & Tizen applications
//
int DALI_EXPORT_API main( int argc, char **argv )
{
  Application application = Application::New( &argc, &argv );

  RunTest( application );

  return 0;
}
<|endoftext|>


<commit_before>//-----------------------------------------------
//
//	This file is part of the Siv3D Engine.
//
//	Copyright (c) 2008-2021 Ryo Suzuki
//	Copyright (c) 2016-2021 OpenSiv3D Project
//
//	Licensed under the MIT License.
//
//-----------------------------------------------

# include <Siv3D/Script.hpp>
# include <Siv3D/Polygon.hpp>
# include "ScriptBind.hpp"
# include "../angelScript/scriptarray.h"

namespace s3d
{
	using namespace AngelScript;

	using ShapeType = Polygon;

	static void DefaultConstruct(ShapeType* self)
	{
		new(self) ShapeType();
	}

	static void CopyConstruct(const Polygon& other, ShapeType* self)
	{
		new(self) ShapeType(other);
	}

	static void ConstructS(const Shape2D& shape2D, ShapeType* self)
	{
		new(self) ShapeType(shape2D);
	}

	static void Destruct(ShapeType* self)
	{
		self->~Polygon();
	}

	static void ListConstruct(const void* list, ShapeType* self)
	{
		const size_t length = *static_cast<const asUINT*>(list);
		const Vec2* data = static_cast<const Vec2*>(static_cast<const void*>(static_cast<const uint8*>(list) + 4));
		new(self) ShapeType(data, length);
	}

	static CScriptArray* Outer(const Polygon& self)
	{
		asITypeInfo* typeID = asGetActiveContext()->GetEngine()->GetTypeInfoByDecl("Array<Vec2>");

		if (void* mem = std::malloc(self.outer().size_bytes() + sizeof(asUINT)))
		{
			*(asUINT*)mem = static_cast<asUINT>(self.outer().size());
			std::memcpy(((asUINT*)mem) + 1, self.outer().data(), self.outer().size_bytes());

			const auto p = CScriptArray::Create(typeID, mem);
			std::free(mem);

			return p;
		}
		else
		{
			return nullptr;
		}
	}

	static bool ConvToBool(const Polygon& polygon)
	{
		return !polygon.isEmpty();
	}

	void RegisterPolygon(asIScriptEngine* engine)
	{
		constexpr char TypeName[] = "Polygon";

		int32 r = 0;
		r = engine->RegisterObjectBehaviour(TypeName, asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(DefaultConstruct), asCALL_CDECL_OBJLAST); assert(r >= 0);
		r = engine->RegisterObjectBehaviour(TypeName, asBEHAVE_CONSTRUCT, "void f(const Polygon& in)", asFUNCTION(CopyConstruct), asCALL_CDECL_OBJLAST); assert(r >= 0);
		r = engine->RegisterObjectBehaviour(TypeName, asBEHAVE_DESTRUCT, "void f()", asFUNCTION(Destruct), asCALL_CDECL_OBJLAST); assert(r >= 0);
		//r = engine->RegisterObjectBehaviour(TypeName, asBEHAVE_CONSTRUCT, "void f(const Shape2D& in)", asFUNCTION(ConstructS), asCALL_CDECL_OBJLAST); assert(r >= 0);
		r = engine->RegisterObjectBehaviour(TypeName, asBEHAVE_LIST_CONSTRUCT, "void f(const Vec2& in) {repeat Vec2}", asFUNCTION(ListConstruct), asCALL_CDECL_OBJLAST); assert(r >= 0);

	}
}
<commit_msg>[Linux] fix<commit_after>//-----------------------------------------------
//
//	This file is part of the Siv3D Engine.
//
//	Copyright (c) 2008-2021 Ryo Suzuki
//	Copyright (c) 2016-2021 OpenSiv3D Project
//
//	Licensed under the MIT License.
//
//-----------------------------------------------

# include <Siv3D/Script.hpp>
# include <Siv3D/Polygon.hpp>
# include "ScriptBind.hpp"
# include "../angelscript/scriptarray.h"

namespace s3d
{
	using namespace AngelScript;

	using ShapeType = Polygon;

	static void DefaultConstruct(ShapeType* self)
	{
		new(self) ShapeType();
	}

	static void CopyConstruct(const Polygon& other, ShapeType* self)
	{
		new(self) ShapeType(other);
	}

	static void ConstructS(const Shape2D& shape2D, ShapeType* self)
	{
		new(self) ShapeType(shape2D);
	}

	static void Destruct(ShapeType* self)
	{
		self->~Polygon();
	}

	static void ListConstruct(const void* list, ShapeType* self)
	{
		const size_t length = *static_cast<const asUINT*>(list);
		const Vec2* data = static_cast<const Vec2*>(static_cast<const void*>(static_cast<const uint8*>(list) + 4));
		new(self) ShapeType(data, length);
	}

	static CScriptArray* Outer(const Polygon& self)
	{
		asITypeInfo* typeID = asGetActiveContext()->GetEngine()->GetTypeInfoByDecl("Array<Vec2>");

		if (void* mem = std::malloc(self.outer().size_bytes() + sizeof(asUINT)))
		{
			*(asUINT*)mem = static_cast<asUINT>(self.outer().size());
			std::memcpy(((asUINT*)mem) + 1, self.outer().data(), self.outer().size_bytes());

			const auto p = CScriptArray::Create(typeID, mem);
			std::free(mem);

			return p;
		}
		else
		{
			return nullptr;
		}
	}

	static bool ConvToBool(const Polygon& polygon)
	{
		return !polygon.isEmpty();
	}

	void RegisterPolygon(asIScriptEngine* engine)
	{
		constexpr char TypeName[] = "Polygon";

		int32 r = 0;
		r = engine->RegisterObjectBehaviour(TypeName, asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(DefaultConstruct), asCALL_CDECL_OBJLAST); assert(r >= 0);
		r = engine->RegisterObjectBehaviour(TypeName, asBEHAVE_CONSTRUCT, "void f(const Polygon& in)", asFUNCTION(CopyConstruct), asCALL_CDECL_OBJLAST); assert(r >= 0);
		r = engine->RegisterObjectBehaviour(TypeName, asBEHAVE_DESTRUCT, "void f()", asFUNCTION(Destruct), asCALL_CDECL_OBJLAST); assert(r >= 0);
		//r = engine->RegisterObjectBehaviour(TypeName, asBEHAVE_CONSTRUCT, "void f(const Shape2D& in)", asFUNCTION(ConstructS), asCALL_CDECL_OBJLAST); assert(r >= 0);
		r = engine->RegisterObjectBehaviour(TypeName, asBEHAVE_LIST_CONSTRUCT, "void f(const Vec2& in) {repeat Vec2}", asFUNCTION(ListConstruct), asCALL_CDECL_OBJLAST); assert(r >= 0);

	}
}
<|endoftext|>


<commit_before>#include "cropeditor.hpp"

#include "cropscene.hpp"
#include "cropview.hpp"
#include <QApplication>
#include <QGraphicsPixmapItem>
#include <QGraphicsView>
#include <QScreen>
#include <QTimer>
#include <settings.hpp>

CropEditor::CropEditor(QPixmap *image, QObject *parent) : QObject(parent) {
    scene = new CropScene(parent, image);
    view = new CropView(scene);
    qreal ratio = QApplication::primaryScreen()->devicePixelRatio();
    pixmapItem = new QGraphicsPixmapItem(*image);
    pixmapItem->setZValue(-1);
    pixmapItem->setScale(1 / ratio);
    scene->addItem(pixmapItem);
    scene->setSceneRect(image->rect());
    view->resize(image->width(), image->height());
    view->setMinimumSize(image->size());
    view->move(0, 0);
    view->show();

    connect(scene, &CropScene::closedWithRect, this, &CropEditor::crop);
}

CropEditor::~CropEditor() {
    delete scene;
    delete view;
}

void CropEditor::crop(QRect rect) {
    QPixmap map = view->grab(rect);
    QPixmap *cropp = new QPixmap;
    map.swap(*cropp);
    delete view;
    emit cropped(cropp);
}
<commit_msg>Crop editor finally has a title<commit_after>#include "cropeditor.hpp"

#include "cropscene.hpp"
#include "cropview.hpp"
#include <QApplication>
#include <QGraphicsPixmapItem>
#include <QGraphicsView>
#include <QScreen>
#include <QTimer>
#include <settings.hpp>

CropEditor::CropEditor(QPixmap *image, QObject *parent) : QObject(parent) {
    scene = new CropScene(parent, image);
    view = new CropView(scene);
    qreal ratio = QApplication::primaryScreen()->devicePixelRatio();
    pixmapItem = new QGraphicsPixmapItem(*image);
    pixmapItem->setZValue(-1);
    pixmapItem->setScale(1 / ratio);
    scene->addItem(pixmapItem);
    scene->setSceneRect(image->rect());
    view->resize(image->width(), image->height());
    view->setMinimumSize(image->size());
    view->move(0, 0);
    view->setWindowTitle("KShare Crop Editor");
    view->show();

    connect(scene, &CropScene::closedWithRect, this, &CropEditor::crop);
}

CropEditor::~CropEditor() {
    delete scene;
    delete view;
}

void CropEditor::crop(QRect rect) {
    QPixmap map = view->grab(rect);
    QPixmap *cropp = new QPixmap;
    map.swap(*cropp);
    delete view;
    emit cropped(cropp);
}
<|endoftext|>


<commit_before>#include <Maple/Gameplay/MapleGameLogic.h>
#include <Bibim/Math.h>
#include <Bibim/Assert.h>
using namespace Bibim;

namespace Maple
{
    MapleGameLogic::MapleGameLogic()
        : restLife(DefaultLife)
    {

    }

    MapleGameLogic::MapleGameLogic(int size)
        : puzzleSize(size),
          restLife(DefaultLife)
    {

    }

    MapleGameLogic::MapleGameLogic(int size, const GamePanel& ansPattern)
    {
        Initialize(size, ansPattern);
    }

    void MapleGameLogic::Initialize(int size, const GamePanel& ansPattern)
    {
        puzzleSize = size;
        restLife = DefaultLife;

        this->ansPattern = ansPattern;
    }

    void MapleGameLogic::Restart()
    {
        for(int i = 0; i < puzzleSize; i++)
        {
            for(int j = 0; j < puzzleSize; j++)
            {
                solvePattern.arr[i][j] = TableState::Uncolored;
            }
        }

        restLife = DefaultLife;
    }

    void MapleGameLogic::Update(float /*dt*/, int /*timestamp*/)
    {
        // Use this code when need to use time measure
    }

    const MapleGameLogic::GamePanel& MapleGameLogic::GetSolvePanel() const
    {
        return solvePattern;
    }

    int MapleGameLogic::GetPuzzleSize() const
    {
        return puzzleSize;
    }

    int MapleGameLogic::GetRestLife() const
    {
        return restLife;
    }

    MapleGameLogic::TryFillColorResult::T MapleGameLogic::TryFillColor()
    {
        BBAssert(cursor.X == cursorTail.X || cursor.Y == cursorTail.Y);

        // 'dic' is direction from 'cursorTail' to 'cursor'
        Point2 dic = cursor - cursorTail;

        TryFillColorResult::T result = TryFillColorResult::NonChanged;

        if(dic == Point2::Zero)
        {
            // Clicked 'O' button when Single cell selected,
            // remove 'X' marker at selected cell.

            if(solvePattern.arr[cursor.X][cursor.Y] == TableState::Uncolored)
            {
                if(ansPattern.arr[cursor.X][cursor.Y] == TableState::Uncolored)
                {
                    // If not correct, check wrong anser

                    solvePattern.arr[cursor.X][cursor.Y] = TableState::ForceErased;

                    Incorrect();
                    result = TryFillColorResult::Incorrect;
                }
                else
                {
                    // Only fill colored when correct

                    solvePattern.arr[cursor.X][cursor.Y] = TableState::Colored;
                    result = TryFillColorResult::Correct;
                }
            }
            else if(solvePattern.arr[cursor.X][cursor.Y] == TableState::Erased)
            {
                // remove 'X' marker when it filled 'X'

                solvePattern.arr[cursor.X][cursor.Y] = TableState::Uncolored;

                result = TryFillColorResult::NonChanged;
            }
        }
        else
        {
            if(dic.X != 0)
                dic.X /= Math::Abs(dic.X);
            else if(dic.Y != 0)
                dic.Y /= Math::Abs(dic.Y);

            result = TryFillColorResult::Correct;

            for(Point2 currentPoint = cursorTail; currentPoint != (cursor + dic); currentPoint += dic)
            {
                if(solvePattern.arr[currentPoint.X][currentPoint.Y] == TableState::Uncolored)
                {
                    // Only works when 'Uncolored'

                    if(ansPattern.arr[currentPoint.X][currentPoint.Y] == TableState::Uncolored)
                    {
                        // If not correct, check wrong anser and stop filling

                        solvePattern.arr[currentPoint.X][currentPoint.Y] = TableState::ForceErased;

                        Incorrect();
                        result = TryFillColorResult::Incorrect;
                        break;
                    }
                    else
                    {
                        // Only fill colored when correct.

                        solvePattern.arr[currentPoint.X][currentPoint.Y] = TableState::Colored;
                    }
                }
            }

            cursorTail = cursor;
        }

        if(GetRestLife() < 0)
        {
            result = TryFillColorResult::GameOver;
        }
        else if(WinCheck())
        {
            result = TryFillColorResult::Clear;
        }

        return result;
    }

    void MapleGameLogic::TryFillErased()
    {
        BBAssert(cursor.X == cursorTail.X || cursor.Y == cursorTail.Y);

        // dic cursorTail cursor ϴ
        Point2 dic = cursor - cursorTail;

        if(dic.X != 0)
            dic.X /= Math::Abs(dic.X);
        else if(dic.Y != 0)
            dic.Y /= Math::Abs(dic.Y);
        else
            dic.Y = 1;

        bool eraseMode = true;

        if(solvePattern.arr[cursorTail.X][cursorTail.Y] == TableState::Erased || solvePattern.arr[cursorTail.X][cursorTail.Y] == TableState::ForceErased)
        {
            //  X  , X    մϴ.

            eraseMode = false;
        }

        for(Point2 currentPoint = cursorTail; currentPoint != (cursor + dic); currentPoint += dic)
        {
            if(eraseMode && solvePattern.arr[currentPoint.X][currentPoint.Y] == TableState::Uncolored)
            {
                //  X ƴϰ, ƹ ͵  ĭ , X ǥ մϴ.
                solvePattern.arr[currentPoint.X][currentPoint.Y] = TableState::Erased;
            }
            else if(!eraseMode && solvePattern.arr[currentPoint.X][currentPoint.Y] == TableState::Erased)
            {
                //  X̰, X ĥ ִ ĭ̸, X ϴ.
                solvePattern.arr[currentPoint.X][currentPoint.Y] = TableState::Uncolored;
            }
        }

        cursorTail = cursor;
    }

    std::vector<std::vector<int> > MapleGameLogic::GetHorizontalNumberCount() const
    {
        std::vector<std::vector<int> > pattern;

        // <TODO> Draw() Լ ð ٿ Ѵٸ, pattern  ѹ ϵ ؾ մϴ.

        for(int i = 0; i < puzzleSize; i++)
        {
            std::vector<int> current;

            int j = puzzleSize - 1;
            int counter = 0;

            while(j >= 0)
            {
                if(ansPattern.arr[i][j] == TableState::Colored)
                    counter++;
                else
                {
                    if(counter > 0)
                    {
                        current.push_back(counter);
                        counter = 0;
                    }
                }

                j--;
            }

            if(counter > 0)
                current.push_back(counter);

            if(current.size() == 0)
                current.push_back(0);

            pattern.push_back(current);
        }

        return pattern;
    }

    std::vector<std::vector<int> > MapleGameLogic::GetVerticalNumberCount() const
    {
        std::vector<std::vector<int> > pattern;

        // <TODO> Draw() Լ ð ٿ Ѵٸ, pattern  ѹ ϵ ؾ մϴ.

        for(int i = 0; i < puzzleSize; i++)
        {
            std::vector<int> current;

            int j = 0;
            int counter = 0;

            while(j < puzzleSize)
            {
                if(ansPattern.arr[j][i] == TableState::Colored)
                    counter++;
                else
                {
                    if(counter > 0)
                    {
                        current.push_back(counter);
                        counter = 0;
                    }
                }

                j++;
            }

            if(counter > 0)
                current.push_back(counter);

            if(current.size() == 0)
                current.push_back(0);

            pattern.push_back(current);
        }

        return pattern;
    }

    Point2 MapleGameLogic::GetCursor() const
    {
        return cursor;
    }

    void MapleGameLogic::SetCursor(const Bibim::Point2& value)
    {
        cursor.X = Math::Clamp(value.X, 0, puzzleSize - 1);
        cursor.Y = Math::Clamp(value.Y, 0, puzzleSize - 1);
    }

    Point2 MapleGameLogic::GetCursorTail() const
    {
        return cursorTail;
    }

    void MapleGameLogic::SetCursorTail(const Bibim::Point2& end)
    {
        Point2 clamped;
        clamped.X = Math::Clamp(end.X, 0, puzzleSize - 1);
        clamped.Y = Math::Clamp(end.Y, 0, puzzleSize - 1);

        cursorTail = clamped;
        cursor = clamped;
    }

    void MapleGameLogic::CursorMove(const Bibim::Point2& dPoint)
    {
        if(Math::Abs(dPoint.X) + Math::Abs(dPoint.Y) != 1)
            return;

        SetCursorTail(cursor + dPoint);
    }

    bool MapleGameLogic::WinCheck()
    {
        // ̰ üũϴ Դϴ.
        // üũ ĭ  ġϸ Դϴ.

        bool result = true;

        for(int i = 0; i < puzzleSize; i++)
        {
            for(int j = 0; j < puzzleSize; j++)
            {
                if(ansPattern.arr[i][j] == TableState::Colored && solvePattern.arr[i][j] != TableState::Colored)
                {
                    result = false;
                    break;
                }
            }

            if(!result)
                break;
        }

        return result;
    }

    void MapleGameLogic::Incorrect()
    {
        //  ϴ.

        //   UIGameLogic ʿ  մϴ.

        restLife--;
    }
}
<commit_msg>Translate Korean comment to English<commit_after>#include <Maple/Gameplay/MapleGameLogic.h>
#include <Bibim/Math.h>
#include <Bibim/Assert.h>
using namespace Bibim;

namespace Maple
{
    MapleGameLogic::MapleGameLogic()
        : restLife(DefaultLife)
    {

    }

    MapleGameLogic::MapleGameLogic(int size)
        : puzzleSize(size),
          restLife(DefaultLife)
    {

    }

    MapleGameLogic::MapleGameLogic(int size, const GamePanel& ansPattern)
    {
        Initialize(size, ansPattern);
    }

    void MapleGameLogic::Initialize(int size, const GamePanel& ansPattern)
    {
        puzzleSize = size;
        restLife = DefaultLife;

        this->ansPattern = ansPattern;
    }

    void MapleGameLogic::Restart()
    {
        for(int i = 0; i < puzzleSize; i++)
        {
            for(int j = 0; j < puzzleSize; j++)
            {
                solvePattern.arr[i][j] = TableState::Uncolored;
            }
        }

        restLife = DefaultLife;
    }

    void MapleGameLogic::Update(float /*dt*/, int /*timestamp*/)
    {
        // Use this code when need to use time measure
    }

    const MapleGameLogic::GamePanel& MapleGameLogic::GetSolvePanel() const
    {
        return solvePattern;
    }

    int MapleGameLogic::GetPuzzleSize() const
    {
        return puzzleSize;
    }

    int MapleGameLogic::GetRestLife() const
    {
        return restLife;
    }

    MapleGameLogic::TryFillColorResult::T MapleGameLogic::TryFillColor()
    {
        BBAssert(cursor.X == cursorTail.X || cursor.Y == cursorTail.Y);

        // 'dic' is direction from 'cursorTail' to 'cursor'
        Point2 dic = cursor - cursorTail;

        TryFillColorResult::T result = TryFillColorResult::NonChanged;

        if(dic == Point2::Zero)
        {
            // Clicked 'O' button when Single cell selected,
            // remove 'X' marker at selected cell.

            if(solvePattern.arr[cursor.X][cursor.Y] == TableState::Uncolored)
            {
                if(ansPattern.arr[cursor.X][cursor.Y] == TableState::Uncolored)
                {
                    // If not correct, check wrong anser

                    solvePattern.arr[cursor.X][cursor.Y] = TableState::ForceErased;

                    Incorrect();
                    result = TryFillColorResult::Incorrect;
                }
                else
                {
                    // Only fill colored when correct

                    solvePattern.arr[cursor.X][cursor.Y] = TableState::Colored;
                    result = TryFillColorResult::Correct;
                }
            }
            else if(solvePattern.arr[cursor.X][cursor.Y] == TableState::Erased)
            {
                // remove 'X' marker when it filled 'X'

                solvePattern.arr[cursor.X][cursor.Y] = TableState::Uncolored;

                result = TryFillColorResult::NonChanged;
            }
        }
        else
        {
            if(dic.X != 0)
                dic.X /= Math::Abs(dic.X);
            else if(dic.Y != 0)
                dic.Y /= Math::Abs(dic.Y);

            result = TryFillColorResult::Correct;

            for(Point2 currentPoint = cursorTail; currentPoint != (cursor + dic); currentPoint += dic)
            {
                if(solvePattern.arr[currentPoint.X][currentPoint.Y] == TableState::Uncolored)
                {
                    // Only works when 'Uncolored'

                    if(ansPattern.arr[currentPoint.X][currentPoint.Y] == TableState::Uncolored)
                    {
                        // If not correct, check wrong anser and stop filling

                        solvePattern.arr[currentPoint.X][currentPoint.Y] = TableState::ForceErased;

                        Incorrect();
                        result = TryFillColorResult::Incorrect;
                        break;
                    }
                    else
                    {
                        // Only fill colored when correct.

                        solvePattern.arr[currentPoint.X][currentPoint.Y] = TableState::Colored;
                    }
                }
            }

            cursorTail = cursor;
        }

        if(GetRestLife() < 0)
        {
            result = TryFillColorResult::GameOver;
        }
        else if(WinCheck())
        {
            result = TryFillColorResult::Clear;
        }

        return result;
    }

    void MapleGameLogic::TryFillErased()
    {
        BBAssert(cursor.X == cursorTail.X || cursor.Y == cursorTail.Y);

        // 'dic' is direction from 'cursorTail' to 'cursor'
        Point2 dic = cursor - cursorTail;

        if(dic.X != 0)
            dic.X /= Math::Abs(dic.X);
        else if(dic.Y != 0)
            dic.Y /= Math::Abs(dic.Y);
        else
            dic.Y = 1;

        bool eraseMode = true;

        if(solvePattern.arr[cursorTail.X][cursorTail.Y] == TableState::Erased || solvePattern.arr[cursorTail.X][cursorTail.Y] == TableState::ForceErased)
        {
            // If start point is marked 'X', operation will remove 'X'

            eraseMode = false;
        }

        for(Point2 currentPoint = cursorTail; currentPoint != (cursor + dic); currentPoint += dic)
        {
            if(eraseMode && solvePattern.arr[currentPoint.X][currentPoint.Y] == TableState::Uncolored)
            {
                // If start point is not 'X', and this is null block, then fill 'X'
                solvePattern.arr[currentPoint.X][currentPoint.Y] = TableState::Erased;
            }
            else if(!eraseMode && solvePattern.arr[currentPoint.X][currentPoint.Y] == TableState::Erased)
            {
                // If start point is 'X', and this is 'X' block, then remove 'X'
                solvePattern.arr[currentPoint.X][currentPoint.Y] = TableState::Uncolored;
            }
        }

        cursorTail = cursor;
    }

    std::vector<std::vector<int> > MapleGameLogic::GetHorizontalNumberCount() const
    {
        std::vector<std::vector<int> > pattern;

        // <TODO> If need to reduce 'Draw()' call speed, reduce calculate 'pattern' only first time.

        for(int i = 0; i < puzzleSize; i++)
        {
            std::vector<int> current;

            int j = puzzleSize - 1;
            int counter = 0;

            while(j >= 0)
            {
                if(ansPattern.arr[i][j] == TableState::Colored)
                    counter++;
                else
                {
                    if(counter > 0)
                    {
                        current.push_back(counter);
                        counter = 0;
                    }
                }

                j--;
            }

            if(counter > 0)
                current.push_back(counter);

            if(current.size() == 0)
                current.push_back(0);

            pattern.push_back(current);
        }

        return pattern;
    }

    std::vector<std::vector<int> > MapleGameLogic::GetVerticalNumberCount() const
    {
        std::vector<std::vector<int> > pattern;

        // <TODO> If need to reduce 'Draw()' call speed, reduce calculate 'pattern' only first time.

        for(int i = 0; i < puzzleSize; i++)
        {
            std::vector<int> current;

            int j = 0;
            int counter = 0;

            while(j < puzzleSize)
            {
                if(ansPattern.arr[j][i] == TableState::Colored)
                    counter++;
                else
                {
                    if(counter > 0)
                    {
                        current.push_back(counter);
                        counter = 0;
                    }
                }

                j++;
            }

            if(counter > 0)
                current.push_back(counter);

            if(current.size() == 0)
                current.push_back(0);

            pattern.push_back(current);
        }

        return pattern;
    }

    Point2 MapleGameLogic::GetCursor() const
    {
        return cursor;
    }

    void MapleGameLogic::SetCursor(const Bibim::Point2& value)
    {
        cursor.X = Math::Clamp(value.X, 0, puzzleSize - 1);
        cursor.Y = Math::Clamp(value.Y, 0, puzzleSize - 1);
    }

    Point2 MapleGameLogic::GetCursorTail() const
    {
        return cursorTail;
    }

    void MapleGameLogic::SetCursorTail(const Bibim::Point2& end)
    {
        Point2 clamped;
        clamped.X = Math::Clamp(end.X, 0, puzzleSize - 1);
        clamped.Y = Math::Clamp(end.Y, 0, puzzleSize - 1);

        cursorTail = clamped;
        cursor = clamped;
    }

    void MapleGameLogic::CursorMove(const Bibim::Point2& dPoint)
    {
        if(Math::Abs(dPoint.X) + Math::Abs(dPoint.Y) != 1)
            return;

        SetCursorTail(cursor + dPoint);
    }

    bool MapleGameLogic::WinCheck()
    {
        // Check for Win Game.

        bool result = true;

        for(int i = 0; i < puzzleSize; i++)
        {
            for(int j = 0; j < puzzleSize; j++)
            {
                if(ansPattern.arr[i][j] == TableState::Colored && solvePattern.arr[i][j] != TableState::Colored)
                {
                    result = false;
                    break;
                }
            }

            if(!result)
                break;
        }

        return result;
    }

    void MapleGameLogic::Incorrect()
    {
        // Just reduce life.

        restLife--;
    }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: PropertyHelper.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: vg $ $Date: 2007-05-22 19:03:24 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "PropertyHelper.hxx"
#include "ContainerHelper.hxx"
#include "macros.hxx"

#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif

#include <vector>
#include <algorithm>
#include <functional>

using namespace ::com::sun::star;
using namespace ::com::sun::star::beans;
using ::rtl::OUString;
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;

namespace
{
struct lcl_EqualsElement : public ::std::unary_function< OUString, bool >
{
    explicit lcl_EqualsElement( const Any & rValue, const Reference< container::XNameAccess > & xAccess )
            : m_aValue( rValue ), m_xAccess( xAccess )
    {
        OSL_ASSERT( m_xAccess.is());
    }

    bool operator() ( const OUString & rName )
    {
        try
        {
            return (m_xAccess->getByName( rName ) == m_aValue);
        }
        catch( const uno::Exception & ex )
        {
            ASSERT_EXCEPTION( ex );
        }
        return false;
    }

private:
    Any m_aValue;
    Reference< container::XNameAccess > m_xAccess;
};

struct lcl_StringMatches : public ::std::unary_function< OUString ,bool >
{
    lcl_StringMatches( const OUString & rCmpStr ) :
            m_aCmpStr( rCmpStr )
    {}

    bool operator() ( const OUString & rStr )
    {
        return rStr.match( m_aCmpStr );
    }

private:
    OUString m_aCmpStr;
};

struct lcl_OUStringRestToInt32 : public ::std::unary_function< OUString, sal_Int32 >
{
    lcl_OUStringRestToInt32( sal_Int32 nPrefixLength ) :
            m_nPrefixLength( nPrefixLength )
    {}
    sal_Int32 operator() ( const OUString & rStr )
    {
        if( m_nPrefixLength > rStr.getLength() )
            return 0;
        return rStr.copy( m_nPrefixLength ).toInt32( 10 /* radix */ );
    }
private:
    sal_Int32 m_nPrefixLength;
};

/** adds a fill gradient, fill hatch, fill bitmap, fill transparency gradient,
    line dash or line marker to the corresponding name container with a unique
    name.

    @param rPrefix
        The prefix used for automated name generation.

    @param rPreferredName
        If this string is not empty it is used as name if it is unique in the
        table. Otherwise a new name is generated using pPrefix.

    @return the new name under which the property was stored in the table
*/
OUString lcl_addNamedPropertyUniqueNameToTable(
    const Any & rValue,
    const Reference< container::XNameContainer > & xNameContainer,
    const OUString & rPrefix,
    const OUString & rPreferredName )
{
    if( ! xNameContainer.is() ||
        ! rValue.hasValue() ||
        ( rValue.getValueType() != xNameContainer->getElementType()))
        return rPreferredName;

    try
    {
        Reference< container::XNameAccess > xNameAccess( xNameContainer, uno::UNO_QUERY_THROW );
        ::std::vector< OUString > aNames( ::chart::ContainerHelper::SequenceToVector( xNameAccess->getElementNames()));
        ::std::vector< OUString >::const_iterator aIt(
            ::std::find_if( aNames.begin(), aNames.end(), lcl_EqualsElement( rValue, xNameAccess )));

        // element not found in container
        if( aIt == aNames.end())
        {
            OUString aUniqueName;

            // check if preferred name is already used
            if( rPreferredName.getLength())
            {
                aIt = ::std::find( aNames.begin(), aNames.end(), rPreferredName );
                if( aIt == aNames.end())
                    aUniqueName = rPreferredName;
            }

            if( ! aUniqueName.getLength())
            {
                // create a unique id using the prefix plus a number
                ::std::vector< sal_Int32 > aNumbers;
                ::std::vector< OUString >::iterator aNonConstIt(
                    ::std::partition( aNames.begin(), aNames.end(), lcl_StringMatches( rPrefix )));
                ::std::transform( aNames.begin(), aNonConstIt,
                                  back_inserter( aNumbers ),
                                  lcl_OUStringRestToInt32( rPrefix.getLength() ));
                ::std::vector< sal_Int32 >::const_iterator aMaxIt(
                    ::std::max_element( aNumbers.begin(), aNumbers.end()));

                sal_Int32 nIndex = 1;
                if( aMaxIt != aNumbers.end())
                    nIndex = (*aMaxIt) + 1;

                aUniqueName = rPrefix + OUString::valueOf( nIndex );
            }

            OSL_ASSERT( aUniqueName.getLength());
            xNameContainer->insertByName( aUniqueName, rValue );
            return aUniqueName;
        }
        else
            // element found => return name
            return *aIt;
    }
    catch( const uno::Exception & ex )
    {
        ASSERT_EXCEPTION( ex );
    }

    return rPreferredName;
}

} // anonymous namespace

namespace chart
{

// static
void PropertyHelper::copyProperties(
    const Reference< XPropertySet > & xSource,
    const Reference< XPropertySet > & xDestination )
{
    if( ! (xSource.is() && xDestination.is()))
        return;

    try
    {
        Reference< XPropertySetInfo > xSrcInfo( xSource->getPropertySetInfo(), uno::UNO_QUERY_THROW );
        Reference< XPropertySetInfo > xDestInfo( xDestination->getPropertySetInfo(), uno::UNO_QUERY_THROW );
        Sequence< Property > aProperties( xSrcInfo->getProperties());
        const sal_Int32 nLength = aProperties.getLength();
        for( sal_Int32 i = 0; i < nLength; ++i )
        {
            OUString aName( aProperties[i].Name);
            if( xDestInfo->hasPropertyByName( aName ))
            {
                Property aProp( xDestInfo->getPropertyByName( aName ));
                if( (aProp.Attributes & PropertyAttribute::READONLY) == 0 )
                    xDestination->setPropertyValue(
                        aName, xSource->getPropertyValue( aName ));
            }
        }
    }
    catch( const uno::Exception & ex )
    {
        ASSERT_EXCEPTION( ex );
    }
}

// static
OUString PropertyHelper::addLineDashUniqueNameToTable(
    const Any & rValue,
    const Reference< lang::XMultiServiceFactory > & xFact,
    const OUString & rPreferredName )
{
    if( xFact.is())
    {
        Reference< container::XNameContainer > xNameCnt(
            xFact->createInstance( C2U( "com.sun.star.drawing.DashTable" )),
            uno::UNO_QUERY );
        if( xNameCnt.is())
            return lcl_addNamedPropertyUniqueNameToTable(
                rValue, xNameCnt, C2U( "ChartDash " ), rPreferredName );
    }
    return OUString();
}

// static
OUString PropertyHelper::addGradientUniqueNameToTable(
    const Any & rValue,
    const Reference< lang::XMultiServiceFactory > & xFact,
    const OUString & rPreferredName )
{
    if( xFact.is())
    {
        Reference< container::XNameContainer > xNameCnt(
            xFact->createInstance( C2U( "com.sun.star.drawing.GradientTable" )),
            uno::UNO_QUERY );
        if( xNameCnt.is())
            return lcl_addNamedPropertyUniqueNameToTable(
                rValue, xNameCnt, C2U( "ChartGradient " ), rPreferredName );
    }
    return OUString();
}

// static
OUString PropertyHelper::addTransparencyGradientUniqueNameToTable(
    const Any & rValue,
    const Reference< lang::XMultiServiceFactory > & xFact,
    const OUString & rPreferredName )
{
    if( xFact.is())
    {
        Reference< container::XNameContainer > xNameCnt(
            xFact->createInstance( C2U( "com.sun.star.drawing.TransparencyGradientTable" )),
            uno::UNO_QUERY );
        if( xNameCnt.is())
            return lcl_addNamedPropertyUniqueNameToTable(
                rValue, xNameCnt, C2U( "ChartTransparencyGradient " ), rPreferredName );
    }
    return OUString();
}

// static
OUString PropertyHelper::addHatchUniqueNameToTable(
    const Any & rValue,
    const Reference< lang::XMultiServiceFactory > & xFact,
    const OUString & rPreferredName )
{
    if( xFact.is())
    {
        Reference< container::XNameContainer > xNameCnt(
            xFact->createInstance( C2U( "com.sun.star.drawing.HatchTable" )),
            uno::UNO_QUERY );
        if( xNameCnt.is())
            return lcl_addNamedPropertyUniqueNameToTable(
                rValue, xNameCnt, C2U( "ChartHatch " ), rPreferredName );
    }
    return OUString();
}

// static
OUString PropertyHelper::addBitmapUniqueNameToTable(
    const Any & rValue,
    const Reference< lang::XMultiServiceFactory > & xFact,
    const OUString & rPreferredName )
{
    if( xFact.is())
    {
        Reference< container::XNameContainer > xNameCnt(
            xFact->createInstance( C2U( "com.sun.star.drawing.BitmapTable" )),
            uno::UNO_QUERY );
        if( xNameCnt.is())
            return lcl_addNamedPropertyUniqueNameToTable(
                rValue, xNameCnt, C2U( "ChartBitmap " ), rPreferredName );
    }
    return OUString();
}

} //  namespace chart
<commit_msg>INTEGRATION: CWS chart11 (1.4.38); FILE MERGED 2007/08/24 08:27:25 bm 1.4.38.4: #i80084# define template specialization in cxx 2007/08/24 07:18:15 bm 1.4.38.3: #i80084# template spezialization needed 2007/08/03 12:57:35 bm 1.4.38.2: #i80084# using template specialization instead of a different function name 2007/07/31 12:56:46 bm 1.4.38.1: #i80084# avoid usage of map operator[] with enums as keys, simplify initialization of default property values<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: PropertyHelper.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: vg $ $Date: 2007-09-18 15:09:42 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "PropertyHelper.hxx"
#include "ContainerHelper.hxx"
#include "macros.hxx"

#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif

#include <vector>
#include <algorithm>
#include <functional>

using namespace ::com::sun::star;
using namespace ::com::sun::star::beans;
using ::rtl::OUString;
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;

namespace
{
struct lcl_EqualsElement : public ::std::unary_function< OUString, bool >
{
    explicit lcl_EqualsElement( const Any & rValue, const Reference< container::XNameAccess > & xAccess )
            : m_aValue( rValue ), m_xAccess( xAccess )
    {
        OSL_ASSERT( m_xAccess.is());
    }

    bool operator() ( const OUString & rName )
    {
        try
        {
            return (m_xAccess->getByName( rName ) == m_aValue);
        }
        catch( const uno::Exception & ex )
        {
            ASSERT_EXCEPTION( ex );
        }
        return false;
    }

private:
    Any m_aValue;
    Reference< container::XNameAccess > m_xAccess;
};

struct lcl_StringMatches : public ::std::unary_function< OUString ,bool >
{
    lcl_StringMatches( const OUString & rCmpStr ) :
            m_aCmpStr( rCmpStr )
    {}

    bool operator() ( const OUString & rStr )
    {
        return rStr.match( m_aCmpStr );
    }

private:
    OUString m_aCmpStr;
};

struct lcl_OUStringRestToInt32 : public ::std::unary_function< OUString, sal_Int32 >
{
    lcl_OUStringRestToInt32( sal_Int32 nPrefixLength ) :
            m_nPrefixLength( nPrefixLength )
    {}
    sal_Int32 operator() ( const OUString & rStr )
    {
        if( m_nPrefixLength > rStr.getLength() )
            return 0;
        return rStr.copy( m_nPrefixLength ).toInt32( 10 /* radix */ );
    }
private:
    sal_Int32 m_nPrefixLength;
};

/** adds a fill gradient, fill hatch, fill bitmap, fill transparency gradient,
    line dash or line marker to the corresponding name container with a unique
    name.

    @param rPrefix
        The prefix used for automated name generation.

    @param rPreferredName
        If this string is not empty it is used as name if it is unique in the
        table. Otherwise a new name is generated using pPrefix.

    @return the new name under which the property was stored in the table
*/
OUString lcl_addNamedPropertyUniqueNameToTable(
    const Any & rValue,
    const Reference< container::XNameContainer > & xNameContainer,
    const OUString & rPrefix,
    const OUString & rPreferredName )
{
    if( ! xNameContainer.is() ||
        ! rValue.hasValue() ||
        ( rValue.getValueType() != xNameContainer->getElementType()))
        return rPreferredName;

    try
    {
        Reference< container::XNameAccess > xNameAccess( xNameContainer, uno::UNO_QUERY_THROW );
        ::std::vector< OUString > aNames( ::chart::ContainerHelper::SequenceToVector( xNameAccess->getElementNames()));
        ::std::vector< OUString >::const_iterator aIt(
            ::std::find_if( aNames.begin(), aNames.end(), lcl_EqualsElement( rValue, xNameAccess )));

        // element not found in container
        if( aIt == aNames.end())
        {
            OUString aUniqueName;

            // check if preferred name is already used
            if( rPreferredName.getLength())
            {
                aIt = ::std::find( aNames.begin(), aNames.end(), rPreferredName );
                if( aIt == aNames.end())
                    aUniqueName = rPreferredName;
            }

            if( ! aUniqueName.getLength())
            {
                // create a unique id using the prefix plus a number
                ::std::vector< sal_Int32 > aNumbers;
                ::std::vector< OUString >::iterator aNonConstIt(
                    ::std::partition( aNames.begin(), aNames.end(), lcl_StringMatches( rPrefix )));
                ::std::transform( aNames.begin(), aNonConstIt,
                                  back_inserter( aNumbers ),
                                  lcl_OUStringRestToInt32( rPrefix.getLength() ));
                ::std::vector< sal_Int32 >::const_iterator aMaxIt(
                    ::std::max_element( aNumbers.begin(), aNumbers.end()));

                sal_Int32 nIndex = 1;
                if( aMaxIt != aNumbers.end())
                    nIndex = (*aMaxIt) + 1;

                aUniqueName = rPrefix + OUString::valueOf( nIndex );
            }

            OSL_ASSERT( aUniqueName.getLength());
            xNameContainer->insertByName( aUniqueName, rValue );
            return aUniqueName;
        }
        else
            // element found => return name
            return *aIt;
    }
    catch( const uno::Exception & ex )
    {
        ASSERT_EXCEPTION( ex );
    }

    return rPreferredName;
}

} // anonymous namespace

namespace chart
{
namespace PropertyHelper
{

void copyProperties(
    const Reference< XPropertySet > & xSource,
    const Reference< XPropertySet > & xDestination )
{
    if( ! (xSource.is() && xDestination.is()))
        return;

    try
    {
        Reference< XPropertySetInfo > xSrcInfo( xSource->getPropertySetInfo(), uno::UNO_QUERY_THROW );
        Reference< XPropertySetInfo > xDestInfo( xDestination->getPropertySetInfo(), uno::UNO_QUERY_THROW );
        Sequence< Property > aProperties( xSrcInfo->getProperties());
        const sal_Int32 nLength = aProperties.getLength();
        for( sal_Int32 i = 0; i < nLength; ++i )
        {
            OUString aName( aProperties[i].Name);
            if( xDestInfo->hasPropertyByName( aName ))
            {
                Property aProp( xDestInfo->getPropertyByName( aName ));
                if( (aProp.Attributes & PropertyAttribute::READONLY) == 0 )
                    xDestination->setPropertyValue(
                        aName, xSource->getPropertyValue( aName ));
            }
        }
    }
    catch( const uno::Exception & ex )
    {
        ASSERT_EXCEPTION( ex );
    }
}

OUString addLineDashUniqueNameToTable(
    const Any & rValue,
    const Reference< lang::XMultiServiceFactory > & xFact,
    const OUString & rPreferredName )
{
    if( xFact.is())
    {
        Reference< container::XNameContainer > xNameCnt(
            xFact->createInstance( C2U( "com.sun.star.drawing.DashTable" )),
            uno::UNO_QUERY );
        if( xNameCnt.is())
            return lcl_addNamedPropertyUniqueNameToTable(
                rValue, xNameCnt, C2U( "ChartDash " ), rPreferredName );
    }
    return OUString();
}

OUString addGradientUniqueNameToTable(
    const Any & rValue,
    const Reference< lang::XMultiServiceFactory > & xFact,
    const OUString & rPreferredName )
{
    if( xFact.is())
    {
        Reference< container::XNameContainer > xNameCnt(
            xFact->createInstance( C2U( "com.sun.star.drawing.GradientTable" )),
            uno::UNO_QUERY );
        if( xNameCnt.is())
            return lcl_addNamedPropertyUniqueNameToTable(
                rValue, xNameCnt, C2U( "ChartGradient " ), rPreferredName );
    }
    return OUString();
}

OUString addTransparencyGradientUniqueNameToTable(
    const Any & rValue,
    const Reference< lang::XMultiServiceFactory > & xFact,
    const OUString & rPreferredName )
{
    if( xFact.is())
    {
        Reference< container::XNameContainer > xNameCnt(
            xFact->createInstance( C2U( "com.sun.star.drawing.TransparencyGradientTable" )),
            uno::UNO_QUERY );
        if( xNameCnt.is())
            return lcl_addNamedPropertyUniqueNameToTable(
                rValue, xNameCnt, C2U( "ChartTransparencyGradient " ), rPreferredName );
    }
    return OUString();
}

OUString addHatchUniqueNameToTable(
    const Any & rValue,
    const Reference< lang::XMultiServiceFactory > & xFact,
    const OUString & rPreferredName )
{
    if( xFact.is())
    {
        Reference< container::XNameContainer > xNameCnt(
            xFact->createInstance( C2U( "com.sun.star.drawing.HatchTable" )),
            uno::UNO_QUERY );
        if( xNameCnt.is())
            return lcl_addNamedPropertyUniqueNameToTable(
                rValue, xNameCnt, C2U( "ChartHatch " ), rPreferredName );
    }
    return OUString();
}

OUString addBitmapUniqueNameToTable(
    const Any & rValue,
    const Reference< lang::XMultiServiceFactory > & xFact,
    const OUString & rPreferredName )
{
    if( xFact.is())
    {
        Reference< container::XNameContainer > xNameCnt(
            xFact->createInstance( C2U( "com.sun.star.drawing.BitmapTable" )),
            uno::UNO_QUERY );
        if( xNameCnt.is())
            return lcl_addNamedPropertyUniqueNameToTable(
                rValue, xNameCnt, C2U( "ChartBitmap " ), rPreferredName );
    }
    return OUString();
}

// ----------------------------------------

void setPropertyValueAny( tPropertyValueMap & rOutMap, tPropertyValueMapKey key, const uno::Any & rAny )
{
    tPropertyValueMap::iterator aIt( rOutMap.find( key ));
    if( aIt == rOutMap.end())
        rOutMap.insert( tPropertyValueMap::value_type( key, rAny ));
    else
        (*aIt).second = rAny;
}

template<>
    void setPropertyValue< ::com::sun::star::uno::Any >( tPropertyValueMap & rOutMap, tPropertyValueMapKey key, const ::com::sun::star::uno::Any & rAny )
{
    setPropertyValueAny( rOutMap, key, rAny );
}

void setPropertyValueDefaultAny( tPropertyValueMap & rOutMap, tPropertyValueMapKey key, const uno::Any & rAny )
{
    OSL_ENSURE( rOutMap.end() == rOutMap.find( key ), "Default already exists for property" );
    setPropertyValue( rOutMap, key, rAny );
}

template<>
    void setPropertyValueDefault< ::com::sun::star::uno::Any >( tPropertyValueMap & rOutMap, tPropertyValueMapKey key, const ::com::sun::star::uno::Any & rAny )
{
    setPropertyValueDefaultAny( rOutMap, key, rAny );
}

void setEmptyPropertyValueDefault( tPropertyValueMap & rOutMap, tPropertyValueMapKey key )
{
    setPropertyValueDefault( rOutMap, key, uno::Any());
}

} // namespace PropertyHelper

} //  namespace chart
<|endoftext|>


<commit_before>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2013 Soumyajit De
 */

#include <shogun/lib/common.h>
#include <shogun/lib/SGVector.h>
#include <shogun/lib/SGMatrix.h>
#include <shogun/mathematics/Statistics.h>
#include <shogun/mathematics/eigen3.h>
#include <shogun/mathematics/linalg/ratapprox/tracesampler/NormalSampler.h>
#include <gtest/gtest.h>

using namespace shogun;
using namespace Eigen;

#ifdef HAVE_LAPACK
TEST(NormalSampler, sample)
{
	const index_t dimension=2;
	const index_t num_samples=5000;
	SGMatrix<float64_t> samples(num_samples, dimension);

	CNormalSampler sampler(dimension);
	sampler.precompute();
	for (index_t i=0; i<num_samples; ++i)
	{
		SGVector<float64_t> s=sampler.sample(0);
		for (index_t j=0; j<dimension; ++j)
			samples(i,j)=s[j];
	}

	SGVector<float64_t> mean=CStatistics::matrix_mean(samples);
	Map<VectorXd> map_mean(mean.vector, mean.vlen);
	EXPECT_NEAR((map_mean-VectorXd::Zero(dimension)).norm(), 0.0, 0.1);

	SGMatrix<float64_t> cov=CStatistics::covariance_matrix(samples);
	Map<MatrixXd> map_cov(cov.matrix, cov.num_rows, cov.num_cols);
	EXPECT_NEAR((map_cov-MatrixXd::Identity(dimension, dimension)).norm(),
		0.0, 0.1);
}
#endif // HAVE_LAPACK

<commit_msg>fix another covariance matrix unit test<commit_after>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2013 Soumyajit De
 */

#include <shogun/lib/common.h>
#include <shogun/lib/SGVector.h>
#include <shogun/lib/SGMatrix.h>
#include <shogun/mathematics/Statistics.h>
#include <shogun/mathematics/eigen3.h>
#include <shogun/mathematics/linalg/ratapprox/tracesampler/NormalSampler.h>
#include <gtest/gtest.h>

using namespace shogun;
using namespace Eigen;

TEST(NormalSampler, sample)
{
	const index_t dimension=2;
	const index_t num_samples=5000;
	SGMatrix<float64_t> samples(num_samples, dimension);

	CNormalSampler sampler(dimension);
	sampler.precompute();
	for (index_t i=0; i<num_samples; ++i)
	{
		SGVector<float64_t> s=sampler.sample(0);
		for (index_t j=0; j<dimension; ++j)
			samples(i,j)=s[j];
	}

	SGVector<float64_t> mean=CStatistics::matrix_mean(samples);
	Map<VectorXd> map_mean(mean.vector, mean.vlen);
	EXPECT_NEAR((map_mean-VectorXd::Zero(dimension)).norm(), 0.0, 0.1);
	SGMatrix<float64_t>::transpose_matrix(samples.matrix, samples.num_rows, samples.num_cols); // TODO: refactor sample_from_gaussian to return column vectors!
	SGMatrix<float64_t> cov=CStatistics::covariance_matrix(samples);
	Map<MatrixXd> map_cov(cov.matrix, cov.num_rows, cov.num_cols);
	EXPECT_NEAR((map_cov-MatrixXd::Identity(dimension, dimension)).norm(),
		0.0, 0.1);
}

<|endoftext|>