<commit_before>/*
 * Copyright 2011-2018 Branimir Karadzic. All rights reserved.
 * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
 */

#include "bgfx_p.h"
#include "nvapi.h"

namespace bgfx
{
	/*
	 * NVAPI
	 *
	 * Reference:
	 * http://docs.nvidia.com/gameworks/content/gameworkslibrary/coresdk/nvapi/index.html
	 * https://github.com/jNizM/AHK_NVIDIA_NvAPI/blob/master/info/NvAPI_IDs.txt
	 */

	struct NvPhysicalGpuHandle;

#define NVAPI_MAX_PHYSICAL_GPUS 64

#if BX_PLATFORM_WINDOWS
#	define NVAPICALL __cdecl
#else
#	define NVAPICALL
#endif // BX_PLATFORM_WINDOWS

	enum NvApiStatus
	{
		NVAPI_OK    =  0,
		NVAPI_ERROR = -1,
	};

	struct NvMemoryInfoV2
	{
		NvMemoryInfoV2()
			: version(sizeof(NvMemoryInfoV2) | (2 << 16) )
		{
		}

		uint32_t version;
		uint32_t dedicatedVideoMemory;
		uint32_t availableDedicatedVideoMemory;
		uint32_t systemVideoMemory;
		uint32_t sharedSystemMemory;
		uint32_t curAvailableDedicatedVideoMemory;
	};

	typedef void*       (NVAPICALL* PFN_NVAPI_QUERYINTERFACE)(uint32_t _functionOffset);
	typedef NvApiStatus (NVAPICALL* PFN_NVAPI_INITIALIZE)();
	typedef NvApiStatus (NVAPICALL* PFN_NVAPI_UNLOAD)();
	typedef NvApiStatus (NVAPICALL* PFN_NVAPI_ENUMPHYSICALGPUS)(NvPhysicalGpuHandle* _handle[NVAPI_MAX_PHYSICAL_GPUS], uint32_t* _gpuCount);
	typedef NvApiStatus (NVAPICALL* PFN_NVAPI_GPUGETMEMORYINFO)(NvPhysicalGpuHandle* _handle, NvMemoryInfoV2* _memoryInfo);
	typedef NvApiStatus (NVAPICALL* PFN_NVAPI_GPUGETFULLNAME)(NvPhysicalGpuHandle* _physicalGpu, char _name[64]);

#define NVAPI_INITIALIZE                        UINT32_C(0x0150e828)
#define NVAPI_UNLOAD                            UINT32_C(0xd22bdd7e)
#define NVAPI_ENUMPHYSICALGPUS                  UINT32_C(0xe5ac921f)
#define NVAPI_GPUGETMEMORYINFO                  UINT32_C(0x07f9b368)
#define NVAPI_GPUGETFULLNAME                    UINT32_C(0xceee8e9f)
#define NVAPI_MULTIDRAWINSTANCEDINDIRECT        UINT32_C(0xd4e26bbf)
#define NVAPI_MULTIDRAWINDEXEDINSTANCEDINDIRECT UINT32_C(0x59e890f9)

	static PFN_NVAPI_QUERYINTERFACE   nvApiQueryInterface;
	static PFN_NVAPI_INITIALIZE       nvApiInitialize;
	static PFN_NVAPI_UNLOAD           nvApiUnload;
	static PFN_NVAPI_ENUMPHYSICALGPUS nvApiEnumPhysicalGPUs;
	static PFN_NVAPI_GPUGETMEMORYINFO nvApiGpuGetMemoryInfo;
	static PFN_NVAPI_GPUGETFULLNAME   nvApiGpuGetFullName;

	/*
	 * NVIDIA Aftermath
	 *
	 * Reference:
	 * https://developer.nvidia.com/nvidia-aftermath
	 */

	typedef int32_t (*PFN_NVAFTERMATH_DX12_INITIALIZE)(int32_t _version, int32_t _flags, const ID3D12Device* _device);
	typedef int32_t (*PFN_NVAFTERMATH_DX12_CREATECONTEXTHANDLE)(const ID3D12CommandList* _commandList, NvAftermathContextHandle** _outContextHandle);
	typedef int32_t (*PFN_NVAFTERMATH_RELEASECONTEXTHANDLE)(const NvAftermathContextHandle* _contextHandle);
	typedef int32_t (*PFN_NVAFTERMATH_SETEVENTMARKER)(const NvAftermathContextHandle* _contextHandle, const void* _markerData, uint32_t _markerSize);
	typedef int32_t (*PFN_NVAFTERMATH_GETDATA)(uint32_t _numContexts, const NvAftermathContextHandle** _contextHandles, void* _outContextData);
	typedef int32_t (*PFN_NVAFTERMATH_GETDEVICESTATUS)(void* _outStatus);
	typedef int32_t (*PFN_NVAFTERMATH_GETPAGEFAULTINFORMATION)(void* _outPageFaultInformation);

	static PFN_NVAFTERMATH_DX12_INITIALIZE          nvAftermathDx12Initialize;
	static PFN_NVAFTERMATH_DX12_CREATECONTEXTHANDLE nvAftermathDx12CreateContextHandle;
	static PFN_NVAFTERMATH_RELEASECONTEXTHANDLE     nvAftermathReleaseContextHandle;
	static PFN_NVAFTERMATH_SETEVENTMARKER           nvAftermathSetEventMarker;
	static PFN_NVAFTERMATH_GETDATA                  nvAftermathGetData;
	static PFN_NVAFTERMATH_GETDEVICESTATUS          nvAftermathGetDeviceStatus;
	static PFN_NVAFTERMATH_GETPAGEFAULTINFORMATION  nvAftermathGetPageFaultInformation;

	NvApi::NvApi()
		: m_nvApiDll(NULL)
		, m_nvGpu(NULL)
		, m_nvAftermathDll(NULL)
		, m_aftermathHandle(NULL)
	{
	}

	void NvApi::init()
	{
		m_nvGpu = NULL;
		m_nvApiDll = bx::dlopen(
			"nvapi"
#if BX_ARCH_64BIT
			"64"
#endif // BX_ARCH_32BIT
			".dll"
			);

		if (NULL != m_nvApiDll)
		{
			nvApiQueryInterface = (PFN_NVAPI_QUERYINTERFACE)bx::dlsym(m_nvApiDll, "nvapi_QueryInterface");

			bool initialized = NULL != nvApiQueryInterface;

			if (initialized)
			{
				nvApiInitialize       = (PFN_NVAPI_INITIALIZE       )nvApiQueryInterface(NVAPI_INITIALIZE);
				nvApiUnload           = (PFN_NVAPI_UNLOAD           )nvApiQueryInterface(NVAPI_UNLOAD);
				nvApiEnumPhysicalGPUs = (PFN_NVAPI_ENUMPHYSICALGPUS )nvApiQueryInterface(NVAPI_ENUMPHYSICALGPUS);
				nvApiGpuGetMemoryInfo = (PFN_NVAPI_GPUGETMEMORYINFO )nvApiQueryInterface(NVAPI_GPUGETMEMORYINFO);
				nvApiGpuGetFullName   = (PFN_NVAPI_GPUGETFULLNAME   )nvApiQueryInterface(NVAPI_GPUGETFULLNAME);

				nvApiD3D11MultiDrawInstancedIndirect        = (PFN_NVAPI_MULTIDRAWINDIRECT)nvApiQueryInterface(NVAPI_MULTIDRAWINSTANCEDINDIRECT);
				nvApiD3D11MultiDrawIndexedInstancedIndirect = (PFN_NVAPI_MULTIDRAWINDIRECT)nvApiQueryInterface(NVAPI_MULTIDRAWINDEXEDINSTANCEDINDIRECT);

				initialized = true
					&& NULL != nvApiInitialize
					&& NULL != nvApiUnload
					&& NULL != nvApiEnumPhysicalGPUs
					&& NULL != nvApiGpuGetMemoryInfo
					&& NULL != nvApiGpuGetFullName
					&& NVAPI_OK == nvApiInitialize()
					;

				if (initialized)
				{
					NvPhysicalGpuHandle* physicalGpus[NVAPI_MAX_PHYSICAL_GPUS];
					uint32_t numGpus = 0;
					nvApiEnumPhysicalGPUs(physicalGpus, &numGpus);

					initialized = 0 < numGpus;
					if (initialized)
					{
						m_nvGpu = physicalGpus[0];
					}

					char name[64];
					nvApiGpuGetFullName(m_nvGpu, name);
					BX_TRACE("%s", name);
				}

				initialized = NULL != m_nvGpu;

				if (!initialized)
				{
					nvApiUnload();
				}
			}

			if (!initialized)
			{
				bx::dlclose(m_nvApiDll);
				m_nvApiDll = NULL;
			}

			BX_WARN(!initialized, "NVAPI supported.");
		}
	}

	void NvApi::shutdown()
	{
		if (NULL != m_nvGpu)
		{
			nvApiUnload();
			m_nvGpu = NULL;
		}

		if (NULL != m_nvApiDll)
		{
			bx::dlclose(m_nvApiDll);
			m_nvApiDll = NULL;
		}

		shutdownAftermath();
	}

	void NvApi::getMemoryInfo(int64_t& _gpuMemoryUsed, int64_t& _gpuMemoryMax)
	{
		if (NULL != m_nvGpu)
		{
			NvMemoryInfoV2 memInfo;
			NvApiStatus status = nvApiGpuGetMemoryInfo(m_nvGpu, &memInfo);
			if (NVAPI_OK == status)
			{
				_gpuMemoryMax  = 1024 * int64_t(memInfo.availableDedicatedVideoMemory);
				_gpuMemoryUsed = 1024 * int64_t(memInfo.availableDedicatedVideoMemory - memInfo.curAvailableDedicatedVideoMemory);
//				BX_TRACE("            dedicatedVideoMemory: %d KiB", memInfo.dedicatedVideoMemory);
//				BX_TRACE("   availableDedicatedVideoMemory: %d KiB", memInfo.availableDedicatedVideoMemory);
//				BX_TRACE("               systemVideoMemory: %d KiB", memInfo.systemVideoMemory);
//				BX_TRACE("              sharedSystemMemory: %d KiB", memInfo.sharedSystemMemory);
//				BX_TRACE("curAvailableDedicatedVideoMemory: %d KiB", memInfo.curAvailableDedicatedVideoMemory);
			}
		}
		else
		{
			_gpuMemoryMax  = -INT64_MAX;
			_gpuMemoryUsed = -INT64_MAX;
		}
	}

	bool NvApi::initAftermath(const ID3D12Device* _device, const ID3D12CommandList* _commandList)
	{
		m_nvAftermathDll = bx::dlopen(
			"GFSDK_Aftermath_Lib."
#if BX_ARCH_32BIT
			"x86"
#else
			"x64"
#endif // BX_ARCH_32BIT
			".dll"
			);

		if (NULL != m_nvAftermathDll)
		{
			nvAftermathDx12Initialize          = (PFN_NVAFTERMATH_DX12_INITIALIZE         )bx::dlsym(m_nvAftermathDll, "GFSDK_Aftermath_DX12_Initialize");
			nvAftermathDx12CreateContextHandle = (PFN_NVAFTERMATH_DX12_CREATECONTEXTHANDLE)bx::dlsym(m_nvAftermathDll, "GFSDK_Aftermath_DX12_CreateContextHandle");
			nvAftermathReleaseContextHandle	   = (PFN_NVAFTERMATH_RELEASECONTEXTHANDLE    )bx::dlsym(m_nvAftermathDll, "GFSDK_Aftermath_ReleaseContextHandle");
			nvAftermathSetEventMarker          = (PFN_NVAFTERMATH_SETEVENTMARKER          )bx::dlsym(m_nvAftermathDll, "GFSDK_Aftermath_SetEventMarker");
			nvAftermathGetData                 = (PFN_NVAFTERMATH_GETDATA                 )bx::dlsym(m_nvAftermathDll, "GFSDK_Aftermath_GetData");
			nvAftermathGetDeviceStatus         = (PFN_NVAFTERMATH_GETDEVICESTATUS         )bx::dlsym(m_nvAftermathDll, "GFSDK_Aftermath_GetDeviceStatus");
			nvAftermathGetPageFaultInformation = (PFN_NVAFTERMATH_GETPAGEFAULTINFORMATION )bx::dlsym(m_nvAftermathDll, "GFSDK_Aftermath_GetPageFaultInformation");

			bool initialized = true
				&& NULL != nvAftermathDx12Initialize
				&& NULL != nvAftermathDx12CreateContextHandle
				&& NULL != nvAftermathReleaseContextHandle
				&& NULL != nvAftermathSetEventMarker
				&& NULL != nvAftermathGetData
				&& NULL != nvAftermathGetDeviceStatus
				&& NULL != nvAftermathGetPageFaultInformation
				;

			if (initialized)
			{
				int32_t result;
				result = nvAftermathDx12Initialize(0x13, 1, _device);
				if (1 == result)
				{
					result = nvAftermathDx12CreateContextHandle(_commandList, &m_aftermathHandle);
					BX_WARN(1 == result, "%x", result);

					if (1 == result)
					{
						return true;
					}
				}
			}

			shutdownAftermath();
		}

		return false;
	}

	void NvApi::shutdownAftermath()
	{
		if (NULL != m_nvAftermathDll)
		{
			if (NULL != m_aftermathHandle)
			{
				nvAftermathReleaseContextHandle(m_aftermathHandle);
				m_aftermathHandle = NULL;
			}

			bx::dlclose(m_nvAftermathDll);
			m_nvAftermathDll = NULL;
		}
	}

#define NVA_CHECK(_call) \
			BX_MACRO_BLOCK_BEGIN \
				int32_t __result__ = _call; \
				BX_CHECK(1 == __result__, #_call " FAILED 0x%08x\n", __result__); \
			BX_MACRO_BLOCK_END

	void NvApi::setMarker(const bx::StringView& _marker)
	{
		if (NULL != m_aftermathHandle)
		{
			NVA_CHECK(nvAftermathSetEventMarker(m_aftermathHandle, _marker.getPtr(), _marker.getLength() ) );
		}
	}

} // namespace bgfx
<commit_msg>Cleanup.<commit_after>/*
 * Copyright 2011-2018 Branimir Karadzic. All rights reserved.
 * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
 */

#include "bgfx_p.h"
#include "nvapi.h"

namespace bgfx
{
	/*
	 * NVAPI
	 *
	 * Reference:
	 * http://docs.nvidia.com/gameworks/content/gameworkslibrary/coresdk/nvapi/index.html
	 * https://github.com/jNizM/AHK_NVIDIA_NvAPI/blob/master/info/NvAPI_IDs.txt
	 */

	struct NvPhysicalGpuHandle;

#define NVAPI_MAX_PHYSICAL_GPUS 64

#if BX_PLATFORM_WINDOWS
#	define NVAPICALL __cdecl
#else
#	define NVAPICALL
#endif // BX_PLATFORM_WINDOWS

	enum NvApiStatus
	{
		NVAPI_OK    =  0,
		NVAPI_ERROR = -1,
	};

	struct NvMemoryInfoV2
	{
		NvMemoryInfoV2()
			: version(sizeof(NvMemoryInfoV2) | (2 << 16) )
		{
		}

		uint32_t version;
		uint32_t dedicatedVideoMemory;
		uint32_t availableDedicatedVideoMemory;
		uint32_t systemVideoMemory;
		uint32_t sharedSystemMemory;
		uint32_t curAvailableDedicatedVideoMemory;
	};

	typedef void*       (NVAPICALL* PFN_NVAPI_QUERYINTERFACE)(uint32_t _functionOffset);
	typedef NvApiStatus (NVAPICALL* PFN_NVAPI_INITIALIZE)();
	typedef NvApiStatus (NVAPICALL* PFN_NVAPI_UNLOAD)();
	typedef NvApiStatus (NVAPICALL* PFN_NVAPI_ENUMPHYSICALGPUS)(NvPhysicalGpuHandle* _handle[NVAPI_MAX_PHYSICAL_GPUS], uint32_t* _gpuCount);
	typedef NvApiStatus (NVAPICALL* PFN_NVAPI_GPUGETMEMORYINFO)(NvPhysicalGpuHandle* _handle, NvMemoryInfoV2* _memoryInfo);
	typedef NvApiStatus (NVAPICALL* PFN_NVAPI_GPUGETFULLNAME)(NvPhysicalGpuHandle* _physicalGpu, char _name[64]);

#define NVAPI_INITIALIZE                        UINT32_C(0x0150e828)
#define NVAPI_UNLOAD                            UINT32_C(0xd22bdd7e)
#define NVAPI_ENUMPHYSICALGPUS                  UINT32_C(0xe5ac921f)
#define NVAPI_GPUGETMEMORYINFO                  UINT32_C(0x07f9b368)
#define NVAPI_GPUGETFULLNAME                    UINT32_C(0xceee8e9f)
#define NVAPI_MULTIDRAWINSTANCEDINDIRECT        UINT32_C(0xd4e26bbf)
#define NVAPI_MULTIDRAWINDEXEDINSTANCEDINDIRECT UINT32_C(0x59e890f9)

	static PFN_NVAPI_QUERYINTERFACE   nvApiQueryInterface;
	static PFN_NVAPI_INITIALIZE       nvApiInitialize;
	static PFN_NVAPI_UNLOAD           nvApiUnload;
	static PFN_NVAPI_ENUMPHYSICALGPUS nvApiEnumPhysicalGPUs;
	static PFN_NVAPI_GPUGETMEMORYINFO nvApiGpuGetMemoryInfo;
	static PFN_NVAPI_GPUGETFULLNAME   nvApiGpuGetFullName;

	/*
	 * NVIDIA Aftermath
	 *
	 * Reference:
	 * https://developer.nvidia.com/nvidia-aftermath
	 */

	typedef int32_t (*PFN_NVAFTERMATH_DX12_INITIALIZE)(int32_t _version, int32_t _flags, const ID3D12Device* _device);
	typedef int32_t (*PFN_NVAFTERMATH_DX12_CREATECONTEXTHANDLE)(const ID3D12CommandList* _commandList, NvAftermathContextHandle** _outContextHandle);
	typedef int32_t (*PFN_NVAFTERMATH_RELEASECONTEXTHANDLE)(const NvAftermathContextHandle* _contextHandle);
	typedef int32_t (*PFN_NVAFTERMATH_SETEVENTMARKER)(const NvAftermathContextHandle* _contextHandle, const void* _markerData, uint32_t _markerSize);
	typedef int32_t (*PFN_NVAFTERMATH_GETDATA)(uint32_t _numContexts, const NvAftermathContextHandle** _contextHandles, void* _outContextData);
	typedef int32_t (*PFN_NVAFTERMATH_GETDEVICESTATUS)(void* _outStatus);
	typedef int32_t (*PFN_NVAFTERMATH_GETPAGEFAULTINFORMATION)(void* _outPageFaultInformation);

	static PFN_NVAFTERMATH_DX12_INITIALIZE          nvAftermathDx12Initialize;
	static PFN_NVAFTERMATH_DX12_CREATECONTEXTHANDLE nvAftermathDx12CreateContextHandle;
	static PFN_NVAFTERMATH_RELEASECONTEXTHANDLE     nvAftermathReleaseContextHandle;
	static PFN_NVAFTERMATH_SETEVENTMARKER           nvAftermathSetEventMarker;
	static PFN_NVAFTERMATH_GETDATA                  nvAftermathGetData;
	static PFN_NVAFTERMATH_GETDEVICESTATUS          nvAftermathGetDeviceStatus;
	static PFN_NVAFTERMATH_GETPAGEFAULTINFORMATION  nvAftermathGetPageFaultInformation;

	NvApi::NvApi()
		: m_nvApiDll(NULL)
		, m_nvGpu(NULL)
		, m_nvAftermathDll(NULL)
		, m_aftermathHandle(NULL)
	{
	}

	void NvApi::init()
	{
		m_nvGpu = NULL;
		m_nvApiDll = bx::dlopen(
			"nvapi"
#if BX_ARCH_64BIT
			"64"
#endif // BX_ARCH_32BIT
			".dll"
			);

		if (NULL != m_nvApiDll)
		{
			nvApiQueryInterface = (PFN_NVAPI_QUERYINTERFACE)bx::dlsym(m_nvApiDll, "nvapi_QueryInterface");

			bool initialized = NULL != nvApiQueryInterface;

			if (initialized)
			{
				nvApiInitialize       = (PFN_NVAPI_INITIALIZE      )nvApiQueryInterface(NVAPI_INITIALIZE);
				nvApiUnload           = (PFN_NVAPI_UNLOAD          )nvApiQueryInterface(NVAPI_UNLOAD);
				nvApiEnumPhysicalGPUs = (PFN_NVAPI_ENUMPHYSICALGPUS)nvApiQueryInterface(NVAPI_ENUMPHYSICALGPUS);
				nvApiGpuGetMemoryInfo = (PFN_NVAPI_GPUGETMEMORYINFO)nvApiQueryInterface(NVAPI_GPUGETMEMORYINFO);
				nvApiGpuGetFullName   = (PFN_NVAPI_GPUGETFULLNAME  )nvApiQueryInterface(NVAPI_GPUGETFULLNAME);

				nvApiD3D11MultiDrawInstancedIndirect        = (PFN_NVAPI_MULTIDRAWINDIRECT)nvApiQueryInterface(NVAPI_MULTIDRAWINSTANCEDINDIRECT);
				nvApiD3D11MultiDrawIndexedInstancedIndirect = (PFN_NVAPI_MULTIDRAWINDIRECT)nvApiQueryInterface(NVAPI_MULTIDRAWINDEXEDINSTANCEDINDIRECT);

				initialized = true
					&& NULL != nvApiInitialize
					&& NULL != nvApiUnload
					&& NULL != nvApiEnumPhysicalGPUs
					&& NULL != nvApiGpuGetMemoryInfo
					&& NULL != nvApiGpuGetFullName
					&& NVAPI_OK == nvApiInitialize()
					;

				if (initialized)
				{
					NvPhysicalGpuHandle* physicalGpus[NVAPI_MAX_PHYSICAL_GPUS];
					uint32_t numGpus = 0;
					nvApiEnumPhysicalGPUs(physicalGpus, &numGpus);

					initialized = 0 < numGpus;
					if (initialized)
					{
						m_nvGpu = physicalGpus[0];
					}

					char name[64];
					nvApiGpuGetFullName(m_nvGpu, name);
					BX_TRACE("%s", name);
				}

				initialized = NULL != m_nvGpu;

				if (!initialized)
				{
					nvApiUnload();
				}
			}

			if (!initialized)
			{
				bx::dlclose(m_nvApiDll);
				m_nvApiDll = NULL;
			}

			BX_WARN(!initialized, "NVAPI supported.");
		}
	}

	void NvApi::shutdown()
	{
		if (NULL != m_nvGpu)
		{
			nvApiUnload();
			m_nvGpu = NULL;
		}

		if (NULL != m_nvApiDll)
		{
			bx::dlclose(m_nvApiDll);
			m_nvApiDll = NULL;
		}

		shutdownAftermath();
	}

	void NvApi::getMemoryInfo(int64_t& _gpuMemoryUsed, int64_t& _gpuMemoryMax)
	{
		if (NULL != m_nvGpu)
		{
			NvMemoryInfoV2 memInfo;
			NvApiStatus status = nvApiGpuGetMemoryInfo(m_nvGpu, &memInfo);
			if (NVAPI_OK == status)
			{
				_gpuMemoryMax  = 1024 * int64_t(memInfo.availableDedicatedVideoMemory);
				_gpuMemoryUsed = 1024 * int64_t(memInfo.availableDedicatedVideoMemory - memInfo.curAvailableDedicatedVideoMemory);
//				BX_TRACE("            dedicatedVideoMemory: %d KiB", memInfo.dedicatedVideoMemory);
//				BX_TRACE("   availableDedicatedVideoMemory: %d KiB", memInfo.availableDedicatedVideoMemory);
//				BX_TRACE("               systemVideoMemory: %d KiB", memInfo.systemVideoMemory);
//				BX_TRACE("              sharedSystemMemory: %d KiB", memInfo.sharedSystemMemory);
//				BX_TRACE("curAvailableDedicatedVideoMemory: %d KiB", memInfo.curAvailableDedicatedVideoMemory);
			}
		}
		else
		{
			_gpuMemoryMax  = -INT64_MAX;
			_gpuMemoryUsed = -INT64_MAX;
		}
	}

	bool NvApi::initAftermath(const ID3D12Device* _device, const ID3D12CommandList* _commandList)
	{
		m_nvAftermathDll = bx::dlopen(
			"GFSDK_Aftermath_Lib."
#if BX_ARCH_32BIT
			"x86"
#else
			"x64"
#endif // BX_ARCH_32BIT
			".dll"
			);

		if (NULL != m_nvAftermathDll)
		{
			nvAftermathDx12Initialize          = (PFN_NVAFTERMATH_DX12_INITIALIZE         )bx::dlsym(m_nvAftermathDll, "GFSDK_Aftermath_DX12_Initialize");
			nvAftermathDx12CreateContextHandle = (PFN_NVAFTERMATH_DX12_CREATECONTEXTHANDLE)bx::dlsym(m_nvAftermathDll, "GFSDK_Aftermath_DX12_CreateContextHandle");
			nvAftermathReleaseContextHandle	   = (PFN_NVAFTERMATH_RELEASECONTEXTHANDLE    )bx::dlsym(m_nvAftermathDll, "GFSDK_Aftermath_ReleaseContextHandle");
			nvAftermathSetEventMarker          = (PFN_NVAFTERMATH_SETEVENTMARKER          )bx::dlsym(m_nvAftermathDll, "GFSDK_Aftermath_SetEventMarker");
			nvAftermathGetData                 = (PFN_NVAFTERMATH_GETDATA                 )bx::dlsym(m_nvAftermathDll, "GFSDK_Aftermath_GetData");
			nvAftermathGetDeviceStatus         = (PFN_NVAFTERMATH_GETDEVICESTATUS         )bx::dlsym(m_nvAftermathDll, "GFSDK_Aftermath_GetDeviceStatus");
			nvAftermathGetPageFaultInformation = (PFN_NVAFTERMATH_GETPAGEFAULTINFORMATION )bx::dlsym(m_nvAftermathDll, "GFSDK_Aftermath_GetPageFaultInformation");

			bool initialized = true
				&& NULL != nvAftermathDx12Initialize
				&& NULL != nvAftermathDx12CreateContextHandle
				&& NULL != nvAftermathReleaseContextHandle
				&& NULL != nvAftermathSetEventMarker
				&& NULL != nvAftermathGetData
				&& NULL != nvAftermathGetDeviceStatus
				&& NULL != nvAftermathGetPageFaultInformation
				;

			if (initialized)
			{
				int32_t result;
				result = nvAftermathDx12Initialize(0x13, 1, _device);
				if (1 == result)
				{
					result = nvAftermathDx12CreateContextHandle(_commandList, &m_aftermathHandle);
					BX_WARN(1 == result, "%x", result);

					if (1 == result)
					{
						return true;
					}
				}
			}

			shutdownAftermath();
		}

		return false;
	}

	void NvApi::shutdownAftermath()
	{
		if (NULL != m_nvAftermathDll)
		{
			if (NULL != m_aftermathHandle)
			{
				nvAftermathReleaseContextHandle(m_aftermathHandle);
				m_aftermathHandle = NULL;
			}

			bx::dlclose(m_nvAftermathDll);
			m_nvAftermathDll = NULL;
		}
	}

#define NVA_CHECK(_call) \
			BX_MACRO_BLOCK_BEGIN \
				int32_t __result__ = _call; \
				BX_CHECK(1 == __result__, #_call " FAILED 0x%08x\n", __result__); \
			BX_MACRO_BLOCK_END

	void NvApi::setMarker(const bx::StringView& _marker)
	{
		if (NULL != m_aftermathHandle)
		{
			NVA_CHECK(nvAftermathSetEventMarker(m_aftermathHandle, _marker.getPtr(), _marker.getLength() ) );
		}
	}

} // namespace bgfx
<|endoftext|>


<commit_before>/*************************************************************************\
**
**  tOutput.cpp: Functions for output objects
**
**
**
**  $Id: tOutput.cpp,v 1.7 1998-06-04 17:57:10 gtucker Exp $
\*************************************************************************/

#include "tOutput.h"

/*************************************************************************\
**
**  Constructor
**
**  The constructor takes two arguments, a pointer to the grid mesh and
**  a reference to an open input file. It reads the base name for the
**  output files from the input file, and opens and initializes these.
**
**  Input: gridPtr -- pointer to a tGrid object (or descendant), assumed
**                    valid
**         infile -- reference to an open input file, assumed valid
**
\*************************************************************************/
template< class tSubNode >
tOutput<tSubNode>::tOutput( tGrid<tSubNode> * gridPtr, tInputFile &infile )
{
   assert( gridPtr > 0 );
   g = gridPtr;

   infile.ReadItem( baseName, "OUTFILENAME" );

   CreateAndOpenFile( &nodeofs, ".nodes" );
   CreateAndOpenFile( &edgofs, ".edges" );
   CreateAndOpenFile( &triofs, ".tri" );
   CreateAndOpenFile( &zofs, ".z" );

}

/*************************************************************************\
**
**  CreateAndOpenFile
**
**  Opens the output file stream pointed by theOFStream, giving it the
**  name <baseName><extension>, and checks to make sure that the ofstream
**  is valid.
**
**  Input:  theOFStream -- ptr to an ofstream object
**          extension -- file name extension (e.g., ".nodes")
**  Output: theOFStream is initialized to create an open output file
**  Assumes: extension is a null-terminated string, and the length of
**           baseName plus extension doesn't exceed kMaxNameSize+6
**           (ie, the extension is expected to be <= 6 characters)
**
\*************************************************************************/
template< class tSubNode >
void tOutput<tSubNode>::CreateAndOpenFile( ofstream *theOFStream,
                                           char *extension )
{
   char fullName[kMaxNameSize+6];

   strcpy( fullName, baseName );
   strcat( fullName, extension );
   theOFStream->open( fullName );

   if( !theOFStream->good() )
       ReportFatalError(
           "I can't create files for output. Memory may be exhausted." );

}

/*************************************************************************\
**
**  WriteOutput
**
**  This function writes information about the mesh to four files called
**  name.nodes, name.edges, name.tri, and name.z, where "name" is a
**  name that the user has specified in the input file and which is
**  stored in the data member baseName.
**
**  Input: time -- time of the current output time-slice
**  Output: the node, edge, and triangle ID numbers are modified so that
**          they are numbered according to their position on the list
**  Assumes: the four file ofstreams have been opened by the constructor
**           and are valid
**
**  TODO: deal with option for once-only printing of mesh when mesh not
**        deforming
\*************************************************************************/
template< class tSubNode >
void tOutput<tSubNode>::WriteOutput( double time )
{
   tGridListIter<tSubNode> niter( g->GetNodeList() );
   tGridListIter<tEdge> eiter( g->GetEdgeList() );
   tListIter<tTriangle> titer( g->GetTriList() );
   tNode * cn;
   tEdge * ce;
   tTriangle * ct;
   int id;
   int nnodes = g->GetNodeList()->getSize();
   int nedges = g->GetEdgeList()->getSize();
   int ntri = g->GetTriList()->getSize();

   cout << "tOutput::WriteOutput()\n";

   // Renumber IDs in order by position on list
   for( cn=niter.FirstP(), id=0; id<nnodes; cn=niter.NextP(), id++ )
       cn->setID( id );
   for( ce=eiter.FirstP(), id=0; id<nedges; ce=eiter.NextP(), id++ )
       ce->setID( id );
   for( ct=titer.FirstP(), id=0; id<ntri; ct=titer.NextP(), id++ )
       ct->setID( id );

   // Write node file and z file
   nodeofs << " " << time << endl << nnodes << endl;
   zofs << " " << time << endl << nnodes << endl;
   for( cn=niter.FirstP(); !(niter.AtEnd()); cn=niter.NextP() )
   {
      nodeofs << cn->getX() << " " << cn->getY() << " "
              << cn->GetEdg()->getID() << " " << cn->getBoundaryFlag() << endl;
      zofs << cn->getZ() << endl;
   }

   // Write edge file
   edgofs << " " << time << endl << nedges << endl;
   for( ce=eiter.FirstP(); !(eiter.AtEnd()); ce=eiter.NextP() )
      edgofs << ce->getOriginPtrNC()->getID() << " "
             << ce->getDestinationPtrNC()->getID() << " "
             << ce->GetCCWEdg()->getID() << endl;

   // Write triangle file
   int i;
   triofs << " " << time << endl << ntri << endl;
   for( ct=titer.FirstP(); !(titer.AtEnd()); ct=titer.NextP() )
   {
      for( i=0; i<=2; i++ )
          triofs << ct->pPtr(i)->getID() << " ";
      for( i=0; i<=2; i++ )
      {
          if( ct->tPtr(i) ) triofs << ct->tPtr(i)->getID() << " ";
          else triofs << "-1 ";
      }
      triofs << ct->ePtr(0)->getID() << " "
             << ct->ePtr(1)->getID() << " "
             << ct->ePtr(2)->getID() << endl;
   }

   WriteNodeData( time );

}

template< class tSubNode >
void tOutput<tSubNode>::WriteNodeData( double time )
{}

template< class tSubNode >
tLOutput<tSubNode>::tLOutput( tGrid<tSubNode> *g, tInputFile &infile )
        : tOutput<tSubNode>( g, infile )  // call base-class constructor
{
   CreateAndOpenFile( &drareaofs, ".area" );
   CreateAndOpenFile( &netofs, ".net" );
   CreateAndOpenFile( &slpofs, ".slp" );
   CreateAndOpenFile( &qofs, ".q" );

}

template< class tSubNode >
void tLOutput<tSubNode>::WriteNodeData( double time )
{
   tGridListIter<tSubNode> ni( g->GetNodeList() );
   tSubNode *cn;
   int nActiveNodes = g->GetNodeList()->getActiveSize();

   drareaofs << " " << time << "\n " << nActiveNodes << endl;
   netofs << " " << time << "\n " << nActiveNodes << endl;
   slpofs << " " << time << "\n " << nActiveNodes << endl;
   qofs << " " << time << "\n " << nActiveNodes << endl;

   for( cn = ni.FirstP(); ni.IsActive(); cn = ni.NextP() )
   {
      assert( cn>0 );
      drareaofs << cn->getDrArea() << endl;
      if( cn->getDownstrmNbr() )
          netofs << cn->getDownstrmNbr()->getID() << endl;
      slpofs << cn->getSlope() << endl;
      qofs << cn->getQ() << endl;
   }

}
<commit_msg>changed capitalization on get/set fns also changed output of q to all nodes, not just active ones<commit_after>/*************************************************************************\
**
**  tOutput.cpp: Functions for output objects
**
**
**
**  $Id: tOutput.cpp,v 1.8 1998-06-04 21:25:57 gtucker Exp $
\*************************************************************************/

#include "tOutput.h"

/*************************************************************************\
**
**  Constructor
**
**  The constructor takes two arguments, a pointer to the grid mesh and
**  a reference to an open input file. It reads the base name for the
**  output files from the input file, and opens and initializes these.
**
**  Input: gridPtr -- pointer to a tGrid object (or descendant), assumed
**                    valid
**         infile -- reference to an open input file, assumed valid
**
\*************************************************************************/
template< class tSubNode >
tOutput<tSubNode>::tOutput( tGrid<tSubNode> * gridPtr, tInputFile &infile )
{
   assert( gridPtr > 0 );
   g = gridPtr;

   infile.ReadItem( baseName, "OUTFILENAME" );

   CreateAndOpenFile( &nodeofs, ".nodes" );
   CreateAndOpenFile( &edgofs, ".edges" );
   CreateAndOpenFile( &triofs, ".tri" );
   CreateAndOpenFile( &zofs, ".z" );

}

/*************************************************************************\
**
**  CreateAndOpenFile
**
**  Opens the output file stream pointed by theOFStream, giving it the
**  name <baseName><extension>, and checks to make sure that the ofstream
**  is valid.
**
**  Input:  theOFStream -- ptr to an ofstream object
**          extension -- file name extension (e.g., ".nodes")
**  Output: theOFStream is initialized to create an open output file
**  Assumes: extension is a null-terminated string, and the length of
**           baseName plus extension doesn't exceed kMaxNameSize+6
**           (ie, the extension is expected to be <= 6 characters)
**
\*************************************************************************/
template< class tSubNode >
void tOutput<tSubNode>::CreateAndOpenFile( ofstream *theOFStream,
                                           char *extension )
{
   char fullName[kMaxNameSize+6];

   strcpy( fullName, baseName );
   strcat( fullName, extension );
   theOFStream->open( fullName );

   if( !theOFStream->good() )
       ReportFatalError(
           "I can't create files for output. Memory may be exhausted." );

}

/*************************************************************************\
**
**  WriteOutput
**
**  This function writes information about the mesh to four files called
**  name.nodes, name.edges, name.tri, and name.z, where "name" is a
**  name that the user has specified in the input file and which is
**  stored in the data member baseName.
**
**  Input: time -- time of the current output time-slice
**  Output: the node, edge, and triangle ID numbers are modified so that
**          they are numbered according to their position on the list
**  Assumes: the four file ofstreams have been opened by the constructor
**           and are valid
**
**  TODO: deal with option for once-only printing of mesh when mesh not
**        deforming
\*************************************************************************/
template< class tSubNode >
void tOutput<tSubNode>::WriteOutput( double time )
{
   tGridListIter<tSubNode> niter( g->getNodeList() );
   tGridListIter<tEdge> eiter( g->getEdgeList() );
   tListIter<tTriangle> titer( g->getTriList() );
   tNode * cn;
   tEdge * ce;
   tTriangle * ct;
   int id;
   int nnodes = g->getNodeList()->getSize();
   int nedges = g->getEdgeList()->getSize();
   int ntri = g->getTriList()->getSize();

   cout << "tOutput::WriteOutput()\n";

   // Renumber IDs in order by position on list
   for( cn=niter.FirstP(), id=0; id<nnodes; cn=niter.NextP(), id++ )
       cn->setID( id );
   for( ce=eiter.FirstP(), id=0; id<nedges; ce=eiter.NextP(), id++ )
       ce->setID( id );
   for( ct=titer.FirstP(), id=0; id<ntri; ct=titer.NextP(), id++ )
       ct->setID( id );

   // Write node file and z file
   nodeofs << " " << time << endl << nnodes << endl;
   zofs << " " << time << endl << nnodes << endl;
   for( cn=niter.FirstP(); !(niter.AtEnd()); cn=niter.NextP() )
   {
      nodeofs << cn->getX() << " " << cn->getY() << " "
              << cn->getEdg()->getID() << " " << cn->getBoundaryFlag() << endl;
      zofs << cn->getZ() << endl;
   }

   // Write edge file
   edgofs << " " << time << endl << nedges << endl;
   for( ce=eiter.FirstP(); !(eiter.AtEnd()); ce=eiter.NextP() )
      edgofs << ce->getOriginPtrNC()->getID() << " "
             << ce->getDestinationPtrNC()->getID() << " "
             << ce->getCCWEdg()->getID() << endl;

   // Write triangle file
   int i;
   triofs << " " << time << endl << ntri << endl;
   for( ct=titer.FirstP(); !(titer.AtEnd()); ct=titer.NextP() )
   {
      for( i=0; i<=2; i++ )
          triofs << ct->pPtr(i)->getID() << " ";
      for( i=0; i<=2; i++ )
      {
          if( ct->tPtr(i) ) triofs << ct->tPtr(i)->getID() << " ";
          else triofs << "-1 ";
      }
      triofs << ct->ePtr(0)->getID() << " "
             << ct->ePtr(1)->getID() << " "
             << ct->ePtr(2)->getID() << endl;
   }

   WriteNodeData( time );

}

template< class tSubNode >
void tOutput<tSubNode>::WriteNodeData( double time )
{}

template< class tSubNode >
tLOutput<tSubNode>::tLOutput( tGrid<tSubNode> *g, tInputFile &infile )
        : tOutput<tSubNode>( g, infile )  // call base-class constructor
{
   CreateAndOpenFile( &drareaofs, ".area" );
   CreateAndOpenFile( &netofs, ".net" );
   CreateAndOpenFile( &slpofs, ".slp" );
   CreateAndOpenFile( &qofs, ".q" );

}

//TODO: should output boundary points as well so they'll map up with nodes
// for plotting. Means changing getSlope so it returns zero if flowedg
// undefined
template< class tSubNode >
void tLOutput<tSubNode>::WriteNodeData( double time )
{
   tGridListIter<tSubNode> ni( g->getNodeList() );
   tSubNode *cn;
   int nActiveNodes = g->getNodeList()->getActiveSize();
   int nnodes = g->getNodeList()->getSize();

   drareaofs << " " << time << "\n " << nActiveNodes << endl;
   netofs << " " << time << "\n " << nActiveNodes << endl;
   slpofs << " " << time << "\n " << nActiveNodes << endl;
   qofs << " " << time << "\n " << nnodes << endl;

   for( cn = ni.FirstP(); ni.IsActive(); cn = ni.NextP() )
   {
      assert( cn>0 );
      drareaofs << cn->getDrArea() << endl;
      if( cn->getDownstrmNbr() )
          netofs << cn->getDownstrmNbr()->getID() << endl;
      slpofs << cn->getSlope() << endl;
   }

   for( cn = ni.FirstP(); !(ni.AtEnd()); cn = ni.NextP() )
      qofs << cn->getQ() << endl;

}
<|endoftext|>


<commit_before>#include "GameObject.h"
#include "Engine.h"
#include "Objects\LevelGrid.h"
#include "Scenes\GameplayScene.h"

USING_NS_CC;

GameObject::GameObject(Type type)
	: _direction(Direction::UP), _sprite(nullptr), _engine(Engine::getInstance()),
	_type(type), _isPassable(true)
{ }

GameObject::~GameObject()
{
	_sprite = nullptr;
	_engine = nullptr;

	if (!_isPassable)
		removeFromPassableLayer(_position);
}

bool GameObject::init()
{
	return Node::init();
}

GameObject::Direction GameObject::getGridDirection()
{
	return _direction;
}

void GameObject::setGridDirection(Direction direction)
{
	_direction = direction;
	setGridDirection(_sprite, direction);
}

Pos2 GameObject::getGridPosition() const
{
	return _position;
}

void GameObject::setGridPosition(const Pos2& p)
{
	auto prevPos = _position;
	_position = p;
	setGridPosition(_sprite, p);

	if (!_isPassable)
		updatePassableLayer(p, prevPos);
}

void GameObject::setGridPosition(int x, int y)
{
	setGridPosition(Pos2(x, y));
}

Pos2 GameObject::getGridPosition(const Node* node)
{
	return Pos2(node->getPosition() / TILE_SIZE);
}

void GameObject::setGridPosition(Node* node, const Pos2& p)
{
	node->setPosition(Vec2(p.x, p.y)  * TILE_SIZE + Vec2::ONE * TILE_SIZE / 2);
}

void GameObject::setGridPosition(Node* node, int x, int y)
{
	setGridPosition(node, Pos2(x, y));
}

void GameObject::setGridDirection(Node* node, Direction direction)
{
	node->setRotation(directionToRotation(direction));
}

Sprite* GameObject::getSprite()
{
	return _sprite;
}

void GameObject::setSprite(Sprite* sprite)
{
	if (_sprite != nullptr && _sprite->getParent() == this)
		this->removeChild(_sprite);

	_sprite = sprite;

	this->addChild(_sprite);
}

Pos2 GameObject::directionToOffset(Direction direction)
{
	switch (direction)
	{
	case Direction::DOWN:
		return Pos2(0, -1);
	case Direction::UP:
		return Pos2(0, +1);
	case Direction::LEFT:
		return Pos2(-1, 0);
	case Direction::RIGHT:
		return Pos2(+1, 0);
	}
	return Pos2(0, 0);
}

GameObject::Direction GameObject::offsetToDirection(Pos2 offset)
{
	offset.normalize();

	if (offset == Pos2(0, -1))
		return Direction::DOWN;
	if (offset == Pos2(0, +1))
		return Direction::UP;
	if (offset == Pos2(-1, 0))
		return Direction::LEFT;
	if (offset == Pos2(+1, 0))
		return Direction::RIGHT;

	throw std::logic_error("Can not convert offset " + offset.toString() + " to direction!");
}

float GameObject::directionToRotation(Direction direction)
{
	switch (direction)
	{
	case Direction::UP:
		return 0.0f;
	case Direction::DOWN:
		return 180.0f;
	case Direction::LEFT:
		return -90.0f;
	case Direction::RIGHT:
		return 90.0f;
	}
	return 0.0f;
}

void GameObject::updatePassableLayer(const Pos2& pos, const Pos2& prevPos)
{
	auto scene = Engine::getInstance()->getCurrentScene<GameplayScene>();
	if (scene == nullptr)
		return;
	auto grid = scene->getGrid();

	grid->setDynamicPassable(prevPos, PassableValue::PASSABLE);
	grid->setDynamicPassable(pos, PassableValue::INPASSABLE);
}

void GameObject::removeFromPassableLayer(const Pos2& pos)
{
	auto scene = Engine::getInstance()->getCurrentScene<GameplayScene>();
	if (scene == nullptr)
		return;
	auto grid = scene->getGrid();

	grid->setDynamicPassable(pos, PassableValue::PASSABLE);
}<commit_msg>Added missing consts<commit_after>#include "GameObject.h"
#include "Engine.h"
#include "Objects\LevelGrid.h"
#include "Scenes\GameplayScene.h"

USING_NS_CC;

GameObject::GameObject(Type type)
	: _direction(Direction::UP), _sprite(nullptr), _engine(Engine::getInstance()),
	_type(type), _isPassable(true)
{ }

GameObject::~GameObject()
{
	_sprite = nullptr;
	_engine = nullptr;

	if (!_isPassable)
		removeFromPassableLayer(_position);
}

bool GameObject::init()
{
	return Node::init();
}

GameObject::Direction GameObject::getGridDirection() const
{
	return _direction;
}

void GameObject::setGridDirection(Direction direction)
{
	_direction = direction;
	setGridDirection(_sprite, direction);
}

Pos2 GameObject::getGridPosition() const
{
	return _position;
}

void GameObject::setGridPosition(const Pos2& p)
{
	auto prevPos = _position;
	_position = p;
	setGridPosition(_sprite, p);

	if (!_isPassable)
		updatePassableLayer(p, prevPos);
}

void GameObject::setGridPosition(int x, int y)
{
	setGridPosition(Pos2(x, y));
}

Pos2 GameObject::getGridPosition(const Node* node)
{
	return Pos2(node->getPosition() / TILE_SIZE);
}

void GameObject::setGridPosition(Node* node, const Pos2& p)
{
	node->setPosition(Vec2(p.x, p.y)  * TILE_SIZE + Vec2::ONE * TILE_SIZE / 2);
}

void GameObject::setGridPosition(Node* node, int x, int y)
{
	setGridPosition(node, Pos2(x, y));
}

void GameObject::setGridDirection(Node* node, Direction direction)
{
	node->setRotation(directionToRotation(direction));
}

Sprite* GameObject::getSprite() const
{
	return _sprite;
}

void GameObject::setSprite(Sprite* sprite)
{
	if (_sprite != nullptr && _sprite->getParent() == this)
		this->removeChild(_sprite);

	_sprite = sprite;

	this->addChild(_sprite);
}

Pos2 GameObject::directionToOffset(Direction direction)
{
	switch (direction)
	{
	case Direction::DOWN:
		return Pos2(0, -1);
	case Direction::UP:
		return Pos2(0, +1);
	case Direction::LEFT:
		return Pos2(-1, 0);
	case Direction::RIGHT:
		return Pos2(+1, 0);
	}
	return Pos2(0, 0);
}

GameObject::Direction GameObject::offsetToDirection(Pos2 offset)
{
	offset.normalize();

	if (offset == Pos2(0, -1))
		return Direction::DOWN;
	if (offset == Pos2(0, +1))
		return Direction::UP;
	if (offset == Pos2(-1, 0))
		return Direction::LEFT;
	if (offset == Pos2(+1, 0))
		return Direction::RIGHT;

	throw std::logic_error("Can not convert offset " + offset.toString() + " to direction!");
}

float GameObject::directionToRotation(Direction direction)
{
	switch (direction)
	{
	case Direction::UP:
		return 0.0f;
	case Direction::DOWN:
		return 180.0f;
	case Direction::LEFT:
		return -90.0f;
	case Direction::RIGHT:
		return 90.0f;
	}
	return 0.0f;
}

void GameObject::updatePassableLayer(const Pos2& pos, const Pos2& prevPos)
{
	auto scene = Engine::getInstance()->getCurrentScene<GameplayScene>();
	if (scene == nullptr)
		return;
	auto grid = scene->getGrid();

	grid->setDynamicPassable(prevPos, PassableValue::PASSABLE);
	grid->setDynamicPassable(pos, PassableValue::INPASSABLE);
}

void GameObject::removeFromPassableLayer(const Pos2& pos)
{
	auto scene = Engine::getInstance()->getCurrentScene<GameplayScene>();
	if (scene == nullptr)
		return;
	auto grid = scene->getGrid();

	grid->setDynamicPassable(pos, PassableValue::PASSABLE);
}<|endoftext|>


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

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

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

#include "tensorflow/lite/c/builtin_op_data.h"
#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/kernels/internal/optimized/optimized_ops.h"
#include "tensorflow/lite/kernels/internal/reference/reference_ops.h"
#include "tensorflow/lite/kernels/internal/tensor.h"
#include "tensorflow/lite/kernels/internal/tensor_ctypes.h"
#include "tensorflow/lite/kernels/internal/types.h"
#include "tensorflow/lite/kernels/kernel_util.h"

namespace tflite {
namespace ops {
namespace builtin {
namespace space_to_depth {

// This file has two implementation of SpaceToDepth. Note that SpaceToDepth
// only works on 4D tensors.
enum KernelType {
  kReference,
  kGenericOptimized,
};

constexpr int kInputTensor = 0;
constexpr int kOutputTensor = 0;

TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
  auto* params =
      reinterpret_cast<TfLiteSpaceToDepthParams*>(node->builtin_data);

  TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
  TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);

  const TfLiteTensor* input;
  TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));
  TfLiteTensor* output;
  TF_LITE_ENSURE_OK(context,
                    GetOutputSafe(context, node, kOutputTensor, &output));

  TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4);

  auto data_type = output->type;
  TF_LITE_ENSURE(context,
                 data_type == kTfLiteFloat32 || data_type == kTfLiteUInt8 ||
                     data_type == kTfLiteInt8 || data_type == kTfLiteInt32 ||
                     data_type == kTfLiteInt64);
  TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);

  const int block_size = params->block_size;
  const int input_height = input->dims->data[1];
  const int input_width = input->dims->data[2];
  int output_height = input_height / block_size;
  int output_width = input_width / block_size;

  TF_LITE_ENSURE_EQ(context, input_height, output_height * block_size);
  TF_LITE_ENSURE_EQ(context, input_width, output_width * block_size);

  TfLiteIntArray* output_size = TfLiteIntArrayCreate(4);
  output_size->data[0] = input->dims->data[0];
  output_size->data[1] = output_height;
  output_size->data[2] = output_width;
  output_size->data[3] = input->dims->data[3] * block_size * block_size;

  return context->ResizeTensor(context, output, output_size);
}

template <KernelType kernel_type>
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
  auto* params =
      reinterpret_cast<TfLiteSpaceToDepthParams*>(node->builtin_data);

  const TfLiteTensor* input;
  TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));
  TfLiteTensor* output;
  TF_LITE_ENSURE_OK(context,
                    GetOutputSafe(context, node, kOutputTensor, &output));

#define TF_LITE_SPACE_TO_DEPTH(type, scalar)                               \
  tflite::SpaceToDepthParams op_params;                                    \
  op_params.block_size = params->block_size;                               \
  type::SpaceToDepth(op_params, GetTensorShape(input),                     \
                     GetTensorData<scalar>(input), GetTensorShape(output), \
                     GetTensorData<scalar>(output))
  switch (input->type) {  // Already know in/out types are same.
    case kTfLiteFloat32:
      if (kernel_type == kReference) {
        TF_LITE_SPACE_TO_DEPTH(reference_ops, float);
      } else {
        TF_LITE_SPACE_TO_DEPTH(optimized_ops, float);
      }
      break;
    case kTfLiteUInt8:
      if (kernel_type == kReference) {
        TF_LITE_SPACE_TO_DEPTH(reference_ops, uint8_t);
      } else {
        TF_LITE_SPACE_TO_DEPTH(optimized_ops, uint8_t);
      }
      break;
    case kTfLiteInt8:
      if (kernel_type == kReference) {
        TF_LITE_SPACE_TO_DEPTH(reference_ops, int8_t);
      } else {
        TF_LITE_SPACE_TO_DEPTH(optimized_ops, int8_t);
      }
      break;
    case kTfLiteInt32:
      if (kernel_type == kReference) {
        TF_LITE_SPACE_TO_DEPTH(reference_ops, int32_t);
      } else {
        TF_LITE_SPACE_TO_DEPTH(optimized_ops, int32_t);
      }
      break;
    case kTfLiteInt64:
      if (kernel_type == kReference) {
        TF_LITE_SPACE_TO_DEPTH(reference_ops, int64_t);
      } else {
        TF_LITE_SPACE_TO_DEPTH(optimized_ops, int64_t);
      }
      break;
    default:
      context->ReportError(context, "Type '%s' not currently supported.",
                           TfLiteTypeGetName(input->type));
      return kTfLiteError;
  }
#undef TF_LITE_SPACE_TO_DEPTH

  return kTfLiteOk;
}

}  // namespace space_to_depth

TfLiteRegistration* Register_SPACE_TO_DEPTH_REF() {
  static TfLiteRegistration r = {
      nullptr, nullptr, space_to_depth::Prepare,
      space_to_depth::Eval<space_to_depth::kReference>};
  return &r;
}

TfLiteRegistration* Register_SPACE_TO_DEPTH_GENERIC_OPT() {
  static TfLiteRegistration r = {
      nullptr, nullptr, space_to_depth::Prepare,
      space_to_depth::Eval<space_to_depth::kGenericOptimized>};
  return &r;
}

TfLiteRegistration* Register_SPACE_TO_DEPTH() {
  return Register_SPACE_TO_DEPTH_GENERIC_OPT();
}

}  // namespace builtin
}  // namespace ops
}  // namespace tflite
<commit_msg>Prevent one more div by 0 in TFLite<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

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

#include "tensorflow/lite/c/builtin_op_data.h"
#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/kernels/internal/optimized/optimized_ops.h"
#include "tensorflow/lite/kernels/internal/reference/reference_ops.h"
#include "tensorflow/lite/kernels/internal/tensor.h"
#include "tensorflow/lite/kernels/internal/tensor_ctypes.h"
#include "tensorflow/lite/kernels/internal/types.h"
#include "tensorflow/lite/kernels/kernel_util.h"

namespace tflite {
namespace ops {
namespace builtin {
namespace space_to_depth {

// This file has two implementation of SpaceToDepth. Note that SpaceToDepth
// only works on 4D tensors.
enum KernelType {
  kReference,
  kGenericOptimized,
};

constexpr int kInputTensor = 0;
constexpr int kOutputTensor = 0;

TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
  auto* params =
      reinterpret_cast<TfLiteSpaceToDepthParams*>(node->builtin_data);

  TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
  TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);

  const TfLiteTensor* input;
  TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));
  TfLiteTensor* output;
  TF_LITE_ENSURE_OK(context,
                    GetOutputSafe(context, node, kOutputTensor, &output));

  TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4);

  auto data_type = output->type;
  TF_LITE_ENSURE(context,
                 data_type == kTfLiteFloat32 || data_type == kTfLiteUInt8 ||
                     data_type == kTfLiteInt8 || data_type == kTfLiteInt32 ||
                     data_type == kTfLiteInt64);
  TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);

  const int block_size = params->block_size;
  TF_LITE_ENSURE(context, block_size > 0);
  const int input_height = input->dims->data[1];
  const int input_width = input->dims->data[2];
  int output_height = input_height / block_size;
  int output_width = input_width / block_size;

  TF_LITE_ENSURE_EQ(context, input_height, output_height * block_size);
  TF_LITE_ENSURE_EQ(context, input_width, output_width * block_size);

  TfLiteIntArray* output_size = TfLiteIntArrayCreate(4);
  output_size->data[0] = input->dims->data[0];
  output_size->data[1] = output_height;
  output_size->data[2] = output_width;
  output_size->data[3] = input->dims->data[3] * block_size * block_size;

  return context->ResizeTensor(context, output, output_size);
}

template <KernelType kernel_type>
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
  auto* params =
      reinterpret_cast<TfLiteSpaceToDepthParams*>(node->builtin_data);

  const TfLiteTensor* input;
  TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));
  TfLiteTensor* output;
  TF_LITE_ENSURE_OK(context,
                    GetOutputSafe(context, node, kOutputTensor, &output));

#define TF_LITE_SPACE_TO_DEPTH(type, scalar)                               \
  tflite::SpaceToDepthParams op_params;                                    \
  op_params.block_size = params->block_size;                               \
  type::SpaceToDepth(op_params, GetTensorShape(input),                     \
                     GetTensorData<scalar>(input), GetTensorShape(output), \
                     GetTensorData<scalar>(output))
  switch (input->type) {  // Already know in/out types are same.
    case kTfLiteFloat32:
      if (kernel_type == kReference) {
        TF_LITE_SPACE_TO_DEPTH(reference_ops, float);
      } else {
        TF_LITE_SPACE_TO_DEPTH(optimized_ops, float);
      }
      break;
    case kTfLiteUInt8:
      if (kernel_type == kReference) {
        TF_LITE_SPACE_TO_DEPTH(reference_ops, uint8_t);
      } else {
        TF_LITE_SPACE_TO_DEPTH(optimized_ops, uint8_t);
      }
      break;
    case kTfLiteInt8:
      if (kernel_type == kReference) {
        TF_LITE_SPACE_TO_DEPTH(reference_ops, int8_t);
      } else {
        TF_LITE_SPACE_TO_DEPTH(optimized_ops, int8_t);
      }
      break;
    case kTfLiteInt32:
      if (kernel_type == kReference) {
        TF_LITE_SPACE_TO_DEPTH(reference_ops, int32_t);
      } else {
        TF_LITE_SPACE_TO_DEPTH(optimized_ops, int32_t);
      }
      break;
    case kTfLiteInt64:
      if (kernel_type == kReference) {
        TF_LITE_SPACE_TO_DEPTH(reference_ops, int64_t);
      } else {
        TF_LITE_SPACE_TO_DEPTH(optimized_ops, int64_t);
      }
      break;
    default:
      context->ReportError(context, "Type '%s' not currently supported.",
                           TfLiteTypeGetName(input->type));
      return kTfLiteError;
  }
#undef TF_LITE_SPACE_TO_DEPTH

  return kTfLiteOk;
}

}  // namespace space_to_depth

TfLiteRegistration* Register_SPACE_TO_DEPTH_REF() {
  static TfLiteRegistration r = {
      nullptr, nullptr, space_to_depth::Prepare,
      space_to_depth::Eval<space_to_depth::kReference>};
  return &r;
}

TfLiteRegistration* Register_SPACE_TO_DEPTH_GENERIC_OPT() {
  static TfLiteRegistration r = {
      nullptr, nullptr, space_to_depth::Prepare,
      space_to_depth::Eval<space_to_depth::kGenericOptimized>};
  return &r;
}

TfLiteRegistration* Register_SPACE_TO_DEPTH() {
  return Register_SPACE_TO_DEPTH_GENERIC_OPT();
}

}  // namespace builtin
}  // namespace ops
}  // namespace tflite
<|endoftext|>


<commit_before>#include "ofApp.h"

//--------------------------------------------------------------
void ofApp::setup()
{
	ofSetLogLevel(OF_LOG_VERBOSE);
	ofSetLogLevel("ofThread", OF_LOG_ERROR);

	ofEnableAlphaBlending();

	doDrawInfo = true;

	targetWidth = 640;
	targetHeight = 480;
#if defined(TARGET_OPENGLES)
	consoleListener.setup(this);
	omxCameraSettings.width = targetWidth;
	omxCameraSettings.height = targetHeight;
	omxCameraSettings.framerate = 15;
	omxCameraSettings.enableTexture = true;

	videoGrabber.setup(omxCameraSettings);
	filterCollection.setup();
	ofSetVerticalSync(false);
#else
	videoGrabber.setDeviceID(0);
	videoGrabber.setDesiredFrameRate(30);
	videoGrabber.setup(targetWidth, targetHeight);
	ofSetVerticalSync(true);
#endif
	doShader = true;
	shader.load("shaderExample");

	fbo.allocate(targetWidth, targetHeight);
	fbo.begin();
	ofClear(0, 0, 0, 0);
	fbo.end();
	// selfberry
	colorGifEncoder.setup(targetWidth, targetHeight, .2, 256);
	ofAddListener(ofxGifEncoder::OFX_GIF_SAVE_FINISHED, this, &ofApp::onGifSaved);

	videoTexture.allocate(targetWidth, targetHeight, GL_RGB);

	bufferDir = "buffer";

	timeZero = ofGetElapsedTimeMicros();
	frameNumber = 0;
	slotRecording = 255;
	slotAmount = 4;
	if (dirSRC.doesDirectoryExist(bufferDir)) {
		dirSRC.removeDirectory(bufferDir, true);
	}
	if (!dirSRC.doesDirectoryExist("slot1")) {
		dirSRC.createDirectory("slot1");
	}
	if (!dirSRC.doesDirectoryExist("slot2")) {
		dirSRC.createDirectory("slot2");
	}
	if (!dirSRC.doesDirectoryExist("slot3")) {
		dirSRC.createDirectory("slot3");
	}
	if (!dirSRC.doesDirectoryExist("slot4")) {
		dirSRC.createDirectory("slot4");
	}
	if (!dirSRC.doesDirectoryExist("tmp")) {
		dirSRC.createDirectory("tmp");
	}
	dirSRC.createDirectory(bufferDir);
	indexSavedPhoto = 0;
	isRecording = false;
	amountOfFrames = 10;
	maxFrames = 10;
	if (settings.loadFile("settings.xml") == false) {
		ofLog() << "XML ERROR, possibly quit";
	}
	settings.pushTag("settings");

	/*if (settings.getValue("log", 1) == 0) {
		ofLogLevel(OF_LOG_SILENT);
	}
	fps = settings.getValue("fps", 15);
	maxFrames = settings.getValue("frameAmount", 15);
	bufferDir = settings.getValue("bufferDir", "buffer");
	outputDir = settings.getValue("outputDir", "output");
	if (settings.getValue("fullScreen", 0) == 1) {
		ofToggleFullscreen();
	}*/
	slotDir = "slot";
	for (int i = 0; i < settings.getNumTags("slot"); i++) {
		settings.pushTag("slot", i);
		videoGrid[i].init(settings.getValue("id", i), settings.getValue("x", 700), settings.getValue("y", 500), &slotDir, settings.getValue("key", 0));
		settings.popTag();
	}
	lastSpot = 0;
	currentDisplaySlot = 2;
	bkgLayer.loadImage("ui.png");
}

//--------------------------------------------------------------
void ofApp::update()
{
#if defined(TARGET_OPENGLES)

#else
	videoGrabber.update();
#endif
	if (!doShader )
	{
		ofLogNotice("update() !doShader return");
		return;
	}
	if (!videoGrabber.isFrameNew())
	{
		ofLogNotice("update() !videoGrabber.isFrameNew return");
		return;
	}
	//ofLogNotice("update() fbo begin");

	fbo.begin();
	ofClear(1, 1, 0, 0);
	shader.begin();
	shader.setUniform1f("time", ofGetElapsedTimef());
	shader.setUniform2f("resolution", ofGetWidth(), ofGetHeight());
#if defined(TARGET_OPENGLES)
	shader.setUniformTexture("tex0", videoGrabber.getTextureReference(), videoGrabber.getTextureID());
	videoGrabber.draw();
#else
	shader.setUniformTexture("tex0", videoGrabber.getTexture(), 0 );// 0 or 1?
	videoGrabber.draw(0, 0);
#endif
	shader.end();
	fbo.end();
	//ofLogNotice("update() fbo end");

	if (isRecording == true) {
		ofLogNotice("update() rec");

		dirSRC.createDirectory(bufferDir);
		dirSRC.listDir(bufferDir);
		recordedFramesAmount = dirSRC.size();
		ofLogNotice("AMOUNT OF FILES: " + ofToString(recordedFramesAmount) + "/" + ofToString(maxFrames));
		if (recordedFramesAmount == maxFrames) {
			isRecording = false;
			indexSavedPhoto = 0;
			ofLogNotice("update() stop recording");
		}
		else {
			if (videoGrabber.isFrameNew()) {
				ofLogNotice("update() isFrameNew");

				string filename;
				if (indexSavedPhoto < 10) filename = "seq00" + ofToString(indexSavedPhoto);
				if (indexSavedPhoto >= 10 && indexSavedPhoto < 100) filename = "seq0" + ofToString(indexSavedPhoto);
				if (indexSavedPhoto >= 100 && indexSavedPhoto < 1000) filename = "seq" + ofToString(indexSavedPhoto);
				// fbo to pixels
				fbo.readToPixels(pix);
				fbo.draw(0, 0, targetWidth, targetHeight);
				ofLogNotice("AMOUNT OF FILES: " + ofToString(recordedFramesAmount) + "/" + ofToString(maxFrames));

				//pix.resize(targetWidth, targetHeight, OF_INTERPOLATE_NEAREST_NEIGHBOR);
				savedImage.setFromPixels(pix);
				savedImage.setImageType(OF_IMAGE_COLOR);
				switch (currentDisplaySlot) {
				case 2:
					savedImage.saveImage("slot2//" + filename + ".tga");
					break;
				case 3:
					savedImage.saveImage("slot3//" + filename + ".tga");
					break;
				case 4:
					savedImage.saveImage("slot4//" + filename + ".tga");
					break;
				}
				savedImage.saveImage(bufferDir + "//" + filename + ".tga");
				//omxCameraSettings.width, omxCameraSettings.height
				// add frame to gif encoder
				colorGifEncoder.addFrame(
					pix.getPixels(),
					targetWidth,
					targetHeight,
					pix.getBitsPerPixel()/*,
										 .1f duration */
				);

				recordedFramesAmount++;
				pix.clear();
				savedImage.clear();
				indexSavedPhoto++;
				if (indexSavedPhoto == amountOfFrames) {
					ofLogNotice("Stop recording: " + ofToString(indexSavedPhoto) + "/" + ofToString(amountOfFrames));
					isRecording = false;
					indexSavedPhoto = 0;
					saveGif();
				}
			}
		}
	}
	for (i = 1; i < slotAmount; i++) {
		videoGrid[i].loadFrameNumber(frameNumber);
	}
	frameNumber++;
	if (frameNumber == maxFrames) {
		frameNumber = 0;
	}
}
void ofApp::saveGif()
{
	string fileName = ofToString(ofGetMonth()) + "-" + ofToString(ofGetDay()) + "-" + ofToString(ofGetHours()) + "-" + ofToString(ofGetMinutes()) + "-" + ofToString(ofGetSeconds());
	ofLogNotice("saveGif: " + fileName);
	colorGifEncoder.save("gif//" + fileName + ".gif");
	ofLogNotice("saveGif end");
}
void ofApp::onGifSaved(string & fileName) {
	cout << "gif saved as " << fileName << endl;
	ofLogNotice("onGifSaved: " + fileName);
	colorGifEncoder.reset();
	ofLogNotice("onGifSaved reset");
}
//--------------------------------------------------------------
void ofApp::draw() {

	ofClear(0, 0, 0, 0);
	stringstream info;
	info << "APP FPS: " << ofGetFrameRate() << "\n";
	info << "SHADER ENABLED: " << doShader << "\n";

	if (doShader)
	{
#if defined(TARGET_OPENGLES)
		fbo.draw(330, 13);
#else
		videoGrabber.draw(330, 13);
#endif
	}
	else
	{
#if defined(TARGET_OPENGLES)
		videoGrabber.draw();
		info << "Camera Resolution: " << videoGrabber.getWidth() << "x" << videoGrabber.getHeight() << " @ " << videoGrabber.getFrameRate() << "FPS" << "\n";
		info << "CURRENT FILTER: " << filterCollection.getCurrentFilterName() << "\n";
#else
		videoGrabber.draw(0, 0);
#endif
	}
	for (int i = 1; i < slotAmount; i++) {
		videoGrid[i].draw();
	}

	info << "\n";
	info << "VERT: changement de filtre" << "\n";
	info << "ROUGE: enregistrer" << "\n";
	bkgLayer.draw(0, 0);
	if (doDrawInfo)
	{
		ofDrawBitmapStringHighlight(info.str(), 50, 940, ofColor::black, ofColor::yellow);
	}
}

//--------------------------------------------------------------
void ofApp::keyPressed(int key)
{
	//ofLog(OF_LOG_VERBOSE, "%c keyPressed", key);
	ofLogNotice("PRESSED KEY: " + ofToString(key));
	/*RED 13 10
		WHITE 127 126
		YELLOW 54
		GREEN 357 65
		BLUE 50*/
	switch (key) {
	case 65:
	case 357:
#if defined(TARGET_OPENGLES)
		videoGrabber.setImageFilter(filterCollection.getNextFilter());
#endif
		break;
	case 10:
	case 13:
		if (!isRecording) {
			isRecording = true;
			indexSavedPhoto = 0;
			currentDisplaySlot++;
			if (currentDisplaySlot > 4) currentDisplaySlot = 2;
			bufferDir = ofToString(ofGetMonth()) + "-" + ofToString(ofGetDay()) + "-" + ofToString(ofGetHours()) + "-" + ofToString(ofGetMinutes()) + "-" + ofToString(ofGetSeconds());
		}
		break;
	case 126:
		doDrawInfo = !doDrawInfo;
		break;
	case 50:
	case 359:
		doShader = !doShader;
		break;
	}
}
#if defined(TARGET_OPENGLES)
void ofApp::onCharacterReceived(KeyListenerEventData& e)
{
	keyPressed((int)e.character);
}
#endif
<commit_msg>creation dossier gif<commit_after>#include "ofApp.h"

//--------------------------------------------------------------
void ofApp::setup()
{
	ofSetLogLevel(OF_LOG_VERBOSE);
	ofSetLogLevel("ofThread", OF_LOG_ERROR);

	ofEnableAlphaBlending();

	doDrawInfo = true;

	targetWidth = 640;
	targetHeight = 480;
#if defined(TARGET_OPENGLES)
	consoleListener.setup(this);
	omxCameraSettings.width = targetWidth;
	omxCameraSettings.height = targetHeight;
	omxCameraSettings.framerate = 15;
	omxCameraSettings.enableTexture = true;

	videoGrabber.setup(omxCameraSettings);
	filterCollection.setup();
	ofSetVerticalSync(false);
#else
	videoGrabber.setDeviceID(0);
	videoGrabber.setDesiredFrameRate(30);
	videoGrabber.setup(targetWidth, targetHeight);
	ofSetVerticalSync(true);
#endif
	doShader = true;
	shader.load("shaderExample");

	fbo.allocate(targetWidth, targetHeight);
	fbo.begin();
	ofClear(0, 0, 0, 0);
	fbo.end();
	// selfberry
	colorGifEncoder.setup(targetWidth, targetHeight, .2, 256);
	ofAddListener(ofxGifEncoder::OFX_GIF_SAVE_FINISHED, this, &ofApp::onGifSaved);

	videoTexture.allocate(targetWidth, targetHeight, GL_RGB);

	bufferDir = "buffer";

	timeZero = ofGetElapsedTimeMicros();
	frameNumber = 0;
	slotRecording = 255;
	slotAmount = 4;
	if (dirSRC.doesDirectoryExist(bufferDir)) {
		dirSRC.removeDirectory(bufferDir, true);
	}
	if (!dirSRC.doesDirectoryExist("slot1")) {
		dirSRC.createDirectory("slot1");
	}
	if (!dirSRC.doesDirectoryExist("slot2")) {
		dirSRC.createDirectory("slot2");
	}
	if (!dirSRC.doesDirectoryExist("slot3")) {
		dirSRC.createDirectory("slot3");
	}
	if (!dirSRC.doesDirectoryExist("slot4")) {
		dirSRC.createDirectory("slot4");
	}
	if (!dirSRC.doesDirectoryExist("tmp")) {
		dirSRC.createDirectory("tmp");
	}
	if (!dirSRC.doesDirectoryExist("gif")) {
		dirSRC.createDirectory("gif");
	}
	dirSRC.createDirectory(bufferDir);
	indexSavedPhoto = 0;
	isRecording = false;
	amountOfFrames = 10;
	maxFrames = 10;
	if (settings.loadFile("settings.xml") == false) {
		ofLog() << "XML ERROR, possibly quit";
	}
	settings.pushTag("settings");

	/*if (settings.getValue("log", 1) == 0) {
		ofLogLevel(OF_LOG_SILENT);
	}
	fps = settings.getValue("fps", 15);
	maxFrames = settings.getValue("frameAmount", 15);
	bufferDir = settings.getValue("bufferDir", "buffer");
	outputDir = settings.getValue("outputDir", "output");
	if (settings.getValue("fullScreen", 0) == 1) {
		ofToggleFullscreen();
	}*/
	slotDir = "slot";
	for (int i = 0; i < settings.getNumTags("slot"); i++) {
		settings.pushTag("slot", i);
		videoGrid[i].init(settings.getValue("id", i), settings.getValue("x", 700), settings.getValue("y", 500), &slotDir, settings.getValue("key", 0));
		settings.popTag();
	}
	lastSpot = 0;
	currentDisplaySlot = 2;
	bkgLayer.loadImage("ui.png");
}

//--------------------------------------------------------------
void ofApp::update()
{
#if defined(TARGET_OPENGLES)

#else
	videoGrabber.update();
#endif
	if (!doShader )
	{
		ofLogNotice("update() !doShader return");
		return;
	}
	if (!videoGrabber.isFrameNew())
	{
		ofLogNotice("update() !videoGrabber.isFrameNew return");
		return;
	}
	//ofLogNotice("update() fbo begin");

	fbo.begin();
	ofClear(1, 1, 0, 0);
	shader.begin();
	shader.setUniform1f("time", ofGetElapsedTimef());
	shader.setUniform2f("resolution", ofGetWidth(), ofGetHeight());
#if defined(TARGET_OPENGLES)
	shader.setUniformTexture("tex0", videoGrabber.getTextureReference(), videoGrabber.getTextureID());
	videoGrabber.draw();
#else
	shader.setUniformTexture("tex0", videoGrabber.getTexture(), 0 );// 0 or 1?
	videoGrabber.draw(0, 0);
#endif
	shader.end();
	fbo.end();
	//ofLogNotice("update() fbo end");

	if (isRecording == true) {
		ofLogNotice("update() rec");

		dirSRC.createDirectory(bufferDir);
		dirSRC.listDir(bufferDir);
		recordedFramesAmount = dirSRC.size();
		ofLogNotice("AMOUNT OF FILES: " + ofToString(recordedFramesAmount) + "/" + ofToString(maxFrames));
		if (recordedFramesAmount == maxFrames) {
			isRecording = false;
			indexSavedPhoto = 0;
			ofLogNotice("update() stop recording");
		}
		else {
			if (videoGrabber.isFrameNew()) {
				ofLogNotice("update() isFrameNew");

				string filename;
				if (indexSavedPhoto < 10) filename = "seq00" + ofToString(indexSavedPhoto);
				if (indexSavedPhoto >= 10 && indexSavedPhoto < 100) filename = "seq0" + ofToString(indexSavedPhoto);
				if (indexSavedPhoto >= 100 && indexSavedPhoto < 1000) filename = "seq" + ofToString(indexSavedPhoto);
				// fbo to pixels
				fbo.readToPixels(pix);
				fbo.draw(0, 0, targetWidth, targetHeight);
				ofLogNotice("AMOUNT OF FILES: " + ofToString(recordedFramesAmount) + "/" + ofToString(maxFrames));

				//pix.resize(targetWidth, targetHeight, OF_INTERPOLATE_NEAREST_NEIGHBOR);
				savedImage.setFromPixels(pix);
				savedImage.setImageType(OF_IMAGE_COLOR);
				switch (currentDisplaySlot) {
				case 2:
					savedImage.saveImage("slot2//" + filename + ".tga");
					break;
				case 3:
					savedImage.saveImage("slot3//" + filename + ".tga");
					break;
				case 4:
					savedImage.saveImage("slot4//" + filename + ".tga");
					break;
				}
				ofLogNotice("update() currentDisplaySlot " + ofToString(currentDisplaySlot));

				savedImage.saveImage(bufferDir + "//" + filename + ".tga");
				//omxCameraSettings.width, omxCameraSettings.height
				// add frame to gif encoder
				colorGifEncoder.addFrame(
					pix.getPixels(),
					targetWidth,
					targetHeight,
					pix.getBitsPerPixel()/*,
										 .1f duration */
				);

				recordedFramesAmount++;
				pix.clear();
				savedImage.clear();
				indexSavedPhoto++;
				if (indexSavedPhoto == amountOfFrames) {
					ofLogNotice("Stop recording: " + ofToString(indexSavedPhoto) + "/" + ofToString(amountOfFrames));
					isRecording = false;
					indexSavedPhoto = 0;
					saveGif();
				}
			}
		}
	}
	for (i = 1; i < slotAmount; i++) {
		videoGrid[i].loadFrameNumber(frameNumber);
	}
	frameNumber++;
	if (frameNumber == maxFrames) {
		frameNumber = 0;
	}
}
void ofApp::saveGif()
{
	string fileName = ofToString(ofGetMonth()) + "-" + ofToString(ofGetDay()) + "-" + ofToString(ofGetHours()) + "-" + ofToString(ofGetMinutes()) + "-" + ofToString(ofGetSeconds());
	ofLogNotice("saveGif: " + fileName);
	colorGifEncoder.save("gif//" + fileName + ".gif");
	ofLogNotice("saveGif end");
}
void ofApp::onGifSaved(string & fileName) {
	cout << "gif saved as " << fileName << endl;
	ofLogNotice("onGifSaved: " + fileName);
	colorGifEncoder.reset();
	ofLogNotice("onGifSaved reset");
}
//--------------------------------------------------------------
void ofApp::draw() {

	ofClear(0, 0, 0, 0);
	stringstream info;
	info << "APP FPS: " << ofGetFrameRate() << "\n";
	info << "SHADER ENABLED: " << doShader << "\n";

	if (doShader)
	{
#if defined(TARGET_OPENGLES)
		fbo.draw(330, 13);
#else
		videoGrabber.draw(330, 13);
#endif
	}
	else
	{
#if defined(TARGET_OPENGLES)
		videoGrabber.draw();
		info << "Camera Resolution: " << videoGrabber.getWidth() << "x" << videoGrabber.getHeight() << " @ " << videoGrabber.getFrameRate() << "FPS" << "\n";
		info << "CURRENT FILTER: " << filterCollection.getCurrentFilterName() << "\n";
#else
		videoGrabber.draw(0, 0);
#endif
	}
	for (int i = 1; i < slotAmount; i++) {
		videoGrid[i].draw();
	}

	info << "\n";
	info << "VERT: changement de filtre" << "\n";
	info << "ROUGE: enregistrer" << "\n";
	bkgLayer.draw(0, 0);
	if (doDrawInfo)
	{
		ofDrawBitmapStringHighlight(info.str(), 50, 940, ofColor::black, ofColor::yellow);
	}
}

//--------------------------------------------------------------
void ofApp::keyPressed(int key)
{
	//ofLog(OF_LOG_VERBOSE, "%c keyPressed", key);
	ofLogNotice("PRESSED KEY: " + ofToString(key));
	/*RED 13 10
		WHITE 127 126
		YELLOW 54
		GREEN 357 65
		BLUE 50*/
	switch (key) {
	case 65:
	case 357:
#if defined(TARGET_OPENGLES)
		videoGrabber.setImageFilter(filterCollection.getNextFilter());
#endif
		break;
	case 10:
	case 13:
		if (!isRecording) {
			isRecording = true;
			indexSavedPhoto = 0;
			currentDisplaySlot++;
			if (currentDisplaySlot > 4) currentDisplaySlot = 2;
			bufferDir = ofToString(ofGetMonth()) + "-" + ofToString(ofGetDay()) + "-" + ofToString(ofGetHours()) + "-" + ofToString(ofGetMinutes()) + "-" + ofToString(ofGetSeconds());
		}
		break;
	case 126:
		doDrawInfo = !doDrawInfo;
		break;
	case 50:
	case 359:
		doShader = !doShader;
		break;
	}
}
#if defined(TARGET_OPENGLES)
void ofApp::onCharacterReceived(KeyListenerEventData& e)
{
	keyPressed((int)e.character);
}
#endif
<|endoftext|>


<commit_before>#pragma once
//=====================================================================//
/*! @file
    @brief  イグナイター・アプリケーション・クラス
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2017, 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "main.hpp"
#include "core/glcore.hpp"
#include "utils/i_scene.hpp"
#include "utils/director.hpp"
#include "widgets/widget.hpp"
#include "widgets/widget_frame.hpp"
#include "widgets/widget_null.hpp"
#include "widgets/widget_button.hpp"
#include "widgets/widget_filer.hpp"
#include "widgets/widget_terminal.hpp"
#include "widgets/widget_list.hpp"
#include "widgets/widget_view.hpp"
#include "widgets/widget_utils.hpp"

#include "interlock.hpp"
#include "root_menu.hpp"
#include "ign_client_tcp.hpp"

namespace app {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  Ignitor アプリケーション・クラス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	class ignitor : public utils::i_scene {

		utils::director<core>&	director_;

		interlock				interlock_;
		root_menu				root_menu_;

///		asio::io_service		io_service_;
		net::ign_client_tcp		client_;
		uint32_t				delay_client_;
		bool					connect_client_;
		bool					start_client_;

		std::string				ip_;

		uint32_t				exit_loop_;

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief  コンストラクター
		*/
		//-----------------------------------------------------------------//
		ignitor(utils::director<core>& d) : director_(d),
			interlock_(),
			root_menu_(d, client_, interlock_),
///			io_service_(),
///			client_(io_service_),
			client_(),
			delay_client_(60), connect_client_(false), start_client_(false),
			ip_(), exit_loop_(60)
		{ }

		//-----------------------------------------------------------------//
		/*!
			@brief  初期化
		*/
		//-----------------------------------------------------------------//
		void initialize()
		{
			root_menu_.initialize();
#if 0
			director_.at().exit_func_ = [=]() {
				std::cout << "Recive EXIT" << std::endl;
				if(exit_loop_ > 0) {
					--exit_loop_;
				}
				return exit_loop_ == 0;
			};
#endif
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  アップデート
		*/
		//-----------------------------------------------------------------//
		void update()
		{
			root_menu_.update();

			gui::widget_director& wd = director_.at().widget_director_;

			if(start_client_) {
				if(client_.probe()) {
					client_.service();
				}
			} else {
				bool cn = root_menu_.get_target_connect();
				if(!connect_client_ && cn) {  // 接続が有効になった
					connect_client_ = cn;
					delay_client_ = 60;
				}
				if(delay_client_ > 0) {
					--delay_client_;
					if(delay_client_ == 0) {
						auto ip = root_menu_.get_target_ip();
						if(!ip.empty() && ip_ != ip) {
							ip_ = ip;
							client_.start(ip_, 23);
							start_client_ = true;
						}
					}
				}
			}

///			io_service_.run();

#if 0
#if 0
			// Drag & Drop されたファイル
			gl::core& core = gl::core::get_instance();
			int id = core.get_recv_files_id();
			if(drop_file_id_ != id) {
				drop_file_id_ = id;
				const utils::strings& ss = core.get_recv_files_path();
				if(!ss.empty()) {
					std::string path = ss[0];
					if(load_ctx_ != nullptr && load_ctx_->get_local_param().select_file_func_ != nullptr) {
						load_ctx_->get_local_param().select_file_func_(path);
					}
				}
			}
#endif
#endif
			wd.update();
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  レンダリング
		*/
		//-----------------------------------------------------------------//
		void render()
		{
			director_.at().widget_director_.service();
			director_.at().widget_director_.render();
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	廃棄
		*/
		//-----------------------------------------------------------------//
		void destroy() { }
	};
}
<commit_msg>update: kikusui manage<commit_after>#pragma once
//=====================================================================//
/*! @file
    @brief  イグナイター・アプリケーション・クラス
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2017, 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "main.hpp"
#include "core/glcore.hpp"
#include "utils/i_scene.hpp"
#include "utils/director.hpp"
#include "widgets/widget.hpp"
#include "widgets/widget_frame.hpp"
#include "widgets/widget_null.hpp"
#include "widgets/widget_button.hpp"
#include "widgets/widget_filer.hpp"
#include "widgets/widget_terminal.hpp"
#include "widgets/widget_list.hpp"
#include "widgets/widget_view.hpp"
#include "widgets/widget_utils.hpp"

#include "interlock.hpp"
#include "root_menu.hpp"
#include "ign_client_tcp.hpp"

namespace app {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  Ignitor アプリケーション・クラス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	class ignitor : public utils::i_scene {

		utils::director<core>&	director_;

		interlock				interlock_;
		root_menu				root_menu_;

///		asio::io_service		io_service_;
		net::ign_client_tcp		client_;
		uint32_t				delay_client_;
		bool					connect_client_;
		bool					start_client_;

		std::string				ip_;

		uint32_t				exit_loop_;
		bool					root_menu_exit_;

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief  コンストラクター
		*/
		//-----------------------------------------------------------------//
		ignitor(utils::director<core>& d) : director_(d),
			interlock_(),
			root_menu_(d, client_, interlock_),
///			io_service_(),
///			client_(io_service_),
			client_(),
			delay_client_(60), connect_client_(false), start_client_(false),
			ip_(), exit_loop_(60), root_menu_exit_(false)
		{ }

		//-----------------------------------------------------------------//
		/*!
			@brief  初期化
		*/
		//-----------------------------------------------------------------//
		void initialize()
		{
			root_menu_.initialize();

			director_.at().exit_func_ = [=]() {
				if(!root_menu_exit_) {
					root_menu_.exit();
					root_menu_exit_ = true;
				}
//				std::cout << "Recive EXIT" << std::endl;
				if(exit_loop_ > 0) {
					--exit_loop_;
				}
				return exit_loop_ == 0;
			};
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  アップデート
		*/
		//-----------------------------------------------------------------//
		void update()
		{
			root_menu_.update();

			gui::widget_director& wd = director_.at().widget_director_;

			if(start_client_) {
				if(client_.probe()) {
					client_.service();
				}
			} else {
				bool cn = root_menu_.get_target_connect();
				if(!connect_client_ && cn) {  // 接続が有効になった
					connect_client_ = cn;
					delay_client_ = 60;
				}
				if(delay_client_ > 0) {
					--delay_client_;
					if(delay_client_ == 0) {
						auto ip = root_menu_.get_target_ip();
						if(!ip.empty() && ip_ != ip) {
							ip_ = ip;
							client_.start(ip_, 23);
							start_client_ = true;
						}
					}
				}
			}

///			io_service_.run();

#if 0
#if 0
			// Drag & Drop されたファイル
			gl::core& core = gl::core::get_instance();
			int id = core.get_recv_files_id();
			if(drop_file_id_ != id) {
				drop_file_id_ = id;
				const utils::strings& ss = core.get_recv_files_path();
				if(!ss.empty()) {
					std::string path = ss[0];
					if(load_ctx_ != nullptr && load_ctx_->get_local_param().select_file_func_ != nullptr) {
						load_ctx_->get_local_param().select_file_func_(path);
					}
				}
			}
#endif
#endif
			wd.update();
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  レンダリング
		*/
		//-----------------------------------------------------------------//
		void render()
		{
			director_.at().widget_director_.service();
			director_.at().widget_director_.render();
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	廃棄
		*/
		//-----------------------------------------------------------------//
		void destroy() { }
	};
}
<|endoftext|>


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

#include "SettingsMVC.h"

SettingsMVC::SettingsMVC(){}

void SettingsMVC::init(ofTrueTypeFont font) {
	checkboxOscArray.init(font, "OSC array xysa", FONT_POSITION_X, 160);
	checkboxFrame.init(font, "Frame active", FONT_POSITION_X, 180);
	//checkboxTimestamp.init(vera, "timestamp active",  60, 170, defXmlPadTimestamp);
	checkboxPosition.init(font, "X-, Y-Position active", FONT_POSITION_X, 200);
	//checkboxVelocity.init(vera, "x-, y-velocity active", 60, 200, defXmlPadVelocity);
	//checkboxMaxis.init(vera, "minor-, major-axis active", 60, 215, defXmlPadMaxis);
	checkboxSize.init(font, "Size active", FONT_POSITION_X, 220);
	checkboxAngle.init(font, "Angle active", FONT_POSITION_X, 240);
}

void SettingsMVC::getXml(ofxXmlDefaultSettings xml) {
	/* OSC variables
	 */
	oscHost = xml.getAttribute("osc", "host", "127.0.0.1", 0);
	oscPort = xml.getAttribute("osc", "port", 12345, 0);

	/* Trackpad variables
	 */
	oscTouchpadDevicename = xml.getValue("pad:devicename", "mtpadosc");
	checkboxOscArray.status  = xml.getValue("pad:array", false, 0);
	//oscArrayActive = xml.getValue("pad:array", false, 0);
	checkboxFrame.status = xml.getValue("pad:frame", false, 0);
	//checkboxTimestamp.status = xml.getValue("pad:timestamp", false, 0);
	checkboxPosition.status = xml.getValue("pad:position", false, 0);
	//checkboxVelocity.status = xml.getValue("pad:velocity", false, 0);
	checkboxSize.status = xml.getValue("pad:size", false, 0);
	//checkboxMaxis.status = xml.getValue("pad:maxis", false, 0);
	checkboxAngle.status = xml.getValue("pad:angle", false, 0);
}

void SettingsMVC::addXml(ofxXmlDefaultSettings xml) {
	/* OSC variables
	 */
	oscHost = "127.0.0.1";
	oscPort = 12345;
	xml.addAttribute("osc", "host", oscHost, 0);
	xml.addAttribute("osc", "post", oscPort, 0);

	/* Trackpad variables
	 */
	oscTouchpadDevicename = "mtpad";

 	checkboxOscArray.status = false;
	checkboxFrame.status = false;
	//checkboxTimestamp.status = false;
	checkboxPosition.status = true;
	//checkboxVelocity.status = false;
	checkboxSize.status = true;
	//checkboxMaxis.status = false;
	checkboxAngle.status = true;
	xml.addTag("pad");
	xml.pushTag("pad", 0);
	xml.addValue("devicename", oscTouchpadDevicename);
	xml.addValue("array", checkboxOscArray.status);
	xml.addValue("frame", checkboxFrame.status);
	//xml.addValue("timestamp", checkboxTimestamp.status);
	xml.addValue("position", checkboxPosition.status);
	//xml.addValue("velocity", checkboxVelocity.status);
	xml.addValue("size", checkboxSize.status);
	//xml.addValue("maxis", checkboxMaxis.status);
	xml.addValue("angle", checkboxAngle.status);
	xml.popTag();
}

void SettingsMVC::setXml(ofxXmlDefaultSettings xml) {
	xml.pushRoot();

	xml.setAttribute("osc", "host", oscHost, 0);
	xml.setAttribute("osc", "port", oscPort, 0);

	xml.setValue("pad:devicename", oscTouchpadDevicename, 0);
	xml.setValue("pad:array", checkboxOscArray.status, 0);
	xml.setValue("pad:frame", checkboxFrame.status, 0);
	//xml.setValue("pad:timestamp", checkboxTimestamp.status, 0);
	xml.setValue("pad:position", checkboxPosition.status, 0);
	//xml.setValue("pad:velocity", checkboxVelocity.status, 0);
	xml.setValue("pad:size", checkboxSize.status, 0);
	//xml.setValue("pad:maxis", checkboxMaxis.status, 0);
	xml.setValue("pad:angle", checkboxAngle.status, 0);

	xml.popRoot();
}

void SettingsMVC::log(){
	ofLog() << "XML: osc:host        = " << oscHost;
	ofLog() << "XML: osc:port        = " << oscPort;

	ofLog() << "pad:devicename  = " << oscTouchpadDevicename;
	ofLog() << "pad:array       = " << checkboxOscArray.status;
	ofLog() << "pad:frame       = " << checkboxFrame.status;
	//ofLog() << "pad:timestamp   = " << checkboxTimestamp.status;
	ofLog() << "pad:position    = " << checkboxPosition.status;
	//ofLog() << "pad:velocity    = " << checkboxVelocity.status;
	ofLog() << "pad:size        = " << checkboxSize.status;
	//ofLog() << "pad:maxis       = " << checkboxMaxis.status;
	ofLog() << "pad:angle       = " << checkboxAngle.status;
}

void SettingsMVC::draw(ofTrueTypeFont font, ofxMultiTouchPad & pad) {
	/* ground
	 */
	ofEnableAlphaBlending();
	ofSetColor(0, 150);
	ofFill();
	ofRect(10, 30, ofGetWidth()-20, ofGetHeight()-40);
	ofDisableAlphaBlending();

	ofSetColor(COLOR_LIGHT_GREY);
	ofFill();

	/* Osc Main Settings
	 */
	font.drawString("OSC Main Settings", FONT_POSITION_X, 50);
	ofLine(FONT_POSITION_X, 60, ofGetWidth()-FONT_POSITION_X, 60);
	// Host: xxx.xxx.xxx.xxx Port: xxxx, Devicename
	font.drawString("Host: ", FONT_POSITION_X, 80);
	font.drawString("Port: ", 190, 80);
	font.drawString("Devicename: ", FONT_POSITION_X, 100);

	/* OSC Message Settings
	 */
	font.drawString("OSC Message Settings", FONT_POSITION_X, 140);
	ofLine(FONT_POSITION_X, 150, ofGetWidth()-FONT_POSITION_X, 150);
	checkboxOscArray.display();
	checkboxFrame.display();
	//cbTimestamp.display();
	checkboxPosition.display();
	//cbVelocity.display();
	//cbMaxis.display();
	checkboxSize.display();
	checkboxAngle.display();
	// shortcuts
	font.drawString("'cmd a'", 190, 170);
	font.drawString("'cmd s'", 190, 190);
	font.drawString("'cmd d'", 190, 210);
	font.drawString("'cmd f'", 190, 230);
	font.drawString("'cmd g'", 190, 250);

	/* Settings information
	 */
	font.drawString("Settings Information", FONT_POSITION_X, 290);
	ofLine(FONT_POSITION_X, 300, ofGetWidth()-FONT_POSITION_X, 300);
	font.drawString("Number of Touchpoints: "+ofToString(pad.getTouchCount()), 15, 320);
	font.drawString("Number of Devices: "+ofToString(pad.getNumDevices()), 15, 340);
	font.drawString("To open the settings xml, press key 'cmd x'", FONT_POSITION_X, 380);
}

void SettingsMVC::mousePressed(int x, int y) {
	cout << "ViewerSettings mousePressed()";
	/* Check boxes
	 */
	checkboxOscArray.pressed(x, y);
	checkboxFrame.pressed(x, y);
	//cbTimestamp.pressed(x, y);
	checkboxPosition.pressed(x, y);
	//cbVelocity.pressed(x, y);
	//cbMaxis.pressed(x, y);
	checkboxSize.pressed(x, y);
	checkboxAngle.pressed(x, y);
}

void SettingsMVC::keyPressed(int key, bool cmdKeyPressed) {
	if (cmdKeyPressed == true) {

		switch (key) {
			/* OSC array
			 */
			case 'a':
				checkboxOscArray.status = !checkboxOscArray.status;
				break;

			/* OSC frame
			 */
			case 's':
				checkboxFrame.status = !checkboxFrame.status;
				// TODO:
				//console.addString("Shortcut padFrame: " + ofToString(xmlPadFrame), true);
				break;

			/* OSC timestamp
			 */
			/*case '3':
				if (settings.padTimestamp == 0) {
					settings.padTimestamp = 1;
				} else {
					settings.padTimestamp = 0;
				}
				cbTimestamp.status = settings.padTimestamp;
				cout << "Shortcut padTimestamp: " << settings.padTimestamp << endl;
				break;*/

			/* OSC position
			 */
			case 'd':
				checkboxPosition.status = !checkboxPosition.status;
				// TODO:
				//console.addString("Shortcut padPosition: " + ofToString(xmlPadPosition), true);
				break;

			/* OSC velocity
			 */
			/*case '5':
				if (settings.padVelocity == 0) {
					settings.padVelocity = 1;
				} else {
					settings.padVelocity = 0;
				}
				cbVelocity.status = settings.padVelocity;
				cout << "Shortcut padVelocity: " << settings.padVelocity << endl;
				break;*/

			/* OSC maxis
			 */
			/*case '4':
				if (settings.padMaxis == 0) {
					settings.padMaxis = 1;
				} else {
					settings.padMaxis = 0;
				}
				cbMaxis.status = settings.padMaxis;
				cout << "Shortcut padMaxis: " << settings.padMaxis << endl;
				break;*/

			/* OSC maxis
			 */
			case 'f':
				checkboxSize.status = !checkboxSize.status;
				// TODO:
				//console.addString("Shortcut padSize: " + ofToString(xmlPadSize), true);
				break;

			/* OSC angle
			 */
			case 'g':
				checkboxAngle.status = !checkboxAngle.status;
				// TODO:
				//console.addString("Shortcut padAngle: " + ofToString(xmlPadAngle), true);
				break;

			default:
				break;
		}

	} // End if cmdKeyPressed
}
<commit_msg>uncomment console out at mousePressed<commit_after>//
// SettingsMVC.cpp
// MultitouchPadOsc is released under the MIT License.
//
// Copyright (c) 2011 - 2012, Paul Vollmer http://www.wrong-entertainment.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

#include "SettingsMVC.h"

SettingsMVC::SettingsMVC(){}

void SettingsMVC::init(ofTrueTypeFont font) {
	checkboxOscArray.init(font, "OSC array xysa", FONT_POSITION_X, 160);
	checkboxFrame.init(font, "Frame active", FONT_POSITION_X, 180);
	//checkboxTimestamp.init(vera, "timestamp active",  60, 170, defXmlPadTimestamp);
	checkboxPosition.init(font, "X-, Y-Position active", FONT_POSITION_X, 200);
	//checkboxVelocity.init(vera, "x-, y-velocity active", 60, 200, defXmlPadVelocity);
	//checkboxMaxis.init(vera, "minor-, major-axis active", 60, 215, defXmlPadMaxis);
	checkboxSize.init(font, "Size active", FONT_POSITION_X, 220);
	checkboxAngle.init(font, "Angle active", FONT_POSITION_X, 240);
}

void SettingsMVC::getXml(ofxXmlDefaultSettings xml) {
	/* OSC variables
	 */
	oscHost = xml.getAttribute("osc", "host", "127.0.0.1", 0);
	oscPort = xml.getAttribute("osc", "port", 12345, 0);

	/* Trackpad variables
	 */
	oscTouchpadDevicename = xml.getValue("pad:devicename", "mtpadosc");
	checkboxOscArray.status  = xml.getValue("pad:array", false, 0);
	//oscArrayActive = xml.getValue("pad:array", false, 0);
	checkboxFrame.status = xml.getValue("pad:frame", false, 0);
	//checkboxTimestamp.status = xml.getValue("pad:timestamp", false, 0);
	checkboxPosition.status = xml.getValue("pad:position", false, 0);
	//checkboxVelocity.status = xml.getValue("pad:velocity", false, 0);
	checkboxSize.status = xml.getValue("pad:size", false, 0);
	//checkboxMaxis.status = xml.getValue("pad:maxis", false, 0);
	checkboxAngle.status = xml.getValue("pad:angle", false, 0);
}

void SettingsMVC::addXml(ofxXmlDefaultSettings xml) {
	/* OSC variables
	 */
	oscHost = "127.0.0.1";
	oscPort = 12345;
	xml.addAttribute("osc", "host", oscHost, 0);
	xml.addAttribute("osc", "post", oscPort, 0);

	/* Trackpad variables
	 */
	oscTouchpadDevicename = "mtpad";

 	checkboxOscArray.status = false;
	checkboxFrame.status = false;
	//checkboxTimestamp.status = false;
	checkboxPosition.status = true;
	//checkboxVelocity.status = false;
	checkboxSize.status = true;
	//checkboxMaxis.status = false;
	checkboxAngle.status = true;
	xml.addTag("pad");
	xml.pushTag("pad", 0);
	xml.addValue("devicename", oscTouchpadDevicename);
	xml.addValue("array", checkboxOscArray.status);
	xml.addValue("frame", checkboxFrame.status);
	//xml.addValue("timestamp", checkboxTimestamp.status);
	xml.addValue("position", checkboxPosition.status);
	//xml.addValue("velocity", checkboxVelocity.status);
	xml.addValue("size", checkboxSize.status);
	//xml.addValue("maxis", checkboxMaxis.status);
	xml.addValue("angle", checkboxAngle.status);
	xml.popTag();
}

void SettingsMVC::setXml(ofxXmlDefaultSettings xml) {
	xml.pushRoot();

	xml.setAttribute("osc", "host", oscHost, 0);
	xml.setAttribute("osc", "port", oscPort, 0);

	xml.setValue("pad:devicename", oscTouchpadDevicename, 0);
	xml.setValue("pad:array", checkboxOscArray.status, 0);
	xml.setValue("pad:frame", checkboxFrame.status, 0);
	//xml.setValue("pad:timestamp", checkboxTimestamp.status, 0);
	xml.setValue("pad:position", checkboxPosition.status, 0);
	//xml.setValue("pad:velocity", checkboxVelocity.status, 0);
	xml.setValue("pad:size", checkboxSize.status, 0);
	//xml.setValue("pad:maxis", checkboxMaxis.status, 0);
	xml.setValue("pad:angle", checkboxAngle.status, 0);

	xml.popRoot();
}

void SettingsMVC::log(){
	ofLog() << "XML: osc:host        = " << oscHost;
	ofLog() << "XML: osc:port        = " << oscPort;

	ofLog() << "pad:devicename  = " << oscTouchpadDevicename;
	ofLog() << "pad:array       = " << checkboxOscArray.status;
	ofLog() << "pad:frame       = " << checkboxFrame.status;
	//ofLog() << "pad:timestamp   = " << checkboxTimestamp.status;
	ofLog() << "pad:position    = " << checkboxPosition.status;
	//ofLog() << "pad:velocity    = " << checkboxVelocity.status;
	ofLog() << "pad:size        = " << checkboxSize.status;
	//ofLog() << "pad:maxis       = " << checkboxMaxis.status;
	ofLog() << "pad:angle       = " << checkboxAngle.status;
}

void SettingsMVC::draw(ofTrueTypeFont font, ofxMultiTouchPad & pad) {
	/* ground
	 */
	ofEnableAlphaBlending();
	ofSetColor(0, 150);
	ofFill();
	ofRect(10, 30, ofGetWidth()-20, ofGetHeight()-40);
	ofDisableAlphaBlending();

	ofSetColor(COLOR_LIGHT_GREY);
	ofFill();

	/* Osc Main Settings
	 */
	font.drawString("OSC Main Settings", FONT_POSITION_X, 50);
	ofLine(FONT_POSITION_X, 60, ofGetWidth()-FONT_POSITION_X, 60);
	// Host: xxx.xxx.xxx.xxx Port: xxxx, Devicename
	font.drawString("Host: ", FONT_POSITION_X, 80);
	font.drawString("Port: ", 190, 80);
	font.drawString("Devicename: ", FONT_POSITION_X, 100);

	/* OSC Message Settings
	 */
	font.drawString("OSC Message Settings", FONT_POSITION_X, 140);
	ofLine(FONT_POSITION_X, 150, ofGetWidth()-FONT_POSITION_X, 150);
	checkboxOscArray.display();
	checkboxFrame.display();
	//cbTimestamp.display();
	checkboxPosition.display();
	//cbVelocity.display();
	//cbMaxis.display();
	checkboxSize.display();
	checkboxAngle.display();
	// shortcuts
	font.drawString("'cmd a'", 190, 170);
	font.drawString("'cmd s'", 190, 190);
	font.drawString("'cmd d'", 190, 210);
	font.drawString("'cmd f'", 190, 230);
	font.drawString("'cmd g'", 190, 250);

	/* Settings information
	 */
	font.drawString("Settings Information", FONT_POSITION_X, 290);
	ofLine(FONT_POSITION_X, 300, ofGetWidth()-FONT_POSITION_X, 300);
	font.drawString("Number of Touchpoints: "+ofToString(pad.getTouchCount()), 15, 320);
	font.drawString("Number of Devices: "+ofToString(pad.getNumDevices()), 15, 340);
	font.drawString("To open the settings xml, press key 'cmd x'", FONT_POSITION_X, 380);
}

void SettingsMVC::mousePressed(int x, int y) {
	//cout << "ViewerSettings mousePressed()" << endl;
	/* Check boxes
	 */
	checkboxOscArray.pressed(x, y);
	checkboxFrame.pressed(x, y);
	//cbTimestamp.pressed(x, y);
	checkboxPosition.pressed(x, y);
	//cbVelocity.pressed(x, y);
	//cbMaxis.pressed(x, y);
	checkboxSize.pressed(x, y);
	checkboxAngle.pressed(x, y);
}

void SettingsMVC::keyPressed(int key, bool cmdKeyPressed) {
	if (cmdKeyPressed == true) {

		switch (key) {
			/* OSC array
			 */
			case 'a':
				checkboxOscArray.status = !checkboxOscArray.status;
				break;

			/* OSC frame
			 */
			case 's':
				checkboxFrame.status = !checkboxFrame.status;
				// TODO:
				//console.addString("Shortcut padFrame: " + ofToString(xmlPadFrame), true);
				break;

			/* OSC timestamp
			 */
			/*case '3':
				if (settings.padTimestamp == 0) {
					settings.padTimestamp = 1;
				} else {
					settings.padTimestamp = 0;
				}
				cbTimestamp.status = settings.padTimestamp;
				cout << "Shortcut padTimestamp: " << settings.padTimestamp << endl;
				break;*/

			/* OSC position
			 */
			case 'd':
				checkboxPosition.status = !checkboxPosition.status;
				// TODO:
				//console.addString("Shortcut padPosition: " + ofToString(xmlPadPosition), true);
				break;

			/* OSC velocity
			 */
			/*case '5':
				if (settings.padVelocity == 0) {
					settings.padVelocity = 1;
				} else {
					settings.padVelocity = 0;
				}
				cbVelocity.status = settings.padVelocity;
				cout << "Shortcut padVelocity: " << settings.padVelocity << endl;
				break;*/

			/* OSC maxis
			 */
			/*case '4':
				if (settings.padMaxis == 0) {
					settings.padMaxis = 1;
				} else {
					settings.padMaxis = 0;
				}
				cbMaxis.status = settings.padMaxis;
				cout << "Shortcut padMaxis: " << settings.padMaxis << endl;
				break;*/

			/* OSC maxis
			 */
			case 'f':
				checkboxSize.status = !checkboxSize.status;
				// TODO:
				//console.addString("Shortcut padSize: " + ofToString(xmlPadSize), true);
				break;

			/* OSC angle
			 */
			case 'g':
				checkboxAngle.status = !checkboxAngle.status;
				// TODO:
				//console.addString("Shortcut padAngle: " + ofToString(xmlPadAngle), true);
				break;

			default:
				break;
		}

	} // End if cmdKeyPressed
}
<|endoftext|>