This commit is contained in:
2025-05-13 02:46:21 +03:00
parent 143e16692e
commit 86914b7fcc
610 changed files with 92343 additions and 2 deletions
View File
+70
View File
@@ -0,0 +1,70 @@
// LifeAudioPlayer.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <SoundSystem.h>
#include <ISound.h>
#include <vfs/IFileSystem.h>
#include <vfs/RootFolder.h>
#include <vfs/fs_win/IFSContentProvider.h>
#include <vfs/pak/IPakFileContentProvider.h>
#include <LString.h>
#include <vfs/WinFileStream.h>
int _tmain(int argc, _TCHAR* argv[])
{
ResourceManager::me()->SetCentralDirectory(STR("C:\\development\\Programming\\Projects\\Data\\"));
/*Core::IFile* txt = fileSystem->GetFile(STR("root/Data/TEST.txt"));
Core::IDataStreamPtr stm1 = txt->OpenRead();
Core::IDataStreamPtr stm2 = txt->OpenRead();
stm1->Seek(1);
stm2->Seek(1);
char c1;
char c2;
stm1->Read(&c1, 1);
stm2->Read(&c2, 1);
printf("Stm1: %c; Stm2:%c\n", c1, c2);
*/
//fileSystem->CreateFolder(STR("root/Data/OLOLO12345"));
fileSystem->NewFile(STR("root/Data/Sounds/ololo.wav"), 1024*1024*3);
//Test(fileSystem);
printf("File system ready!\n");
Sound::SoundSystem* sndSystem;
sndSystem = new Sound::SoundSystem();
if(sndSystem->Init(fileSystem) != 0)
{
printf("Error initializing sound system!");
return -1;
}
printf("Sound system ready!\n");
Sound::ISound* snd = sndSystem->getSound(STR("root/Data/Sounds/Wwise_Nor_Music.015.ogg"), Sound::SM_ENABLED);
snd->Play();
//Sound::ISound* snd2 = sndSystem->getSound(STR("Wwise_Nor_Music.003.ogg"), Sound::SM_ENABLED);
//snd2->Play();
while(true)
{
sndSystem->Update();
}
printf("Press Enter key to exit\n");
getchar();
delete snd;
delete sndSystem;
return 0;
}
+171
View File
@@ -0,0 +1,171 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{4F307D56-E0CB-442C-8E76-FB3C827D54BF}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>LifeAudioPlayer</RootNamespace>
<SccProjectName>&lt;Project Location In Database&gt;</SccProjectName>
<SccAuxPath>&lt;Source Control Database&gt;</SccAuxPath>
<SccLocalPath>&lt;Local Binding Root of Project&gt;</SccLocalPath>
<SccProvider>Mercurial Source Control Package</SccProvider>
<VCTargetsPath Condition="'$(VCTargetsPath11)' != '' and '$(VSVersion)' == '' and $(VisualStudioVersion) == ''">$(VCTargetsPath11)</VCTargetsPath>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v120</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v120</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v120</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v120</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\Program Files %28x86%29\Visual Leak Detector\include;$(SolutionDir)\LifeCore\include;$(SolutionDir)\LifeSound\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalLibraryDirectories>C:\Program Files %28x86%29\Visual Leak Detector\lib;$(SolutionDir)\LifeCore\lib;$(SolutionDir)\LifeSound\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalDependencies>LifeCore_d.lib;LifeSound_d.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\Program Files %28x86%29\Visual Leak Detector\include;$(SolutionDir)\LifeCore\include;$(SolutionDir)\LifeSound\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalLibraryDirectories>C:\Program Files %28x86%29\Visual Leak Detector\lib;$(SolutionDir)\LifeCore\lib;$(SolutionDir)\LifeSound\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalDependencies>LifeCore_d.lib;LifeSound_d.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>$(SolutionDir)\LifeCore\include;$(SolutionDir)\LifeSound\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalLibraryDirectories>$(SolutionDir)\LifeCore\lib;$(SolutionDir)\LifeSound\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalDependencies>LifeCore.lib;LifeSound.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>$(SolutionDir)\LifeCore\include;$(SolutionDir)\LifeSound\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalLibraryDirectories>$(SolutionDir)\LifeCore\lib;$(SolutionDir)\LifeSound\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalDependencies>LifeCore.lib;LifeSound.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="stdafx.h" />
<ClInclude Include="targetver.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="LifeAudioPlayer.cpp" />
<ClCompile Include="stdafx.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
+8
View File
@@ -0,0 +1,8 @@
// stdafx.cpp : source file that includes just the standard includes
// LifeAudioPlayer.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
+13
View File
@@ -0,0 +1,13 @@
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
// TODO: reference additional headers your program requires here
+8
View File
@@ -0,0 +1,8 @@
#pragma once
// Including SDKDDKVer.h defines the highest available Windows platform.
// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and
// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h.
#include <SDKDDKVer.h>
View File
+18
View File
@@ -0,0 +1,18 @@
#ifndef Array_h__
#define Array_h__
namespace LifeCore
{
template<typename T>
class Array
{
public:
Array(size_t capacity);
~Array();
T& operator[](size_t id) const;
size_t Write(const T* src, size_t count);
private:
T* data;
};
}
#endif // Array_h__
+11
View File
@@ -0,0 +1,11 @@
#ifndef Axis_h__
#define Axis_h__
namespace LifeCore{
enum Axis{
AXIS_X,
AXIS_Y,
AXIS_Z
};
}
#endif // Axis_h__
+170
View File
@@ -0,0 +1,170 @@
#ifndef BoundingBox3D_h__
#define BoundingBox3D_h__
#include "math/LifeMath.h"
namespace LifeCore
{
#undef INLINE
#ifdef _WIN32
#ifdef _MSC_VER
#define INLINE __forceinline
#endif
#else
#ifdef __GNUC__
#define INLINE __attribute__((always_inline))
#endif
#endif
#ifndef INLINE
#define INLINE inline
#endif
enum ContainmentType
{
Disjoint = 0,
Contains = 1,
Intersects = 2
};
class BoundingBox3D
{
public:
BoundingBox3D()
{
vMin = LifeMath::float3(1000000000, 1000000000, 1000000000);
vMax = LifeMath::float3(-1000000000, -1000000000, -1000000000);
}
INLINE BoundingBox3D& operator=(const BoundingBox3D& other)
{
vMin = other.minimum();
vMax = other.maximum();
return *this;
}
BoundingBox3D(float size)
{
float offset = size/2.0f;
vMin = LifeMath::float3(-offset, -offset, -offset);
vMax = LifeMath::float3(offset, offset, offset);
}
BoundingBox3D(LifeMath::float3& minPoint, LifeMath::float3& maxPoint)
{
vMin = minPoint;
vMax = maxPoint;
}
BoundingBox3D(LifeMath::float4& minPoint, LifeMath::float4& maxPoint)
{
vMin = LifeMath::float3(minPoint.X, minPoint.Y, minPoint.Z);
vMax = LifeMath::float3(maxPoint.X, maxPoint.Y, maxPoint.Z);
}
const LifeMath::float3 maximum() const
{
return vMax;
}
LifeMath::float3 size() const
{
return vMax - vMin;
}
const LifeMath::float3 minimum() const
{
return vMin;
}
void resize(const LifeMath::float3& min, const LifeMath::float3& max)
{
vMin = min;
vMax = max;
}
float sizeX() const
{
return vMax.X - vMin.X;
}
float sizeY() const
{
return vMax.Y - vMin.Y;
}
float sizeZ() const
{
return vMax.Z - vMin.Z;
}
~BoundingBox3D()
{
}
void Merge(BoundingBox3D& box)
{
Vec3Maximize(this->vMax, box.maximum(), this->vMax);
Vec3Minimize(this->vMin, box.minimum(), this->vMin);
}
BoundingBox3D Clone()
{
return BoundingBox3D(vMin, vMax);
}
static BoundingBox3D FromPoints(LifeMath::float4* points, int count)
{
LifeMath::float4 min = points[0];
LifeMath::float4 max = min;
for (int i = 0; i < count; i++)
{
Vec4Minimize(min, points[i], min);
Vec4Maximize(max, points[i], max);
}
return BoundingBox3D(min, max);
}
static BoundingBox3D FromPoints(LifeMath::float3* points, int count)
{
LifeMath::float3 min = points[0];
LifeMath::float3 max = min;
for (int i = 0; i < count; i++)
{
Vec3Minimize(min, points[i], min);
Vec3Maximize(max, points[i], max);
}
return BoundingBox3D(min, max);
}
static ContainmentType ContainsBox( BoundingBox3D& box1, BoundingBox3D& box2)
{
if ((box1.maximum().X < box2.minimum().X) || (box1.minimum().X > box2.maximum().X))
{
return Disjoint;
}
if ((box1.maximum().Y < box2.minimum().Y) || (box1.minimum().Y > box2.maximum().Y))
{
return Disjoint;
}
if ((box1.maximum().Z < box2.minimum().Z) || (box1.minimum().Z > box2.maximum().Z))
{
return Disjoint;
}
if ((((box1.minimum().X <= box2.minimum().X) && (box2.maximum().X <= box1.maximum().X)) && ((box1.minimum().Y <= box2.minimum().Y) && (box2.maximum().Y <= box1.maximum().Y))) && ((box1.minimum().Z <= box2.minimum().Z) && (box2.maximum().Z <= box1.maximum().Z)))
{
return Contains;
}
return Intersects;
}
void GetCorners(LifeMath::float3* corners) const
{
// 5________6
// / /
// / /
// /________2/
// 1 | 7
// | |
// | |
// 0---------3
corners[0] = LifeMath::float3(vMin.X, vMin.Y, vMin.Z);
corners[1] = LifeMath::float3(vMin.X, vMax.Y, vMin.Z);
corners[2] = LifeMath::float3(vMax.X, vMax.Y, vMin.Z);
corners[3] = LifeMath::float3(vMax.X, vMin.Y, vMin.Z);
corners[4] = LifeMath::float3(vMin.X, vMin.Y, vMax.Z);
corners[5] = LifeMath::float3(vMin.X, vMax.Y, vMax.Z);
corners[6] = LifeMath::float3(vMax.X, vMax.Y, vMax.Z);
corners[7] = LifeMath::float3(vMax.X, vMin.Y, vMax.Z);
}
private:
LifeMath::float3 vMin;
LifeMath::float3 vMax;
};
}
#endif // BoundingBox3D_h__
+10
View File
@@ -0,0 +1,10 @@
#define ENGINE_VERSION 1
//#define BUILD_STATIC
#ifdef BUILD_STATIC
#define LIFE_EXPORTS
#else
#define LIFE_EXPORTS
#endif
typedef unsigned char byte;
+22
View File
@@ -0,0 +1,22 @@
#ifndef COM_H__
#define COM_H__
#include "log/NLog.h"
#define PPCAT_NX(A, B) A ## B
#define PPCAT(A, B) PPCAT_NX(A, B)
#define SAFE_RELEASE(__PTR___) \
if(__PTR___ != nullptr)\
(__PTR___)->Release(); \
#define FINAL_RELEASE(__PTR___) \
if(__PTR___ != nullptr) {\
auto __PTR___##release_return_val = (__PTR___)->Release(); \
if(__PTR___##release_return_val != 0) {\
LogInfo() << PPCAT("Final release failed on object ", #__PTR___) << " Refcount now = " << __PTR___##release_return_val; \
}}
#endif
+132
View File
@@ -0,0 +1,132 @@
#ifndef DELEGATE_H
#define DELEGATE_H
//Container interface
template<typename... Args>
class IContainer {
public:
virtual void Call(Args...) {}
virtual ~IContainer() {}
IContainer<Args...> *next;
};
//Container realization
template< typename T, typename M, typename... Args > class MContainer : public IContainer<Args...> {
public:
MContainer(T* c, M m) : mClass(c), mMethod(m) {}
void Call(Args... args) {
(mClass->*mMethod)(args...);
}
private:
T *mClass;
M mMethod;
};
template< typename M, typename... Args > class FContainer : public IContainer<Args...> {
public:
FContainer(M m) : mMethod(m) {}
void Call(Args... args) {
(mMethod)(args...);
}
private:
M mMethod;
};
//Delegate
template<typename... Args>
class Delegate {
public:
Delegate() {
mContainerHead = new IContainer<Args...>();
mContainerTail = mContainerHead;
mContainerHead->next = 0;
}
~Delegate() {
IContainer<Args...> *container = mContainerHead;
while(container) {
IContainer<Args...> *temp = container->next;
delete container;
container = temp;
}
}
void Clear() {
IContainer<Args...> *container = mContainerHead->next;
while(container) {
IContainer<Args...> *temp = container->next;
delete container;
container = temp;
}
mContainerHead->next = 0;
mContainerTail = mContainerHead;
}
template<typename T, typename M>
void Connect(T *c, M m) {
mContainerTail->next = new MContainer< T, M, Args... >(c, m);
mContainerTail->next->next = 0;
mContainerTail = mContainerTail->next;
}
template<typename M>
void Connect(M m) {
mContainerTail->next = new FContainer< M, Args... >(m);
mContainerTail->next->next = 0;
mContainerTail = mContainerTail->next;
}
template<typename T, typename M>
void Disconnect(T *c, M m) {
IContainer<Args...> *container = mContainerHead;
while(container->next) {
MContainer<T, M, Args...> *temp = dynamic_cast<MContainer<T, M, Args...>*>(container->next);
if(temp) {
if(container->next == mContainerTail) {
mContainerTail = container;
}
container->next = container->next->next;
delete temp;
break;
}
container = container->next;
}
}
template<typename M>
void Disconnect(M m) {
IContainer<Args...> *container = mContainerHead;
while(container->next) {
FContainer<M, Args...> *temp = dynamic_cast<FContainer<M, Args...>*>(container->next);
if(temp) {
if(container->next == mContainerTail) {
mContainerTail = container;
}
container->next = container->next->next;
delete temp;
break;
}
container = container->next;
}
}
void operator ()(Args... args) {
Call(args...);
}
void Call(Args... args) {
IContainer<Args...> *container = mContainerHead;
while(container) {
container->Call(args...);
container = container->next;
}
}
private:
IContainer<Args...> *mContainerHead;
IContainer<Args...> *mContainerTail;
};
#endif // DELEGATE_H
+14
View File
@@ -0,0 +1,14 @@
#ifndef DisplayMode_h__
#define DisplayMode_h__
namespace LifeCore
{
struct DisplayMode
{
int width;
int height;
int refreshRate;
int bpp;
};
}
#endif // DisplayMode_h__
+20
View File
@@ -0,0 +1,20 @@
#ifndef Error_h__
#define Error_h__
enum ERROR_CODE
{
EC_TEST = 0,
};
enum SUCCESS_CODE
{
SC_OK = 0,
SC_FAIL = 1
};
enum VFS_ERROR
{
EC_UNKNOWN = -1,
EC_FILE_ALREADY_EXISTS = 1
};
#endif // Error_h__
+78
View File
@@ -0,0 +1,78 @@
#include "FrameCounter.h"
#include "Timer.h"
namespace LifeCore
{
FrameCounter::FrameCounter()
:fps(0.0f), frame_range(50), avg_fps(0.0f), time_elapsed(0.0f),
frame_id(0), time_elapsed_avg(0.0f), buffer_pos(0)
{
timer = new Timer();
prev_time = new float[frame_range];
for(int i = 0; i < frame_range; i++)
prev_time[i] = 0.0f;
}
FrameCounter::~FrameCounter()
{
delete[] prev_time;
}
float FrameCounter::GetFps()
{
return fps;
}
float FrameCounter::GetFpsAvg()
{
return avg_fps;
}
float FrameCounter::GetTimeElapled()
{
return time_elapsed;
}
float FrameCounter::GetTimeElapsedAvg()
{
return time_elapsed_avg;
}
void FrameCounter::SetFrameRange(int range)
{
frame_range = range;
buffer_pos = 0;
if(prev_time!=0)
delete[] prev_time;
prev_time = new float[frame_range];
for(int i = 0; i < frame_range; i++)
prev_time[i] = 0.0f;
}
int FrameCounter::GetFrameId()
{
return frame_id;
}
void FrameCounter::OnFrameEnd()
{
timer->Stop();
//get frame time elapsed
time_elapsed = timer->getTimeElapsed();
//store time elapsed in buffer
prev_time[frame_id % frame_range] = time_elapsed;
//fix offset
buffer_pos++;
if(buffer_pos >= frame_range)
buffer_pos = 0;
fps = 1.0f / time_elapsed;
//compute average time elapsed
float sum = 0.0f;
for(int i = 0; i < frame_range; i++)
sum += prev_time[i];
time_elapsed_avg = sum / (float)frame_range;
avg_fps = 1.0f / time_elapsed_avg;
frame_id++;
timer->Start();
}
}
+32
View File
@@ -0,0 +1,32 @@
#ifndef FrameCounter_h__
#define FrameCounter_h__
namespace LifeCore
{
class Timer;
class FrameCounter
{
public:
FrameCounter();
~FrameCounter();
int GetFrameId();
float GetFps();
float GetFpsAvg();
float GetTimeElapled();
float GetTimeElapsedAvg();
void SetFrameRange(int range);
void OnFrameEnd();
private:
float* prev_time;
int buffer_pos;
float fps;
float avg_fps;
float time_elapsed;
float time_elapsed_avg;
int frame_range;
int frame_id;
Timer* timer;
};
}
#endif // FrameCounter_h__
+14
View File
@@ -0,0 +1,14 @@
#ifndef ICamera_h__
#define ICamera_h__
#include "IDevice.h"
#include "NMath.h"
using namespace NettleMath;
namespace LifeCore {
struct ICamera : public IDevice {
};
}
#endif // ICamera_h__
+14
View File
@@ -0,0 +1,14 @@
#ifndef IDATARECTANGLE_H__
#define IDATARECTANGLE_H__
#include "IMemoryStream.h"
namespace LifeCore
{
typedef struct IDataRectangle
{
int pitch;
LifeCore::IMemoryStream data;
}IDataRectangle, *PIDataRectangle, **LPIDataRectangle;
}
#endif
+24
View File
@@ -0,0 +1,24 @@
#ifndef IDATASTREAM_H__
#define IDATASTREAM_H__
#include <memory>
namespace LifeCore
{
class IDataStream
{
public:
virtual ~IDataStream(){}
virtual void Close() = 0;
virtual size_t Read(void* pBuffer, size_t countBytes) = 0;
virtual size_t Write(const void* pBuffer, size_t countBytes) = 0;
virtual void Seek(size_t position) = 0;
virtual size_t Tell() = 0;
virtual size_t Length() = 0;
virtual bool CanRead() = 0;
virtual bool CanWrite() = 0;
};
typedef std::auto_ptr<IDataStream> IDataStreamPtr;
}
#endif
+9
View File
@@ -0,0 +1,9 @@
#ifndef IDevice_h__
#define IDevice_h__
namespace LifeCore{
struct IDevice{
};
}
#endif // IDevice_h__
+14
View File
@@ -0,0 +1,14 @@
#ifndef IImage_h__
#define IImage_h__
#include "NMath.h"
using namespace NettleMath;
namespace LifeCore {
struct IImage {
virtual int2 GetSize() = 0;
virtual int32 GetBpp() = 0;
virtual bool Read(int2 size, uint8* buffer) = 0;
};
}
#endif // IImage_h__
+61
View File
@@ -0,0 +1,61 @@
#include "IInputSystem.h"
#include "IInputListener.h"
namespace LifeCore
{
bool IInputSystem::IsListening(IInputListener* listener){
for(auto val : listeners)
if(val == listener)
return true;
return false;
}
bool IInputSystem::RemoveListener(IInputListener* listener){
auto it = listeners.begin();
for(it = listeners.begin(); it != listeners.end(); ++it){
if(*it == listener)
break;
}
if(it == listeners.end())
return false;
listeners.erase(it);
if(listener->GetInputSystem() == this){
listener->SetInputSystem(nullptr);
}
return true;
}
void IInputSystem::AddListener(IInputListener* listener){
if(IsListening(listener))
return;
listeners.push_back(listener);
if(listener->GetInputSystem() != this)
listener->SetInputSystem(this);
}
bool IInputSystem::KeyPressed(Key key){
return keyboard_keys[static_cast<size_t>(key)];
}
void IInputSystem::OnKeyPress(Key key, unsigned int text, const std::string& str){
keyboard_keys[static_cast<size_t>(key)] = true;
for(auto listener : listeners)
listener->KeyDown(key, text, str);
}
void IInputSystem::OnKeyRelease(Key key, unsigned int text, const std::string& str){
keyboard_keys[static_cast<size_t>(key)] = false;
for(auto listener : listeners)
listener->KeyUp(key, text, str);
}
void IInputSystem::OnMouseMove(int absX, int relX, int absY, int relY){
for(auto listener : listeners)
listener->MouseMove(absX, relX, absY, relY);
}
void IInputSystem::OnMousePress(MouseKey button){
for(auto listener : listeners)
listener->MousePressed(button);
}
void IInputSystem::OnMouseRelease(MouseKey button){
for(auto listener : listeners)
listener->MouseReleased(button);
}
}
+132
View File
@@ -0,0 +1,132 @@
#ifndef IInputSystem_h__
#define IInputSystem_h__
#include "Types.h"
#include <string>
#include <list>
#include <vector>
#include <array>
namespace LifeCore
{
class KeyCodes {
public:
enum Key {
UNKNOWN_KEY,
KEY_ESCAPE,
KEY_F1,
KEY_F2,
KEY_F3,
KEY_F4,
KEY_F5,
KEY_F6,
KEY_F7,
KEY_F8,
KEY_F9,
KEY_F10,
KEY_F11,
KEY_F12,
KEY_PRINT_SCREEN,
KEY_SCROLL_LOCK,
KEY_PAUSE,
KEY_TILDE,
KEY_1,
KEY_2,
KEY_3,
KEY_4,
KEY_5,
KEY_6,
KEY_7,
KEY_8,
KEY_9,
KEY_0,
KEY_MINUS,
KEY_EQUAL,
KEY_BACKSPACE,
KEY_TAB,
KEY_CAPS_LOCK,
KEY_SHIFT,
KEY_CONTROL,
KEY_META_LEFT,
KEY_META_RIGHT,
KEY_ALT,
KEY_SPACE,
KEY_MENU,
KEY_ENTER,
KEY_A,
KEY_B,
KEY_C,
KEY_D,
KEY_E,
KEY_F,
KEY_G,
KEY_H,
KEY_I,
KEY_J,
KEY_K,
KEY_L,
KEY_M,
KEY_N,
KEY_O,
KEY_P,
KEY_Q,
KEY_R,
KEY_S,
KEY_T,
KEY_U,
KEY_V,
KEY_W,
KEY_X,
KEY_Y,
KEY_Z,
KEY_BRACKET_RIGHT,
KEY_BRACKET_LEFT,
KEY_BACKSLASH,
KEY_SEMICOLON,
KEY_APOSTROPHE,
KEY_COMMA,
KEY_DOT,
KEY_SLASH,
KEY_INSERT,
KEY_DELETE,
KEY_HOME,
KEY_END,
KEY_PAGE_UP,
KEY_PAGE_DOWN,
KEY_UP,
KEY_LEFT,
KEY_DOWN,
KEY_RIGHT,
KEY_NUM_LOCK,
KEY_NUM_DIVIDE,
KEY_NUM_MULTIPLY,
KEY_NUM_SUBTRACT,
KEY_NUM_ADD,
KEY_NUM_DECIMAL,
KEY_NUM_0,
KEY_NUM_1,
KEY_NUM_2,
KEY_NUM_3,
KEY_NUM_4,
KEY_NUM_5,
KEY_NUM_SPECIAL,
KEY_NUM_6,
KEY_NUM_7,
KEY_NUM_8,
KEY_NUM_9
};
};
class IInputListener;
class IInputSystem
{
public:
virtual bool IsKeyPressed(KeyCodes::Key key) = 0;
};
}
#endif // IInputSystem_h__
+139
View File
@@ -0,0 +1,139 @@
#ifndef I_MEMORY_STREAM_H__
#define I_MEMORY_STREAM_H__
#include "IDataStream.h"
namespace LifeCore
{
class IMemoryStream : public LifeCore::IDataStream
{
private:
char* pData;
size_t position;
size_t stmLength;
bool userData;
public:
IMemoryStream()
{
userData = true;
pData = 0;
stmLength = 0;
position = 0;
}
IMemoryStream(size_t size)
{
userData = false;
pData = new char[size];
stmLength = size;
position = 0;
}
IMemoryStream(char* _pData, size_t dataSize)
{
userData = true;
pData = _pData;
stmLength = dataSize;
position = 0;
}
~IMemoryStream()
{
if(!userData && pData !=0)
{
delete[] pData;
}
}
int stride;
int vertexCount;
char* GetData()
{
return pData;
}
void Clear(int val)
{
memset(pData, val, stmLength);
}
void Close()
{
}
void Reset(char* _pData, size_t dataSize)
{
pData = _pData;
stmLength = dataSize;
position = 0;
}
size_t Read(void* pBuffer, size_t countBytes)
{
size_t diff = stmLength - position;
if(diff <=0 || !countBytes)return 0;
if(countBytes > diff)
countBytes = diff;
memcpy(pBuffer, pData + position, countBytes);
position+=countBytes;
return countBytes;
}
size_t ReadInt8(char& data)
{
return Read(&data, sizeof(char));
}
size_t ReadInt16(short& data)
{
return Read(&data, sizeof(short));
}
size_t ReadInt32(int& data)
{
return Read(&data, sizeof(int));
}
#define DEF_WRITE(type_name)\
size_t Write(type_name val) \
{ return Write(&val, sizeof(type_name)); } \
DEF_WRITE(short);
DEF_WRITE(int);
DEF_WRITE(char);
DEF_WRITE(float);
DEF_WRITE(double);
DEF_WRITE(long long);
DEF_WRITE(unsigned short);
DEF_WRITE(unsigned int);
DEF_WRITE(unsigned char);
size_t Write(const void* pBuffer, size_t countBytes)
{
size_t diff = stmLength - position;
if(diff <=0)return 0;
//if(countBytes > diff)
// countBytes = diff;
memcpy(pData + position, pBuffer, countBytes);
position+=countBytes;
return countBytes;
}
void Seek(size_t _position)
{
position = _position;
if(position < 0) position = 0;
if(position >= stmLength && stmLength !=0) position = stmLength - 1;
}
size_t Tell()
{
return position;
}
size_t Length()
{
return stmLength;
}
bool CanRead()
{
return true;
}
bool CanWrite()
{
return true;
}
};
}
#endif
+24
View File
@@ -0,0 +1,24 @@
#include "IProperty.h"
namespace LifeCore
{
bool IProperty::ContainsAttribute(const String& name)
{
if(attributes.find(name) == attributes.end())
return false;
return true;
}
int IProperty::AddAttribute(const String& name, const String& value)
{
attributes[name] = value;
return SC_OK;
}
int IProperty::GetAttribute(const String& name, String& value)
{
if(attributes.find(name) == attributes.end())
return SC_FAIL;
value = attributes[name];
return SC_OK;
}
}
+57
View File
@@ -0,0 +1,57 @@
#ifndef IProperty_h__
#define IProperty_h__
#include "LString.h"
#include "delegate/Delegate.h"
#include <map>
#include "Error.h"
#include "ISerializable.h"
namespace LifeCore
{
enum PropertyEditMode
{
EM_INPLACE = 0,
EM_DROPDOWN = 1,
EM_CUSTOM = 2,
};
struct Attribute
{
public:
String Name;
String Value;
};
class IProperty : public ISerializable
{
public:
EVENT0(PropertyEvent);
PropertyEvent Event_ValueChanged;
int AddAttribute(const String& name, const String& value);
int GetAttribute(const String& name, String& value);
virtual String ToString() { return STR("Unspecified"); };
virtual void FromString(const String& str) { UNREFERENCED_PARAMETER(str); }
bool ContainsAttribute(const String& name);
template<typename T> void Set(const T* src){
Set(static_cast<const void*>(src), sizeof(T));
}
template<typename T> void Set(const T& src){
Set(static_cast<const void*>(&src), sizeof(T));
}
template<typename T> const T& Get(){
return *static_cast<const T*>(GetPtr());
}
private:
typedef std::map<String, String> AttributeList;
typedef std::map<String, String>::iterator AttributeListItr;
AttributeList attributes;
protected:
virtual void Set(const void* src, size_t size) = 0;
virtual const void* GetPtr() = 0;
void OnValueChanged(){
Event_ValueChanged.Invoke();
}
};
}
#endif // IProperty_h__
+66
View File
@@ -0,0 +1,66 @@
#include "IPropertyHolder.h"
#include <assert.h>
namespace LifeCore
{
bool IPropertyHolder::Serialize(LifeCore::IMemoryStream* stm)
{
stm->Write(size_t(properties.size()));
for(PropertyCollectionItr it = properties.begin(); it != properties.end(); ++it){
(*it)->Serialize(stm);
}
return true;
}
bool IPropertyHolder::Deserialize(LifeCore::IMemoryStream* stm)
{
size_t prop_cnt;
stm->Read(&prop_cnt, sizeof(prop_cnt));
assert(prop_cnt == properties.size() && "Failed on IPropertyHolder deserialization!");
for(PropertyCollectionItr it = properties.begin(); it != properties.end(); ++it){
(*it)->Deserialize(stm);
}
return true;
}
PropertyCollection* IPropertyHolder::GetProperties()
{
return &properties;
}
void IPropertyHolder::RegisterProperty(IProperty* property)
{
properties.push_back(property);
}
void IPropertyHolder::UnregisterProperty(IProperty* property)
{
UNREFERENCED_PARAMETER(property);
//TODO remove prop
}
bool IPropertyHolder::GetPropertyByAttribute(const String& name, IProperty** prop)
{
for(PropertyCollectionItr it = properties.begin(); it != properties.end(); ++it)
{
IProperty* p = *it;
if(p->ContainsAttribute(name))
{
*prop = p;
return true;
}
}
return false;
}
bool IPropertyHolder::GetPropertyByAttribute(const String& name, const String& value, IProperty** prop)
{
for(PropertyCollectionItr it = properties.begin(); it != properties.end(); ++it)
{
IProperty* p = *it;
String tmpVal;
if(p->GetAttribute(name, tmpVal) == SC_OK)
{
if(tmpVal == value)
{
*prop = p;
return true;
}
}
}
return false;
}
}
+27
View File
@@ -0,0 +1,27 @@
#ifndef IPropertyHolder_h__
#define IPropertyHolder_h__
#include <vector>
#include "IProperty.h"
#include "ISerializable.h"
typedef std::vector<LifeCore::IProperty*> PropertyCollection;
typedef std::vector<LifeCore::IProperty*>::iterator PropertyCollectionItr;
namespace LifeCore
{
class IPropertyHolder : public ISerializable
{
public:
bool Serialize(LifeCore::IMemoryStream* stm);
bool Deserialize(LifeCore::IMemoryStream* stm);
PropertyCollection* GetProperties();
void RegisterProperty(IProperty* property);
void UnregisterProperty(IProperty* property);
bool GetPropertyByAttribute(const String& name, IProperty** prop);
bool GetPropertyByAttribute(const String& name, const String& value, IProperty** prop);
private:
PropertyCollection properties;
};
}
#endif // IPropertyHolder_h__
+25
View File
@@ -0,0 +1,25 @@
#ifndef IPropertyItem_h__
#define IPropertyItem_h__
#include "Property.h"
#include <delegate/Delegate.h>
namespace LifeCore
{
class IPropertyItem
{
public:
EVENT0(PropertyItemEvent);
PropertyItemEvent Event_ValueChanged;
virtual PropertyEditMode GetEditMode() = 0;
virtual void OnBeginEdit() {};
virtual void OnEndEdit(const String& data) = 0;
virtual String ToString() = 0;
private:
void OnPropertyChanged()
{
Event_ValueChanged.Invoke();
}
};
}
#endif // IPropertyItem_h__
+13
View File
@@ -0,0 +1,13 @@
#ifndef ISerializable_h__
#define ISerializable_h__
#include "IMemoryStream.h"
class ISerializable
{
public:
virtual bool Serialize(LifeCore::IMemoryStream* stm) = 0;
virtual bool Deserialize(LifeCore::IMemoryStream* stm) = 0;
};
#endif // ISerializable_h__
+114
View File
@@ -0,0 +1,114 @@
#ifndef ITransform_h__
#define ITransform_h__
#include "math/LifeMath.h"
#include "delegate/Delegate.h"
namespace LifeCore
{
class ITransform
{
private:
LifeMath::float3 position;
LifeMath::Quaternion rotation;
LifeMath::float3 scaling;
LifeMath::float4x4 transform;
bool valid;
public:
EVENT(TransformEvent);
TransformEvent Event_SetPosition;
TransformEvent Event_SetRotation;
TransformEvent Event_SetScaling;
void UpdateTransform()
{
LifeMath::float4x4 trans;
Mat4x4Translation(position, trans);
LifeMath::float4x4 scale;
Mat4x4Scaling(scaling, scale);
LifeMath::float4x4 rot;
Mat4x4RotationQuaternion(rotation, rot);
transform = scale * rot * trans;
valid = true;
}
bool IsValid()
{
return valid;
}
ITransform()
:valid(false), position(0.0f, 0.0f, 0.0f), scaling(1.0f, 1.0f, 1.0f)
{
QuatSetAxisAngle(LifeMath::float3(0.0f, 0.0f, 0.0f), 0.0f, rotation);
UpdateTransform();
}
~ITransform()
{
}
const LifeMath::float4x4& GetMatrix()
{
if(!valid)
UpdateTransform();
return transform;
}
const LifeMath::float3& GetPosition() const
{
return position;
}
const LifeMath::float3& GetScaling() const
{
return scaling;
}
const LifeMath::Quaternion& GetRotation() const
{
return rotation;
}
void SetMatrix(const LifeMath::float4x4& newTransform)
{
transform = newTransform;
Mat4x4Decompose(transform, position, scaling, rotation);
valid = true;
}
void SetPosition(const LifeMath::float3& _position)
{
if(position != _position)
{
position = _position;
valid = false;
Event_SetPosition.Invoke();
}
}
void SetRotation(const LifeMath::Quaternion& _rotation)
{
if(rotation != _rotation)
{
rotation = _rotation;
valid = false;
Event_SetRotation.Invoke();
}
}
void SetRotation(const LifeMath::float3& axis, float angle)
{
QuatSetAxisAngle(axis, angle, rotation);
valid = false;
Event_SetRotation.Invoke();
}
void SetAngles(const LifeMath::float3& angles)
{
printf("OMG! SetAngles isn't implemented!!");
}
void SetScaling(const LifeMath::float3& _scaling)
{
if(scaling != _scaling)
{
scaling = _scaling;
valid = false;
Event_SetScaling.Invoke();
}
}
};
}
#endif // ITransform_h__
+43
View File
@@ -0,0 +1,43 @@
#ifndef IRenderWindow_h__
#define IRenderWindow_h__
#include "delegate/Delegate.h"
#include "Build.h"
#include "LString.h"
#include "DisplayMode.h"
#include "IWindowDemander.h"
#include "IInputSystem.h"
namespace LifeCore
{
class IWindow : public IInputSystem
{
public:
virtual void Update() = 0;
virtual void SetCaption(const String& caption) = 0;
virtual int GetWindowHandle() = 0;
virtual int GetWidth() = 0;
virtual int GetHeight() = 0;
virtual void SetSize(int w, int h) = 0;
virtual const String& GetCaption() = 0;
virtual bool IsFullScreen() = 0;
virtual void SetFullScreen(bool state) = 0;
virtual bool SwitchMode(bool fullscreen) = 0;
virtual void SetFullscreenMode(DisplayMode mode) = 0;
/*virtual const DisplayMode& GetFullscreenMode()
{
return fsMode;
}*/
virtual void OnActivate() = 0;
virtual void OnDeactivate() = 0;
virtual void OnResize() = 0;
virtual bool IsActive() = 0;
virtual bool IsModeSwitching() = 0;
virtual void SetCursorVisible(bool state) = 0;
virtual bool IsCursorVisible() = 0;
virtual void CenterWindow() = 0;
};
}
#endif // IRenderWindow_h__
+10
View File
@@ -0,0 +1,10 @@
#ifndef IWindowDemander_h__
#define IWindowDemander_h__
namespace LifeCore {
class IWindowDemander {
public:
virtual void OnRawInput() = 0;
};
}
#endif // IWindowDemander_h__
+11
View File
@@ -0,0 +1,11 @@
#ifndef InputDevice_h__
#define InputDevice_h__
#include "IDevice.h"
namespace LifeCore{
class InputDevice : public LifeCore::IDevice{
};
}
#endif // InputDevice_h__
+17
View File
@@ -0,0 +1,17 @@
#ifndef InputListener_h__
#define InputListener_h__
#include "InputTypes.h"
#include "math/LifeMath.h"
namespace LifeCore{
class InputListener{
public:
InputListener();
virtual ~InputListener();
virtual void onKeyEvent(InputDeviceType dev_type, int dev_id, InputKey key, InputKeyAction action) = 0;
virtual void onAxisEvent(InputDeviceType dev_type, int dev_id, Axis axis, float value) = 0;
virtual void onAngleEvent(InputDeviceType dev_type, int dev_id, LifeMath::float3 axis, float angle) = 0;
};
}
#endif // InputListener_h__
+101
View File
@@ -0,0 +1,101 @@
#include "InputSystem.h"
#include "log/NLog.h"
namespace LifeCore {
InputSystem::InputSystem() {
auto hInst = GetModuleHandle(NULL);
hwnd = NULL;
WNDCLASSEX wndClass = { NULL };
wndClass.cbSize = sizeof(WNDCLASSEX);
wndClass.cbClsExtra = NULL;
wndClass.cbWndExtra = NULL;
wndClass.hbrBackground = (HBRUSH)GetStockObject(1);
wndClass.hCursor = (HCURSOR)LoadCursor(NULL, IDC_ARROW);
wndClass.hIcon = LoadIcon(hInst, IDI_APPLICATION);
wndClass.hIconSm = LoadIcon(hInst, IDI_APPLICATION);
wndClass.hInstance = hInst;
wndClass.lpfnWndProc = WndProc;
wndClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wndClass.lpszMenuName = NULL;
wndClass.lpszClassName = _text("LifeEngineInputWindow");
if(!RegisterClassEx(&wndClass)) {
MessageBox((HWND)hwnd, _text("Can not create window class! We all gonna die!!"), _text("OH SHIT!"), MB_OK);
}
RECT NewWindowSize;
NewWindowSize.top = 30;
NewWindowSize.left = 300;
NewWindowSize.bottom = NewWindowSize.top + 100;
NewWindowSize.right = NewWindowSize.left + 100;
AdjustWindowRect(&NewWindowSize, WS_OVERLAPPEDWINDOW, false);
if(!(hwnd = (long)CreateWindowEx(NULL, _text("LifeEngineInputWindow"), _text("LifeEngine Input window"), WS_THICKFRAME,
NewWindowSize.left, NewWindowSize.top, NewWindowSize.right - NewWindowSize.left, NewWindowSize.bottom - NewWindowSize.top, NULL, NULL, hInst, NULL))) {
MessageBox((HWND)hwnd, _text("Can not create window! We all gonna die!!"), _text("HOLY SHIT!"), MB_OK);
}
SetWindowLongPtr((HWND)hwnd, GWLP_USERDATA, (long)(this));
ShowWindow((HWND)hwnd, SW_HIDE);
}
void InputSystem::Init() {
RAWINPUTDEVICE dev;
dev.usUsagePage = 1;
dev.usUsage = 2;
dev.dwFlags = 0;
dev.hwndTarget = (HWND)hwnd;
if(!RegisterRawInputDevices(&dev, 1, sizeof(dev))) {
LogInfo() << "Raw devices registration failed!";
} else {
LogInfo() << "Raw devices registered!";
}
}
void InputSystem::Update() {
MSG msg = { 0 };
while(PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
LRESULT __stdcall InputSystem::WndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) {
switch(message) {
case WM_INPUT:
{
UINT dwSize;
GetRawInputData((HRAWINPUT)lparam, RID_INPUT, NULL, &dwSize, sizeof(RAWINPUTHEADER));
char* data = new char[dwSize];
if(GetRawInputData((HRAWINPUT)lparam, RID_INPUT, data, &dwSize, sizeof(RAWINPUTHEADER)) != dwSize) {
LogInfo() << "Wrong raw input size!";
}
RAWINPUT* inp = (RAWINPUT*)data;
if(inp->header.dwType == RIM_TYPEMOUSE) {
LogInfo() << "Read mouse input2!";
LogInfo() << "Buttons: " << inp->data.mouse.ulButtons;
}
long val = GetWindowLongPtr(hwnd, GWLP_USERDATA);
if(val) {
InputSystem* input = reinterpret_cast<InputSystem*>(val);
LogInfo() << "OnInput";
//wnd->OnInput();
}
delete[] data;
return 0;
}
break;
}
return DefWindowProc(hwnd, message, wparam, lparam);
}
}
+19
View File
@@ -0,0 +1,19 @@
#ifndef InputSystem_h__
#define InputSystem_h__
#include <Windows.h>
#include "Types.h"
namespace LifeCore {
class InputSystem
{
public:
InputSystem();
void Init();
void Update();
private:
static long __stdcall WndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam);
uint8 keys[0xff];
long hwnd;
};
}
#endif // InputSystem_h__
+22
View File
@@ -0,0 +1,22 @@
#ifndef InputSystem_h__
#define InputSystem_h__
#include "InputDevice.h"
#include "InputTypes.h"
#include <memory>
#include <vector>
namespace LifeCore{
class InputSystem{
public:
typedef std::vector<std::shared_ptr<InputDevice> > InputDeviceList;
InputSystem();
virtual ~InputSystem();
InputDeviceList getDevices(InputDeviceType device);
virtual void update();
private:
InputDeviceList devices;
};
}
#endif // InputSystem_h__
+181
View File
@@ -0,0 +1,181 @@
#include "InputSystemOIS.h"
#include <OIS.h>
using namespace OIS;
#include <iostream>
#include <sstream>
#include <windows.h>
#include <vector>
#include "LString.h"
namespace LifeCore
{
class input_impl : public KeyListener, MouseListener
{
public:
input_impl(IInputSystem* sys)
{
input_system = sys;
}
~input_impl()
{
if(input)
InputManager::destroyInputSystem(input);
}
void Init(int scrW, int scrH, bool exclusiveMode, int hwnd)
{
//setlocale(LC_ALL,"");
HWND hw = (HWND)hwnd;
std::ostringstream wnd;
wnd << (size_t)hw << "\0";
pl.insert(std::make_pair( std::string("WINDOW"), wnd.str() ));
if( exclusiveMode)
{
pl.insert(std::make_pair(std::string("w32_mouse"), std::string("DISCL_FOREGROUND")));
pl.insert(std::make_pair(std::string("w32_mouse"), std::string("DISCL_EXCLUSIVE")));
}
else
{
pl.insert(std::make_pair(std::string("w32_mouse"), std::string("DISCL_BACKGROUND")));
pl.insert(std::make_pair(std::string("w32_mouse"), std::string("DISCL_NONEXCLUSIVE")));
}
pl.insert(std::make_pair(std::string("w32_keyboard"), std::string("DISCL_BACKGROUND")));
pl.insert(std::make_pair(std::string("w32_keyboard"), std::string("DISCL_NONEXCLUSIVE")));
input = InputManager::createInputSystem(pl);
keyboard = (Keyboard*)input->createInputObject(OISKeyboard,1);
mouse = (Mouse*)input->createInputObject(OISMouse,1);
mouse->getMouseState().width = scrW;
mouse->getMouseState().height = scrH;
keyboard->setEventCallback(this);
mouse->setEventCallback(this);
keyboard->setTextTranslation(OIS::Keyboard::Unicode);
}
bool KeyPressed(Key key)
{
return keyboard->isKeyDown((KeyCode)key);
}
bool MouseButtonPressed(LifeCore::MouseKey button)
{
MouseButtonID k = (MouseButtonID)(button);
return mState.buttonDown(k);
}
int GetMouseWheel()
{
return mState.Z.rel;
}
void Capture()
{
keyboard->capture();
mouse->capture();
mState = mouse->getMouseState();
}
int GetMouseRelativeX()
{
return mState.X.rel;
}
int GetMouseRelativeY()
{
return mState.Y.rel;
}
int GetMouseAbsoluteX()
{
return mState.X.abs;
}
int GetMouseAbsoluteY()
{
return mState.Y.abs;
}
private:
IInputSystem* input_system;
ParamList pl;
InputManager* input;
Keyboard* keyboard;
Mouse* mouse;
OIS::MouseState mState;
bool keyPressed( const KeyEvent &arg ){
//String text = arg.text;
wchar_t new_key[2];
new_key[0]= arg.text;
new_key[1] = L'\0';
std::wstring str(&new_key[0]);
std::string res;
WCSTMBS(str.c_str(), res);
input_system->OnKeyPress((Key)arg.key,new_key[0], res);
return true;
}
bool keyReleased( const KeyEvent &arg ){
wchar_t new_key[2];
new_key[0] = arg.text;
new_key[1] = L'\0';
std::wstring str(&new_key[0]);
std::string res;
WCSTMBS(str.c_str(), res);
input_system->OnKeyRelease((Key)arg.key, arg.text, res);
return true;
}
bool mouseMoved( const MouseEvent &arg ) {
input_system->OnMouseMove(arg.state.X.abs,arg.state.X.rel,arg.state.Y.abs,arg.state.Y.rel);
return true;
}
bool mousePressed( const MouseEvent &arg, MouseButtonID id ){
input_system->OnMousePress((LifeCore::MouseKey)id);
return true;
}
bool mouseReleased( const MouseEvent &arg, MouseButtonID id ){
input_system->OnMouseRelease((LifeCore::MouseKey)id);
return true;
}
};
InputSystemOIS::InputSystemOIS()
{
pImpl = new input_impl(this);
}
InputSystemOIS::~InputSystemOIS()
{
if(pImpl)
delete pImpl;
}
void InputSystemOIS::Init(int scrW, int scrH, bool exclusiveMode, int hwnd)
{
pImpl->Init(scrW, scrH, exclusiveMode, hwnd);
}
void InputSystemOIS::Capture()
{
pImpl->Capture();
}
bool InputSystemOIS::KeyPressed(Key key)
{
return pImpl->KeyPressed(key);
}
bool InputSystemOIS::MouseButtonPressed(LifeCore::MouseKey key)
{
return pImpl->MouseButtonPressed(key);
}
int InputSystemOIS::GetMouseWheel()
{
return pImpl->GetMouseWheel();
}
int InputSystemOIS::GetMouseRelativeX()
{
return pImpl->GetMouseRelativeX();
}
int InputSystemOIS::GetMouseRelativeY()
{
return pImpl->GetMouseRelativeY();
}
int InputSystemOIS::GetMouseAbsoluteX()
{
return pImpl->GetMouseAbsoluteX();
}
int InputSystemOIS::GetMouseAbsoluteY()
{
return pImpl->GetMouseAbsoluteY();
}
}
+30
View File
@@ -0,0 +1,30 @@
#ifndef InputSystemOIS_h__
#define InputSystemOIS_h__
#include "IInputSystem.h"
namespace LifeCore
{
class input_impl;
class InputSystemOIS : public LifeCore::IInputSystem
{
private:
input_impl* pImpl;
public:
InputSystemOIS();
~InputSystemOIS();
void Init(int scrW, int scrH, bool exclusiveMode, int hwnd);
void Capture();
bool KeyPressed(LifeCore::Key key);
bool MouseButtonPressed(LifeCore::MouseKey key);
int GetMouseWheel();
int GetMouseRelativeX();
int GetMouseRelativeY();
int GetMouseAbsoluteX();
int GetMouseAbsoluteY();
void CenterCursor(){}
};
};
#endif // InputSystemOIS_h__
+182
View File
@@ -0,0 +1,182 @@
#ifndef InputTypes_h__
#define InputTypes_h__
#include "Axis.h"
namespace LifeCore{
enum InputKey {
KEY_UNASSIGNED = 0x00,
KEY_ESCAPE = 0x01,
KEY_1 = 0x02,
KEY_2 = 0x03,
KEY_3 = 0x04,
KEY_4 = 0x05,
KEY_5 = 0x06,
KEY_6 = 0x07,
KEY_7 = 0x08,
KEY_8 = 0x09,
KEY_9 = 0x0A,
KEY_0 = 0x0B,
KEY_MINUS = 0x0C, // - on main keyboard
KEY_EQUALS = 0x0D,
KEY_BACK = 0x0E, // backspace
KEY_TAB = 0x0F,
KEY_Q = 0x10,
KEY_W = 0x11,
KEY_E = 0x12,
KEY_R = 0x13,
KEY_T = 0x14,
KEY_Y = 0x15,
KEY_U = 0x16,
KEY_I = 0x17,
KEY_O = 0x18,
KEY_P = 0x19,
KEY_LBRACKET = 0x1A,
KEY_RBRACKET = 0x1B,
KEY_RETURN = 0x1C, // Enter on main keyboard
KEY_LCONTROL = 0x1D,
KEY_A = 0x1E,
KEY_S = 0x1F,
KEY_D = 0x20,
KEY_F = 0x21,
KEY_G = 0x22,
KEY_H = 0x23,
KEY_J = 0x24,
KEY_K = 0x25,
KEY_L = 0x26,
KEY_SEMICOLON = 0x27,
KEY_APOSTROPHE = 0x28,
KEY_GRAVE = 0x29, // accent
KEY_LSHIFT = 0x2A,
KEY_BACKSLASH = 0x2B,
KEY_Z = 0x2C,
KEY_X = 0x2D,
KEY_C = 0x2E,
KEY_V = 0x2F,
KEY_B = 0x30,
KEY_N = 0x31,
KEY_M = 0x32,
KEY_COMMA = 0x33,
KEY_PERIOD = 0x34, // . on main keyboard
KEY_SLASH = 0x35, // / on main keyboard
KEY_RSHIFT = 0x36,
KEY_MULTIPLY = 0x37, // * on numeric keypad
KEY_LMENU = 0x38, // left Alt
KEY_SPACE = 0x39,
KEY_CAPITAL = 0x3A,
KEY_F1 = 0x3B,
KEY_F2 = 0x3C,
KEY_F3 = 0x3D,
KEY_F4 = 0x3E,
KEY_F5 = 0x3F,
KEY_F6 = 0x40,
KEY_F7 = 0x41,
KEY_F8 = 0x42,
KEY_F9 = 0x43,
KEY_F10 = 0x44,
KEY_NUMLOCK = 0x45,
KEY_SCROLL = 0x46, // Scroll Lock
KEY_NUMPAD7 = 0x47,
KEY_NUMPAD8 = 0x48,
KEY_NUMPAD9 = 0x49,
KEY_SUBTRACT = 0x4A, // - on numeric keypad
KEY_NUMPAD4 = 0x4B,
KEY_NUMPAD5 = 0x4C,
KEY_NUMPAD6 = 0x4D,
KEY_ADD = 0x4E, // + on numeric keypad
KEY_NUMPAD1 = 0x4F,
KEY_NUMPAD2 = 0x50,
KEY_NUMPAD3 = 0x51,
KEY_NUMPAD0 = 0x52,
KEY_DECIMAL = 0x53, // . on numeric keypad
KEY_OEM_102 = 0x56, // < > | on UK/Germany keyboards
KEY_F11 = 0x57,
KEY_F12 = 0x58,
KEY_F13 = 0x64, // (NEC PC98)
KEY_F14 = 0x65, // (NEC PC98)
KEY_F15 = 0x66, // (NEC PC98)
KEY_KANA = 0x70, // (Japanese keyboard)
KEY_ABNT_C1 = 0x73, // / ? on Portugese (Brazilian) keyboards
KEY_CONVERT = 0x79, // (Japanese keyboard)
KEY_NOCONVERT = 0x7B, // (Japanese keyboard)
KEY_YEN = 0x7D, // (Japanese keyboard)
KEY_ABNT_C2 = 0x7E, // Numpad . on Portugese (Brazilian) keyboards
KEY_NUMPADEQUALS= 0x8D, // = on numeric keypad (NEC PC98)
KEY_PREVTRACK = 0x90, // Previous Track (KEY_CIRCUMFLEX on Japanese keyboard)
KEY_AT = 0x91, // (NEC PC98)
KEY_COLON = 0x92, // (NEC PC98)
KEY_UNDERLINE = 0x93, // (NEC PC98)
KEY_KANJI = 0x94, // (Japanese keyboard)
KEY_STOP = 0x95, // (NEC PC98)
KEY_AX = 0x96, // (Japan AX)
KEY_UNLABELED = 0x97, // (J3100)
KEY_NEXTTRACK = 0x99, // Next Track
KEY_NUMPADENTER = 0x9C, // Enter on numeric keypad
KEY_RCONTROL = 0x9D,
KEY_MUTE = 0xA0, // Mute
KEY_CALCULATOR = 0xA1, // Calculator
KEY_PLAYPAUSE = 0xA2, // Play / Pause
KEY_MEDIASTOP = 0xA4, // Media Stop
KEY_VOLUMEDOWN = 0xAE, // Volume -
KEY_VOLUMEUP = 0xB0, // Volume +
KEY_WEBHOME = 0xB2, // Web home
KEY_NUMPADCOMMA = 0xB3, // , on numeric keypad (NEC PC98)
KEY_DIVIDE = 0xB5, // / on numeric keypad
KEY_SYSRQ = 0xB7,
KEY_RMENU = 0xB8, // right Alt
KEY_PAUSE = 0xC5, // Pause
KEY_HOME = 0xC7, // Home on arrow keypad
KEY_UP = 0xC8, // UpArrow on arrow keypad
KEY_PGUP = 0xC9, // PgUp on arrow keypad
KEY_LEFT = 0xCB, // LeftArrow on arrow keypad
KEY_RIGHT = 0xCD, // RightArrow on arrow keypad
KEY_END = 0xCF, // End on arrow keypad
KEY_DOWN = 0xD0, // DownArrow on arrow keypad
KEY_PGDOWN = 0xD1, // PgDn on arrow keypad
KEY_INSERT = 0xD2, // Insert on arrow keypad
KEY_DELETE = 0xD3, // Delete on arrow keypad
KEY_LWIN = 0xDB, // Left Windows key
KEY_RWIN = 0xDC, // Right Windows key
KEY_APPS = 0xDD, // AppMenu key
KEY_POWER = 0xDE, // System Power
KEY_SLEEP = 0xDF, // System Sleep
KEY_WAKE = 0xE3, // System Wake
KEY_WEBSEARCH = 0xE5, // Web Search
KEY_WEBFAVORITES= 0xE6, // Web Favorites
KEY_WEBREFRESH = 0xE7, // Web Refresh
KEY_WEBSTOP = 0xE8, // Web Stop
KEY_WEBFORWARD = 0xE9, // Web Forward
KEY_WEBBACK = 0xEA, // Web Back
KEY_MYCOMPUTER = 0xEB, // My Computer
KEY_MAIL = 0xEC, // Mail
KEY_MEDIASELECT = 0xED, // Media Select
KEY_MOUSE_OFFSET = 0xff,
KEY_MOUSE_LEFT = KEY_MOUSE_OFFSET + 0,
KEY_MOUSE_RIGHT = KEY_MOUSE_OFFSET + 1,
KEY_MOUSE_MIDDLE = KEY_MOUSE_OFFSET + 2,
KEY_MOUSE_3 = KEY_MOUSE_OFFSET + 3,
KEY_MOUSE_4 = KEY_MOUSE_OFFSET + 4,
KEY_MOUSE_5 = KEY_MOUSE_OFFSET + 5,
KEY_MOUSE_6 = KEY_MOUSE_OFFSET + 6,
KEY_MOUSE_7 =KEY_MOUSE_OFFSET + 7,
};
enum InputKeyAction{
IKA_PRESS,
IKA_RELEASE,
IKA_HOLD
};
enum InputDeviceType{
IDT_UNKNOWN = 0,
IDT_KEYBOARD = (1 << 0),
IDT_MOUSE = (1 << 1),
IDT_JOYSTICK = (1 << 2),
IDT_MAGNETOMETER = (1 << 3),
IDT_GYROSCOPE = (1 << 4)
};
}
#endif // InputTypes_h__
+209
View File
@@ -0,0 +1,209 @@
#include "LString.h"
#include <sstream>
extern int StrToInt(const String& str)
{
std::stringstream ss(str);
int val;
ss >> val;
return val;
}
extern String GetFileName(const String& path)
{
int a = path.find_last_of(PATH_SPLITTER);
if(a == -1)
return path;
int length = path.length();
return path.substr(a+1, length - a);
}
extern String GetFileName(const String& path, const String& pathSplitter)
{
int a = path.find_last_of(pathSplitter.c_str());
if(a == -1)
return path;
int length = path.length();
return path.substr(a+1, length - a);
}
extern String GetFilePath(const String& path, const String& pathSplitter)
{
int a = path.find_last_of(pathSplitter.c_str());
if(a == -1)
return path;
return path.substr(0, a);
}
extern String GetFileNameWithoutExtention(const String& path)
{
int a = path.find_last_of(_text("/"));
int b = path.find_last_of(_text("."));
if(a == -1 && b == -1)
return path;
if(b == -1)
{
int length = path.length();
return path.substr(a+1, length - a);
}
return path.substr(a+1, b-a - 1);
}
extern void GetRootFolderS(const String& path, String& folderName, String& resultPath)
{
int start = path.find_first_not_of(_text("/"));
int offset = path.find_first_of(_text("/"),start);
if(start < 0)
{
folderName = path;
resultPath = String(_text(""));
return;
}
if(offset < 0)
{
folderName = path.substr(start, path.length());
resultPath = String(_text(""));
return;
}
folderName = path.substr(start, offset - start);
resultPath = path.substr(offset, path.length() - offset);
}
extern void GetRootFolderS(const String& path, String& folderName)
{
int start = path.find_first_not_of(_text("/"));
int offset = path.find_first_of(_text("/"),start);
folderName = path.substr(start, offset - start);
}
extern String GetDirectoryName(const String& path)
{
String ret = path;
if(ret.length()<2) return ret;
while(ret.length() > 1 && (ret.c_str()[ret.length()-1]) == L'\\')
ret = ret.substr(0,ret.length()-1);
int a = ret.find_last_of(PATH_SPLITTER);
if(a == -1)
return ret;
int length = ret.length();
return ret.substr(a+1, length - a);
}
extern void SplitString(const String& text, std::vector<String>* collection)
{
int pos = 0;
int counter = 0;
const char* str = text.c_str();
while(str[counter])
{
if(str[counter] == '\n')
{
(*collection).push_back(text.substr(pos, counter - pos));
pos = counter + 1;
}
counter++;
}
int diff = text.size() - pos;
if(diff)
(*collection).push_back(text.substr(pos, diff));
}
extern void SplitString(const String& text, std::vector<String>* collection, char splitter)
{
int pos = 0;
int counter = 0;
const char* str = text.c_str();
while(str[counter])
{
if(str[counter] == splitter)
{
(*collection).push_back(text.substr(pos, counter - pos));
pos = ++counter;
//counter++;
}
counter++;
}
int diff = text.size() - pos;
if(diff)
(*collection).push_back(text.substr(pos, diff));
}
extern void SplitStringW(const std::wstring& text, std::vector<std::wstring>* collection)
{
int pos = 0;
int counter = 0;
const wchar_t* str = text.c_str();
while(str[counter])
{
if(str[counter] == L'\n')
{
(*collection).push_back(text.substr(pos, counter - pos));
pos = counter + 1;
}
counter++;
}
int diff = text.size() - pos;
if(diff)
(*collection).push_back(text.substr(pos, diff));
}
extern void SplitStringW(const std::wstring& text, std::vector<std::wstring>* collection, wchar_t splitter)
{
int pos = 0;
int counter = 0;
const wchar_t* str = text.c_str();
while(str[counter])
{
if(str[counter] == splitter)
{
(*collection).push_back(text.substr(pos, counter - pos));
pos = counter;
}
counter++;
}
int diff = text.size() - pos;
if(diff)
(*collection).push_back(text.substr(pos, diff));
}
extern void StringSerialize(const String& src, LifeCore::IMemoryStream* stm)
{
//HACK Multi byte string may be not only one byte per character
String::size_type size = src.length();
stm->Write(size);
stm->Write(src.c_str(), size);
}
extern String StringDeserialize(LifeCore::IMemoryStream* stm)
{
String::size_type size;
stm->Read(&size, sizeof(size));
char* buffer = new char[size + 1];
buffer[size] = 0;
stm->Read(buffer, size);
String val = String(buffer);
delete[] buffer;
return val;
}
extern void WCSTMBS(const wchar_t* src, String& dst)
{
int length = wcslen(src);
int len = WideCharToMultiByte(CP_ACP, 0, src, length, 0, 0,0,0);
char* buf = new char[len+1];
memset(buf,0,len+1);
WideCharToMultiByte(CP_ACP, 0, src, length, buf, len+1,0,0);
dst = String(buf);
delete[] buf;
}
extern void MBSTWCS(const String& src, std::wstring& dst)
{
int strLen = MultiByteToWideChar(CP_ACP, 0, src.c_str(), -1, NULL, 0);
wchar_t* widePath = new wchar_t[strLen];
MultiByteToWideChar(CP_ACP, 0, src.c_str(), -1, widePath, strLen);
dst = std::wstring(widePath);
delete[]widePath;
}
+75
View File
@@ -0,0 +1,75 @@
#ifndef LSTRING_H__
#define LSTRING_H__
#define _SCL_SECURE_NO_WARNINGS
#include <string>
#include <vector>
#include <Windows.h>
#include "IMemoryStream.h"
#ifdef _UNICODE
typedef std::wstring String;
#define _text(str) L##str
#define PRINT wprintf
#define STRCMP wcscmp
typedef wchar_t tchar;
#define string_size(str) (str.length() * 2)
#else
#define _text(str) str
#define PRINT printf
typedef std::string String;
typedef char tchar;
#define STRCMP strcmp
#define string_size(str) (str.length())
#endif
#ifdef WIN32
#define PATH_SPLITTER _text("\\")
#else
#define PATH_SPLITTER _text("/")
#endif
typedef std::vector<String> StringVector;
typedef std::vector<std::wstring> WStringVector;
extern int StrToInt(const String& str);
extern String GetFileName(const String& path);
extern String GetFileName(const String& path, const String& pathSplitter);
extern String GetFileNameWithoutExtention(const String& path);
extern String GetFilePath(const String& path, const String& pathSplitter);
extern void GetRootFolderS(const String& path, String& folderName, String& resultPath);
extern void GetRootFolderS(const String& path, String& folderName);
extern String GetDirectoryName(const String& path);
extern void SplitString(const String& text, std::vector<String>* collection);
extern void SplitString(const String& text, std::vector<String>* collection, char splitter);
extern void SplitStringW(const std::wstring& text, std::vector<std::wstring>* collection);
extern void SplitStringW(const std::wstring& text, std::vector<std::wstring>* collection, wchar_t splitter);
extern void WCSTMBS(const wchar_t* src, String& dst);
extern void MBSTWCS(const String& src, std::wstring& dst);
extern void StringSerialize(const String& src, LifeCore::IMemoryStream* stm);
extern String StringDeserialize(LifeCore::IMemoryStream* stm);
#define AS_STRING(omg) String(_text(##omg##))
#define STR(omg) String(_text(##omg##))
#endif
+299
View File
@@ -0,0 +1,299 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<ItemGroup>
<ClCompile Include="Array.cpp" />
<ClCompile Include="FrameCounter.cpp" />
<ClCompile Include="InputSystem.cpp" />
<ClCompile Include="IProperty.cpp" />
<ClCompile Include="IPropertyHolder.cpp" />
<ClCompile Include="log\CLog.cpp" />
<ClCompile Include="log\NLog.cpp" />
<ClCompile Include="LString.cpp" />
<ClCompile Include="math\LifeMath.cpp" />
<ClCompile Include="media\WebCamera.cpp" />
<ClCompile Include="media\WinMfFormatReader.cpp" />
<ClCompile Include="media\WinMfImageGrabber.cpp" />
<ClCompile Include="minizip\ioapi.c" />
<ClCompile Include="minizip\iowin32.c" />
<ClCompile Include="minizip\miniunz.c" />
<ClCompile Include="minizip\minizip.c" />
<ClCompile Include="minizip\mztools.c" />
<ClCompile Include="minizip\unzip.c" />
<ClCompile Include="minizip\zip.c" />
<ClCompile Include="PixelBuffer.cpp" />
<ClCompile Include="WindowPixelManager.cpp" />
<ClCompile Include="WindowWin.cpp" />
<ClCompile Include="Timer.cpp" />
<ClCompile Include="Utils.cpp" />
<ClCompile Include="vfs\fs_win\IFSContentProvider.cpp" />
<ClCompile Include="vfs\fs_win\IFSFile.cpp" />
<ClCompile Include="vfs\fs_win\IFSFolder.cpp" />
<ClCompile Include="vfs\IFileSystem.cpp" />
<ClCompile Include="vfs\pak\IPakFile.cpp" />
<ClCompile Include="vfs\pak\IPakFileContentProvider.cpp" />
<ClCompile Include="vfs\pak\IPakFolder.cpp" />
<ClCompile Include="vfs\pak\pak_io\PakFile.cpp" />
<ClCompile Include="vfs\WinFileStream.cpp" />
<ClCompile Include="vfs\zip\IZipFile.cpp" />
<ClCompile Include="vfs\zip\IZipFileContentProvider.cpp" />
<ClCompile Include="vfs\zip\IZipFolder.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="Array.h" />
<ClInclude Include="Axis.h" />
<ClInclude Include="BoundingBox3D.h" />
<ClInclude Include="Build.h" />
<ClInclude Include="Com.h" />
<ClInclude Include="Delegate.h" />
<ClInclude Include="delegate\Delegate.h" />
<ClInclude Include="delegate\Delegate_base.h" />
<ClInclude Include="DisplayMode.h" />
<ClInclude Include="Error.h" />
<ClInclude Include="FrameCounter.h" />
<ClInclude Include="ICamera.h" />
<ClInclude Include="IDataRectangle.h" />
<ClInclude Include="IDataStream.h" />
<ClInclude Include="IDevice.h" />
<ClInclude Include="IImage.h" />
<ClInclude Include="IInputSystem.h" />
<ClInclude Include="IMemoryStream.h" />
<ClInclude Include="InputDevice.h" />
<ClInclude Include="InputSystem.h" />
<ClInclude Include="IProperty.h" />
<ClInclude Include="IPropertyHolder.h" />
<ClInclude Include="IPropertyItem.h" />
<ClInclude Include="IWindow.h" />
<ClInclude Include="ISerializable.h" />
<ClInclude Include="ITransform.h" />
<ClInclude Include="IWindowDemander.h" />
<ClInclude Include="log\CLog.h" />
<ClInclude Include="log\NLog.h" />
<ClInclude Include="LString.h" />
<ClInclude Include="math\LifeMath.h" />
<ClInclude Include="math\Matrix4x4.h" />
<ClInclude Include="math\Plane.h" />
<ClInclude Include="math\Quaternion.h" />
<ClInclude Include="math\Rectangle.h" />
<ClInclude Include="math\Spline.h" />
<ClInclude Include="math\Vector2D.h" />
<ClInclude Include="math\Vector3D.h" />
<ClInclude Include="math\Vector4D.h" />
<ClInclude Include="math\vector_base.h" />
<ClInclude Include="PixelBuffer.h" />
<ClInclude Include="RawBuffer.h" />
<ClInclude Include="media\WebCamera.h" />
<ClInclude Include="media\WinMfFormatReader.h" />
<ClInclude Include="media\WinMfImageGrabber.h" />
<ClInclude Include="media\WinMfMediaType.h" />
<ClInclude Include="minizip\crypt.h" />
<ClInclude Include="minizip\ioapi.h" />
<ClInclude Include="minizip\iowin32.h" />
<ClInclude Include="minizip\mztools.h" />
<ClInclude Include="minizip\unzip.h" />
<ClInclude Include="minizip\zip.h" />
<ClInclude Include="Property.h" />
<ClInclude Include="Range.h" />
<ClInclude Include="WindowPixelManager.h" />
<ClInclude Include="WindowWin.h" />
<ClInclude Include="Singleton.h" />
<ClInclude Include="Timer.h" />
<ClInclude Include="tools\CompilerDetect.h" />
<ClInclude Include="tools\Inline.h" />
<ClInclude Include="tools\OsDetect.h" />
<ClInclude Include="Types.h" />
<ClInclude Include="Utils.h" />
<ClInclude Include="vfs\fs_win\IFSContentProvider.h" />
<ClInclude Include="vfs\fs_win\IFSFile.h" />
<ClInclude Include="vfs\fs_win\IFSFolder.h" />
<ClInclude Include="vfs\fs_win\IFSStream.h" />
<ClInclude Include="vfs\IContentProvider.h" />
<ClInclude Include="vfs\IFile.h" />
<ClInclude Include="vfs\IFileSystem.h" />
<ClInclude Include="vfs\IFolder.h" />
<ClInclude Include="vfs\pak\IPakFile.h" />
<ClInclude Include="vfs\pak\IPakFileContentProvider.h" />
<ClInclude Include="vfs\pak\IPakFolder.h" />
<ClInclude Include="vfs\pak\IPakStream.h" />
<ClInclude Include="vfs\pak\pak_io\EntryInfo.h" />
<ClInclude Include="vfs\pak\pak_io\FileEntry.h" />
<ClInclude Include="vfs\pak\pak_io\FolderEntry.h" />
<ClInclude Include="vfs\pak\pak_io\PakFile.h" />
<ClInclude Include="vfs\pak\pak_io\pakHeader.h" />
<ClInclude Include="vfs\pak\pak_io\PakTypes.h" />
<ClInclude Include="vfs\pak\pak_io\targetver.h" />
<ClInclude Include="vfs\RootFolder.h" />
<ClInclude Include="vfs\WinFileStream.h" />
<ClInclude Include="vfs\zip\IZipFile.h" />
<ClInclude Include="vfs\zip\IZipFileContentProvider.h" />
<ClInclude Include="vfs\zip\IZipFolder.h" />
<ClInclude Include="vfs\zip\IZipStream.h" />
<ClInclude Include="Window.h" />
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{E83FE0FE-36DC-4F92-B074-5A7280FE6C17}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>LifeCore</RootNamespace>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v120</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v120</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v120</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v120</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<OutDir>$(SolutionDir)\bin\</OutDir>
<IntDir>$(SolutionDir)\tmp\$(Configuration)\</IntDir>
<TargetName>$(ProjectName)_d</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<TargetName>$(ProjectName)_d</TargetName>
<OutDir>$(SolutionDir)$(ProjectName)\lib\$(Platform)\</OutDir>
<IntDir>$(SolutionDir)$(ProjectName)\tmp\$(Platform)\$(Configuration)\</IntDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<OutDir>$(SolutionDir)\bin\</OutDir>
<IntDir>$(SolutionDir)\tmp\$(Configuration)\</IntDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<OutDir>$(SolutionDir)\bin\</OutDir>
<IntDir>$(SolutionDir)\tmp\$(Configuration)\</IntDir>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>C:\nettlemath\nettlemath;$(REPO_DIR)/ois-v1-3/includes;$(REPO_DIR)/zlib-1.2.5/</AdditionalIncludeDirectories>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
<MinimalRebuild>false</MinimalRebuild>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
<Lib>
<AdditionalLibraryDirectories>
</AdditionalLibraryDirectories>
<AdditionalDependencies>
</AdditionalDependencies>
</Lib>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>$(REPO_DIR)/ois-v1-3/includes;$(REPO_DIR)/zlib-1.2.5</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>C:\nettlemath\nettlemath;$(REPO_DIR)/ois-v1-3/includes;$(REPO_DIR)/zlib-1.2.5/</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
<Lib>
<AdditionalDependencies>OIS_static.lib</AdditionalDependencies>
<AdditionalLibraryDirectories>$(REPO_DIR)\ois-v1-3\lib\</AdditionalLibraryDirectories>
</Lib>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>$(REPO_DIR)/ois-v1-3/includes</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
+10
View File
@@ -0,0 +1,10 @@
/*
#include "PixelBuffer.h"
namespace LifeCore {
PixelBuffer::PixelBuffer(uint32 _format, uint32 _width, uint32 _height, uint8 _bpp, uint32 _stride)
:format(format), width(_width), height(_height), bpp(_bpp), stride(_stride), RawBuffer<uint8>(_stride * _height)
{
}
}*/
+21
View File
@@ -0,0 +1,21 @@
/*
#ifndef PixelBuffer_h__
#define PixelBuffer_h__
#include "RawBuffer.h"
#include "Types.h"
namespace LifeCore {
class PixelBuffer : public RawBuffer<uint8> {
public:
PixelBuffer(uint32 _format, uint32 _width, uint32 _height, uint8 _bpp, uint32 _stride);
private:
uint32 format;
uint32 width;
uint32 height;
uint8 bpp;
uint32 stride;
};
}
#endif // PixelBuffer_h__
*/
+183
View File
@@ -0,0 +1,183 @@
#ifndef Property_h__
#define Property_h__
#include "delegate/Delegate.h"
#include "IProperty.h"
#include "Utils.h"
#include <assert.h>
namespace LifeCore
{
#define DEFINE_PROPERTY(___name, ___type) \
Core::Property<##___type##>*## ___name;
#define ALLOC_PROPERTY(_name, _type) \
new Core::Property<##_type##>(STR(#_name));
template<typename T>
class Property : public IProperty
{
public:
Property()
{
}
void Set(const void* src, size_t size){
//size must be equal
assert(sizeof(T) == size);
memcpy(&value, src, size);
}
const void* GetPtr(){
return &value;
}
bool Serialize(LifeCore::IMemoryStream* stm)
{
StringSerialize(name, stm);
stm->Write(size_t(sizeof(value)));
stm->Write(&value, sizeof(value));
return true;
}
bool Deserialize(LifeCore::IMemoryStream* stm)
{
name = StringDeserialize(stm);
size_t data_len;
stm->Read(&data_len, sizeof(data_len));
stm->Read(&value, data_len);
return true;
}
const Property<T>& operator=(const T& other)
{
value = other;
OnValueChanged();
return *this;
}
const Property<T>& operator=(const Property<T>& other)
{
value = other.value;
OnValueChanged();
return *this;
}
const T& operator()()
{
return value;
}
String ToString() { return STR(typeid(T).name()); };
void FromString(const String& str){}
const String& GetName()
{
return name;
}
private:
String name;
T value;
};
bool Property<String>::Serialize(LifeCore::IMemoryStream* stm)
{
StringSerialize(name, stm);
StringSerialize(value, stm);
return true;
}
bool Property<String>::Deserialize(LifeCore::IMemoryStream* stm)
{
name = StringDeserialize(stm);
value = StringDeserialize(stm);
return true;
}
void Property<String>::FromString(const String& str)
{
*this = str;
}
void Property<int8>::FromString(const String& str)
{
*this = StringToInt8(str);
}
void Property<int16>::FromString(const String& str)
{
*this = StringToInt16(str);
}
void Property<int32>::FromString(const String& str)
{
*this = StringToInt32(str);
}
void Property<int64>::FromString(const String& str)
{
*this = StringToInt64(str);
}
void Property<uint8>::FromString(const String& str)
{
*this = StringToUInt8(str);
}
void Property<uint16>::FromString(const String& str)
{
*this = StringToUInt16(str);
}
void Property<uint32>::FromString(const String& str)
{
*this = StringToUInt32(str);
}
void Property<uint64>::FromString(const String& str)
{
*this = StringToUInt64(str);
}
void Property<float>::FromString(const String& str)
{
*this = StringToFloat(str);
}
void Property<double>::FromString(const String& str)
{
*this = StringToDouble(str);
}
String Property<String>::ToString()
{
return value;
}
String Property<int8>::ToString()
{
return Int8ToString(value);
}
String Property<int16>::ToString()
{
return Int16ToString(value);
}
String Property<int32>::ToString()
{
return Int32ToString(value);
}
String Property<int64>::ToString()
{
return Int64ToString(value);
}
String Property<uint8>::ToString()
{
return UInt8ToString(value);
}
String Property<uint16>::ToString()
{
return UInt16ToString(value);
}
String Property<uint32>::ToString()
{
return UInt32ToString(value);
}
String Property<uint64>::ToString()
{
return UInt64ToString(value);
}
String Property<bool>::ToString()
{
return BoolToString(value);
}
String Property<float>::ToString()
{
return FloatToString(value);
}
String Property<double>::ToString()
{
return DoubleToString(value);
}
}
#endif // Property_h__
+20
View File
@@ -0,0 +1,20 @@
#ifndef RANGE_H__
#define RANGE_H__
namespace LifeCore
{
template<typename T>
class Range
{
public:
T RangeStart;
T RangeEnd;
Range(T _start, T _end)
{
RangeStart = _start;
RangeEnd = _end;
}
};
}
#endif
+30
View File
@@ -0,0 +1,30 @@
#ifndef RawBuffer_h__
#define RawBuffer_h__
#include <memory>
#include "media/WinMfMediaType.h"
namespace LifeCore {
template<typename T>
class RawBuffer {
public:
RawBuffer(size_t size, WinMfMediaType _type)
:dataSize(size), Type(_type)
{
data = new T[size];
}
void SetData(void* pData) {
memcpy_s(data, dataSize, pData, dataSize);
}
virtual ~RawBuffer() {
delete[] data;
}
WinMfMediaType Type;
T *data;
size_t dataSize;
protected:
};
}
#endif // RawBuffer_h__
+27
View File
@@ -0,0 +1,27 @@
#ifndef ___SINGLETON_H__
#define ___SINGLETON_H__
#include <memory>
template <typename T>
class Singleton
{
private:
static std::auto_ptr<T> instance;
Singleton(const Singleton& rval){}
public:
Singleton(){}
virtual ~Singleton(){}
static T *me()
{
if (!instance.get())
instance.reset(new T());
return instance.get();
}
};
template <class T>
std::auto_ptr<T> Singleton<T>::instance;
#endif // ___SINGLETON_H__
+60
View File
@@ -0,0 +1,60 @@
#include "Timer.h"
#include <Windows.h>
//#define TIMER_TGT
namespace LifeCore
{
Timer::Timer()
:timeElapsed(0)
{
#ifdef TIMER_TGT
if(refCount == 0)
timeBeginPeriod(1);
refCount++;
#else
QueryPerformanceFrequency((LARGE_INTEGER *)&perfFreq);
#endif
}
Timer::~Timer()
{
#ifdef TIMER_TGT
refCount--;
if(refCount == 0)
timeEndPeriod(1);
#endif
}
void Timer::Start()
{
#ifdef TIMER_TGT
lastTime = timeGetTime();
#else
DWORD_PTR old_mask = SetThreadAffinityMask(GetCurrentThread(), 0);
QueryPerformanceCounter((LARGE_INTEGER *)&lastTime);
SetThreadAffinityMask(GetCurrentThread(), old_mask);
#endif
}
void Timer::Stop()
{
#ifdef TIMER_TGT
curTime = timeGetTime();
diff = curTime - lastTime;
timeElapsed = 1.0 / (double)diff; //time in SECONDS
#else
DWORD_PTR old_mask = SetThreadAffinityMask(GetCurrentThread(), 0);
QueryPerformanceCounter((LARGE_INTEGER *)&curTime);
SetThreadAffinityMask(GetCurrentThread(), old_mask);
if(lastTime == 0)
timeElapsed = 0;
else
{
timeElapsed = (float)((double)(curTime - lastTime) / (double)perfFreq);
}
#endif
}
float Timer::getTimeElapsed()
{
return timeElapsed;
}
}
+31
View File
@@ -0,0 +1,31 @@
#ifndef Timer_h__
#define Timer_h__
#define TIMER_QPC
#ifndef TIMER_QPC
#define TIMER_TGT
#define TIMER_TYPES DWORD
#else
#define TIMER_TYPES __int64
#endif
namespace LifeCore
{
static int refCount = 0;
class Timer
{
private:
TIMER_TYPES lastTime, curTime, diff, perfFreq;
float timeElapsed;
public:
Timer();
~Timer();
void Start();
void Stop();
float getTimeElapsed();
};
}
#endif // Timer_h__
+36
View File
@@ -0,0 +1,36 @@
#ifndef Types_h__
#define Types_h__
#include "LString.h"
typedef unsigned char _bool;
typedef unsigned char byte;
#undef INLINE
#ifdef _WIN32
#ifdef _MSC_VER
#define INLINE __forceinline
#endif
#else
#ifdef __GNUC__
#define INLINE __attribute__((always_inline))
#endif
#endif
#ifndef INLINE
#define INLINE inline
#endif
typedef unsigned long long uint64;
typedef unsigned int uint32;
typedef unsigned short uint16;
typedef unsigned char uint8;
typedef long long int64;
typedef int int32;
typedef short int16;
typedef char int8;
typedef float real;
#endif // Types_h__
+221
View File
@@ -0,0 +1,221 @@
#include "Utils.h"
#include <sstream>
extern int8 StringToInt8(const String& str){
int32 val2;
std::stringstream ss;
ss << str;
ss >> val2;
return (int8)val2;
}
extern uint8 StringToUInt8(const String& str)
{
uint32 val2;
//sscanf(str.c_str(), "%hu", &val2);
std::stringstream ss;
ss << str;
ss >> val2;
return (uint8)val2;
}
extern int16 StringToInt16(const String& str)
{
int16 val2;
//sscanf(str.c_str(), "%hi", &val2);
std::stringstream ss;
ss << str;
ss >> val2;
return val2;
}
extern uint16 StringToUInt16(const String& str)
{
uint16 val2;
//sscanf(str.c_str(), "%hu", &val2);
std::stringstream ss;
ss << str;
ss >> val2;
return val2;
}
extern int32 StringToInt32(const String& str)
{
int32 val2;
//sscanf(str.c_str(), "%i", &val2);
std::stringstream ss;
ss << str;
ss >> val2;
return val2;
}
extern uint32 StringToUInt32(const String& str)
{
uint32 val2;
//sscanf(str.c_str(), "%u", &val2);
std::stringstream ss;
ss << str;
ss >> val2;
return val2;
}
extern int64 StringToInt64(const String& str)
{
int64 val2;
//sscanf(str.c_str(), "%l", &val2);
std::stringstream ss;
ss << str;
ss >> val2;
return val2;
}
extern uint64 StringToUInt64(const String& str)
{
uint64 val2;
//sscanf(str.c_str(), "%ul", &val2);
std::stringstream ss;
ss << str;
ss >> val2;
return val2;
}
extern float StringToFloat(const String& str)
{
float val2;
//sscanf(str.c_str(), "%f", &val);
std::stringstream ss;
ss << str;
ss >> val2;
return val2;
}
extern double StringToDouble(const String& str)
{
float val2;
//sscanf(str.c_str(), "%d", &val);
std::stringstream ss;
ss << str;
ss >> val2;
return val2;
}
extern String Int8ToString(int8 value)
{
/*char buffer[16];
memset(buffer,0,16);
sprintf(buffer, "%hi", value);*/
std::stringstream ss;
ss << value;
return ss.str();
}
extern String Int16ToString(int16 value)
{
/*char buffer[16];
memset(buffer,0,16);
sprintf(buffer, "%hi", value);
return String(buffer);*/
std::stringstream ss;
ss << value;
return ss.str();
}
extern String Int32ToString(int32 value)
{
/*char buffer[16];
memset(buffer,0,16);
sprintf(buffer, "%i", value);
return String(buffer);*/
std::stringstream ss;
ss << value;
return ss.str();
}
extern String Int64ToString(int64 value)
{
/*char buffer[32];
memset(buffer,0,32);
sprintf(buffer, "%li", value);
return String(buffer);*/
std::stringstream ss;
ss << value;
return ss.str();
}
extern String UInt8ToString(uint8 value)
{
/*char buffer[16];
memset(buffer,0,16);
sprintf(buffer, "%hu", value);
return String(buffer);*/
std::stringstream ss;
ss << value;
return ss.str();
}
extern String UInt16ToString(uint16 value)
{
/*char buffer[16];
memset(buffer,0,16);
sprintf(buffer, "%hu", value);
return String(buffer);*/
std::stringstream ss;
ss << value;
return ss.str();
}
extern String UInt32ToString(uint32 value)
{
/*char buffer[16];
memset(buffer,0,16);
sprintf(buffer, "%u", value);
return String(buffer);*/
std::stringstream ss;
ss << value;
return ss.str();
}
extern String UInt64ToString(uint32 value)
{
/*char buffer[32];
memset(buffer,0,32);
sprintf(buffer, "%lu", value);
return String(buffer);*/
std::stringstream ss;
ss << value;
return ss.str();
}
extern String FloatToString(float val)
{
/*char buffer[32];
memset(buffer,0,32);
sprintf(buffer, "%f", val);
return String(buffer);*/
std::stringstream ss;
ss << val;
return ss.str();
}
extern String DoubleToString(double val)
{
/*char buffer[64];
memset(buffer,0,64);
sprintf(buffer, "%d", val);
return String(buffer);*/
std::stringstream ss;
ss << val;
return ss.str();
}
extern String BoolToString(bool value)
{
return value == true ? STR("true") : STR("false");
}
extern bool StringToBool(const String& str)
{
String strCopy = str;
std::transform(strCopy.begin(), strCopy.end(), strCopy.begin(), ::tolower);
return str == STR("true") ? true : false;
}
+63
View File
@@ -0,0 +1,63 @@
#ifndef Utils_h__
#define Utils_h__
#include "Types.h"
#include "LString.h"
#include <stdio.h>
#include <algorithm>
#include <cctype>
//TODO fix me, plz, cuz I'm just copy of int16 conversion!
extern int8 StringToInt8(const String& str);
extern uint8 StringToUInt8(const String& str);
extern int16 StringToInt16(const String& str);
extern uint16 StringToUInt16(const String& str);
extern int32 StringToInt32(const String& str);
extern uint32 StringToUInt32(const String& str);
extern int64 StringToInt64(const String& str);
extern uint64 StringToUInt64(const String& str);
extern float StringToFloat(const String& str);
extern double StringToDouble(const String& str);
extern String Int8ToString(int8 value);
extern String Int16ToString(int16 value);
extern String Int32ToString(int32 value);
extern String Int64ToString(int32 value);
extern String UInt8ToString(uint8 value);
extern String UInt16ToString(uint16 value);
extern String UInt32ToString(uint32 value);
extern String UInt64ToString(uint32 value);
extern String FloatToString(float val);
extern String DoubleToString(double val);
extern String BoolToString(bool value);
extern bool StringToBool(const String& str);
template <class T> void SafeRelease(T **ppT) {
if(*ppT) {
(*ppT)->Release();
*ppT = NULL;
}
}
#endif // Utils_h__
+36
View File
@@ -0,0 +1,36 @@
#ifndef Window_h__
#define Window_h__
#include "IWindow.h"
#include "delegate/Delegate.h"
#include "Build.h"
#include "LString.h"
#include "DisplayMode.h"
#include "IWindowDemander.h"
#include "IInputSystem.h"
namespace LifeCore {
class Window : public IWindow {
public:
//events
EVENT(ExitEvent);
ExitEvent Event_Quit;
EVENT1(WindowEvent, IWindow*);
WindowEvent Event_Resize;
WindowEvent Event_SwitchFullscreen;
WindowEvent Event_Deactivate;
WindowEvent Event_Activate;
protected:
bool bCursorVisible;
bool bModeSwitching;
bool bFullscreen;
bool bActive;
int width;
int height;
String caption;
DisplayMode fsMode;
};
}
#endif // Window_h__
+34
View File
@@ -0,0 +1,34 @@
#include "WindowPixelManager.h"
namespace LifeCore {
WindowPixelManager::WindowPixelManager(WindowWin* wnd, int bpp)
:window(wnd)
{
hwnd = (HWND)(window->GetWindowHandle());
::ZeroMemory(&bitmapInfo, sizeof(BITMAPINFOHEADER));
bitmapInfo.biSize = sizeof(BITMAPINFOHEADER);
bitmapInfo.biWidth = wnd->GetWidth();
bitmapInfo.biHeight = -wnd->GetHeight();
bitmapInfo.biPlanes = 1;
bitmapInfo.biBitCount = bpp;
bitmapInfo.biCompression = 0;
bitmapInfo.biSizeImage = wnd->GetWidth() * wnd->GetHeight() * (bpp / 8);
info.bmiHeader = bitmapInfo;
context = ::GetDC(hwnd);
}
void WindowPixelManager::SetPixels(int width, int height, void* pixels) {
bitmapInfo.biWidth = width;
bitmapInfo.biHeight = -height;
bitmapInfo.biSizeImage = width * height * (bitmapInfo.biBitCount / 8);
info.bmiHeader = bitmapInfo;
SetDIBitsToDevice(context, 0, 0, width, height, 0, 0, 0, height, pixels, &info, 0);
}
/**/
}
+20
View File
@@ -0,0 +1,20 @@
#ifndef WINDOW_PIXEL_MANAGER_H__
#define WINDOW_PIXEL_MANAGER_H__
#include "WindowWin.h"
#include <Windows.h>
namespace LifeCore {
class WindowPixelManager {
public:
WindowPixelManager(WindowWin* wnd, int bpp);
void SetPixels(int width, int height, void* pixels);
private:
WindowWin* window;
BITMAPINFOHEADER bitmapInfo;
BITMAPINFO info;
HWND hwnd;
HDC context;
};
}
#endif
+548
View File
@@ -0,0 +1,548 @@
#include "WindowWin.h"
#define L_WIN32
#include <windows.h>
#include "log/NLog.h"
namespace LifeCore {
LRESULT __stdcall WndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam);
WindowWin::WindowWin() {
bFullscreen = false;
bActive = true;
bModeSwitching = false;
bCursorVisible = true;
bAltEnterLocked = false;
width = 256;
height = 256;
g_hInst = GetModuleHandle(NULL);
g_hwnd = NULL;
//memset(&g_wndClass,0,sizeof(WNDCLASSEX));
WNDCLASSEX g_wndClass = { NULL };
g_wndClass.cbSize = sizeof(WNDCLASSEX);
g_wndClass.cbClsExtra = NULL;
g_wndClass.cbWndExtra = NULL;
g_wndClass.hbrBackground = (HBRUSH)GetStockObject(1);
g_wndClass.hCursor = (HCURSOR)LoadCursor(NULL, IDC_ARROW);
g_wndClass.hIcon = LoadIcon(g_hInst, IDI_APPLICATION);
g_wndClass.hIconSm = LoadIcon(g_hInst, IDI_APPLICATION);
g_wndClass.hInstance = g_hInst;
g_wndClass.lpfnWndProc = WndProc;
g_wndClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
g_wndClass.lpszMenuName = NULL;
g_wndClass.lpszClassName = _text("Onotole");
if(!RegisterClassEx(&g_wndClass)) {
MessageBox(g_hwnd, _text("Can not create window class! We all gonna die!!"), _text("OH SHIT!"), MB_OK);
}
//calculate window size
RECT NewWindowSize;
NewWindowSize.top = 30;
NewWindowSize.left = 300;
NewWindowSize.bottom = NewWindowSize.top + height;
NewWindowSize.right = NewWindowSize.left + width;
AdjustWindowRect(&NewWindowSize, WS_OVERLAPPEDWINDOW, false);
/*WS_MINIMIZEBOX
WS_MAXIMIZEBOX*/
if(!(g_hwnd = CreateWindowEx(NULL, _text("Onotole"), _text("LifeEngine render window"), WS_THICKFRAME,
NewWindowSize.left, NewWindowSize.top, NewWindowSize.right - NewWindowSize.left, NewWindowSize.bottom - NewWindowSize.top, NULL, NULL, g_hInst, NULL))) {
MessageBox(g_hwnd, _text("Can not create window! We all gonna die!!"), _text("HOLY SHIT!"), MB_OK);
}
ShowWindow(g_hwnd, SW_SHOWNORMAL);
SetForegroundWindow(g_hwnd);
SetFocus(g_hwnd);
ZeroMemory(&mode, sizeof(DEVMODE));
mode.dmSize = sizeof(DEVMODE);
EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &mode);
WindowWin* ptr = this;
long val = (long)ptr;
SetWindowLongPtr(g_hwnd, GWLP_USERDATA, val);
fsMode.width = 640;
fsMode.height = 480;
fsMode.refreshRate = 60;
fsMode.bpp = 4;
CenterWindow();
}
bool WindowWin::IsKeyPressed(KeyCodes::Key key) {
return false;
}
void WindowWin::Update() {
#ifdef L_WIN32
MSG msg = { 0 };
while(PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) {
switch(msg.message) {
case WM_QUIT:
{
Event_Quit.Invoke();
//exit(0);
}
break;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
#endif
}
void WindowWin::SetCaption(const String& val) {
caption = val;
SetWindowText(g_hwnd, caption.c_str());
}
void WindowWin::SetFullScreen(bool state) {
bFullscreen = state;
}
bool WindowWin::IsFullScreen() {
return bFullscreen;
}
WindowWin::~WindowWin(void) {
ChangeDisplaySettings(&mode, 0);
}
void WindowWin::OnActivate() {
bActive = true;
Event_Activate.Invoke(this);
}
void WindowWin::OnDeactivate() {
bActive = false;
Event_Deactivate.Invoke(this);
}
void WindowWin::OnResize() {
if(!IsFullScreen() || !bModeSwitching) {
RECT r;
::GetClientRect(g_hwnd, &r);
width = r.right - r.left;
height = r.bottom - r.top;
}
Event_Resize.Invoke(this);
}
bool WindowWin::IsActive() {
return bActive;
}
bool WindowWin::IsModeSwitching() {
return bModeSwitching;
}
void WindowWin::SetCursorVisible(bool state) {
bCursorVisible = state;
}
bool WindowWin::IsCursorVisible() {
return bCursorVisible;
}
bool WindowWin::SwitchMode(bool fullscreen) {
bFullscreen = fullscreen;
if(bFullscreen) {
bModeSwitching = true;
DEVMODE fmode;
ZeroMemory(&fmode, sizeof(DEVMODE));
fmode.dmSize = sizeof(DEVMODE);
fmode.dmPelsWidth = fsMode.width;
fmode.dmPelsHeight = fsMode.height;
fmode.dmBitsPerPel = mode.dmBitsPerPel;
fmode.dmDisplayFrequency = fsMode.refreshRate;
fmode.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL | DM_DISPLAYFREQUENCY;
//if(ChangeDisplaySettings(&fmode,0)!= DISP_CHANGE_SUCCESSFUL)
// return false;
SetWindowLong(g_hwnd, GWL_EXSTYLE, WS_EX_APPWINDOW | WS_EX_TOPMOST);
SetWindowLong(g_hwnd, GWL_STYLE, WS_POPUP);
SetWindowPos(g_hwnd, HWND_TOPMOST, 0, 0, fsMode.width, fsMode.height, SWP_SHOWWINDOW | SWP_FRAMECHANGED);
bModeSwitching = false;
} else {
//if(ChangeDisplaySettings(&mode_window,0)!= DISP_CHANGE_SUCCESSFUL)
// return false;
SetWindowLong(g_hwnd, GWL_EXSTYLE, WS_EX_APPWINDOW);
SetWindowLong(g_hwnd, GWL_STYLE, WS_OVERLAPPEDWINDOW);
SetSize(width, height);
CenterWindow();
}
Event_SwitchFullscreen.Invoke(this);
return true;
}
void WindowWin::CenterWindow() {
int mx = GetSystemMetrics(SM_CXSCREEN);
int my = GetSystemMetrics(SM_CYSCREEN);
int nx = (mx - width) / 2;
int ny = (my - height) / 2;
SetWindowPos(g_hwnd, NULL, nx, ny, -1, -1,
SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
}
void WindowWin::SetFullscreenMode(LifeCore::DisplayMode mode) {
fsMode = mode;
}
void WindowWin::SetSize(int w, int h) {
if(!IsFullScreen()) {
width = w;
height = h;
RECT NewWindowSize;
NewWindowSize.top = 50;
NewWindowSize.left = 50;
NewWindowSize.bottom = NewWindowSize.top + h;
NewWindowSize.right = NewWindowSize.left + w;
AdjustWindowRect(&NewWindowSize, WS_OVERLAPPEDWINDOW, false);
SetWindowPos(g_hwnd, HWND_TOP, NewWindowSize.left, NewWindowSize.top, NewWindowSize.right - NewWindowSize.left, NewWindowSize.bottom - NewWindowSize.top, SWP_SHOWWINDOW | SWP_FRAMECHANGED);
//::MoveWindow(g_hwnd,NewWindowSize.left, NewWindowSize.top, NewWindowSize.right - NewWindowSize.left, NewWindowSize.bottom - NewWindowSize.top, true);
CenterWindow();
}
}
KeyCodes::Key WindowWin::ConvertKeyCode(unsigned long key_code) {
switch(key_code) {
case VK_ESCAPE:
return KeyCodes::KEY_ESCAPE;
case VK_F1:
return KeyCodes::KEY_F1;
case VK_F2:
return KeyCodes::KEY_F2;
case VK_F3:
return KeyCodes::KEY_F3;
case VK_F4:
return KeyCodes::KEY_F4;
case VK_F5:
return KeyCodes::KEY_F5;
case VK_F6:
return KeyCodes::KEY_F6;
case VK_F7:
return KeyCodes::KEY_F7;
case VK_F8:
return KeyCodes::KEY_F8;
case VK_F9:
return KeyCodes::KEY_F9;
case VK_F10:
return KeyCodes::KEY_F10;
case VK_F11:
return KeyCodes::KEY_F11;
case VK_F12:
return KeyCodes::KEY_F12;
case VK_SNAPSHOT:
return KeyCodes::KEY_PRINT_SCREEN;
case VK_SCROLL:
return KeyCodes::KEY_SCROLL_LOCK;
case VK_PAUSE:
return KeyCodes::KEY_PAUSE;
case VK_OEM_3:
return KeyCodes::KEY_TILDE;
case 0x30:
return KeyCodes::KEY_1;
case 0x31:
return KeyCodes::KEY_2;
case 0x32:
return KeyCodes::KEY_3;
case 0x33:
return KeyCodes::KEY_4;
case 0x34:
return KeyCodes::KEY_5;
case 0x35:
return KeyCodes::KEY_6;
case 0x36:
return KeyCodes::KEY_7;
case 0x37:
return KeyCodes::KEY_8;
case 0x38:
return KeyCodes::KEY_9;
case 0x39:
return KeyCodes::KEY_0;
case 0xBD:
return KeyCodes::KEY_MINUS;
case 0xBB:
return KeyCodes::KEY_EQUAL;
case VK_BACK:
return KeyCodes::KEY_BACKSPACE;
case VK_TAB:
return KeyCodes::KEY_TAB;
case VK_CAPITAL:
return KeyCodes::KEY_CAPS_LOCK;
case VK_SHIFT:
return KeyCodes::KEY_SHIFT;
case VK_CONTROL:
return KeyCodes::KEY_CONTROL;
case VK_LWIN:
return KeyCodes::KEY_META_LEFT;
case VK_RWIN:
return KeyCodes::KEY_META_RIGHT;
case VK_MENU:
return KeyCodes::KEY_ALT;
case VK_SPACE:
return KeyCodes::KEY_SPACE;
case VK_APPS:
return KeyCodes::KEY_MENU;
case VK_RETURN:
return KeyCodes::KEY_ENTER;
case 0x41:
return KeyCodes::KEY_A;
case 0x42:
return KeyCodes::KEY_B;
case 0x43:
return KeyCodes::KEY_C;
case 0x44:
return KeyCodes::KEY_D;
case 0x45:
return KeyCodes::KEY_E;
case 0x46:
return KeyCodes::KEY_F;
case 0x47:
return KeyCodes::KEY_G;
case 0x48:
return KeyCodes::KEY_H;
case 0x49:
return KeyCodes::KEY_I;
case 0x4A:
return KeyCodes::KEY_J;
case 0x4B:
return KeyCodes::KEY_K;
case 0x4C:
return KeyCodes::KEY_L;
case 0x4D:
return KeyCodes::KEY_M;
case 0x4E:
return KeyCodes::KEY_N;
case 0x4F:
return KeyCodes::KEY_O;
case 0x50:
return KeyCodes::KEY_P;
case 0x51:
return KeyCodes::KEY_Q;
case 0x52:
return KeyCodes::KEY_R;
case 0x53:
return KeyCodes::KEY_S;
case 0x54:
return KeyCodes::KEY_T;
case 0x55:
return KeyCodes::KEY_U;
case 0x56:
return KeyCodes::KEY_V;
case 0x57:
return KeyCodes::KEY_W;
case 0x58:
return KeyCodes::KEY_X;
case 0x59:
return KeyCodes::KEY_Y;
case 0x5A:
return KeyCodes::KEY_Z;
case VK_OEM_4:
return KeyCodes::KEY_BRACKET_LEFT;
case VK_OEM_6:
return KeyCodes::KEY_BRACKET_RIGHT;
case VK_OEM_5:
return KeyCodes::KEY_BACKSLASH;
case VK_OEM_1:
return KeyCodes::KEY_SEMICOLON;
case VK_OEM_7:
return KeyCodes::KEY_APOSTROPHE;
case 0xBC:
return KeyCodes::KEY_COMMA;
case 0xBE:
return KeyCodes::KEY_DOT;
case VK_OEM_2:
return KeyCodes::KEY_SLASH;
case VK_INSERT:
return KeyCodes::KEY_INSERT;
case VK_DELETE:
return KeyCodes::KEY_DELETE;
case VK_HOME:
return KeyCodes::KEY_HOME;
case VK_END:
return KeyCodes::KEY_END;
case VK_PRIOR:
return KeyCodes::KEY_PAGE_UP;
case VK_NEXT:
return KeyCodes::KEY_PAGE_DOWN;
case VK_UP:
return KeyCodes::KEY_UP;
case VK_LEFT:
return KeyCodes::KEY_LEFT;
case VK_DOWN:
return KeyCodes::KEY_DOWN;
case VK_RIGHT:
return KeyCodes::KEY_RIGHT;
case VK_NUMLOCK:
return KeyCodes::KEY_NUM_LOCK;
case VK_ADD:
return KeyCodes::KEY_NUM_ADD;
case VK_SUBTRACT:
return KeyCodes::KEY_NUM_SUBTRACT;
case VK_MULTIPLY:
return KeyCodes::KEY_NUM_MULTIPLY;
case VK_DIVIDE:
return KeyCodes::KEY_NUM_DIVIDE;
case VK_NUMPAD0:
return KeyCodes::KEY_NUM_0;
case VK_NUMPAD1:
return KeyCodes::KEY_NUM_1;
case VK_NUMPAD2:
return KeyCodes::KEY_NUM_2;
case VK_NUMPAD3:
return KeyCodes::KEY_NUM_3;
case VK_NUMPAD4:
return KeyCodes::KEY_NUM_4;
case VK_NUMPAD5:
return KeyCodes::KEY_NUM_5;
case VK_CLEAR:
return KeyCodes::KEY_NUM_SPECIAL;
case VK_NUMPAD6:
return KeyCodes::KEY_NUM_6;
case VK_NUMPAD7:
return KeyCodes::KEY_NUM_7;
case VK_NUMPAD8:
return KeyCodes::KEY_NUM_8;
case VK_NUMPAD9:
return KeyCodes::KEY_NUM_9;
case VK_DECIMAL:
return KeyCodes::KEY_NUM_DECIMAL;
default:
return KeyCodes::UNKNOWN_KEY;
}
}
LRESULT __stdcall WndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) {
switch(message) {
case WM_SIZE:
{
//íå ðåñàéçèì äåâàéñ åñëè îêíî ñâ¸ðíóòî
if(wparam != SIZE_MINIMIZED) {
long val = GetWindowLongPtr(hwnd, GWLP_USERDATA);
if(val) {
WindowWin* wnd = (WindowWin*)val;
wnd->OnResize();
}
}
}
break;
case WM_SETCURSOR:
{
static bool hiddencursor = false;
WORD ht = LOWORD(lparam);
long val = GetWindowLongPtr(hwnd, GWLP_USERDATA);
if(val) {
WindowWin* wnd = (WindowWin*)val;
if(wnd->IsCursorVisible()) {
ShowCursor(true);
} else {
if(HTCLIENT == ht && !hiddencursor) {
hiddencursor = true;
ShowCursor(false);
} else if(HTCLIENT != ht && hiddencursor) {
hiddencursor = false;
ShowCursor(true);
}
}
}
}
break;
case WM_ACTIVATEAPP:
{
//if(wparam == TRUE)
long val = GetWindowLongPtr(hwnd, GWLP_USERDATA);
if(val) {
WindowWin* wnd = (WindowWin*)val;
if(wparam!= 0) {
wnd->OnActivate();
} else {
wnd->OnDeactivate();
}
}
}
break;
case WM_ACTIVATE: //Catch Alt + Tab
{
switch(wparam) {
case WA_ACTIVE:
{
long val = GetWindowLongPtr(hwnd, GWLP_USERDATA);
if(val) {
WindowWin* wnd = (WindowWin*)val;
wnd->OnActivate();
}
}
break;
case WA_INACTIVE:
{
long val = GetWindowLongPtr(hwnd, GWLP_USERDATA);
if(val) {
WindowWin* wnd = (WindowWin*)val;
wnd->OnDeactivate();
}
}
break;
}
}
break;
case WM_DESTROY:
PostQuitMessage(0);
DestroyWindow(hwnd);
break;
case WM_SYSKEYDOWN:
switch(wparam) {
case VK_RETURN:
{
if(GetKeyState(VK_MENU)) //Alt + Enter
{
long val = GetWindowLongPtr(hwnd, GWLP_USERDATA);
if(val) {
WindowWin* wnd = (WindowWin*)val;
if(!wnd->IsAltEnterLocked()) {
wnd->SetAltEnterLocked(true);
wnd->SwitchMode(!wnd->IsFullScreen());
}
}
}
}
break;
}
break;
case WM_SYSKEYUP:
{
switch(wparam) {
case VK_RETURN:
{
long val = GetWindowLongPtr(hwnd, GWLP_USERDATA);
if(val) {
WindowWin* wnd = (WindowWin*)val;
wnd->SetAltEnterLocked(false);
}
}
break;
}
}
break;
case WM_KEYDOWN:
switch(wparam) {
case VK_ESCAPE:
//PostQuitMessage(0);
exit(0);
break;
}
}
return DefWindowProc(hwnd, message, wparam, lparam);
}
}
+74
View File
@@ -0,0 +1,74 @@
#pragma once
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include "Window.h"
namespace LifeCore{
class WindowWin : public Window
{
public:
/*virtual ~RenderWindow(void) {}
virtual void Update() = 0;
virtual void SetCaption(const String& caption) = 0;
virtual int GetWindowHandle() = 0;
virtual int GetWidth() = 0;
virtual int GetHeight() = 0;
virtual const String& GetCaption() = 0;*/
WindowWin();
~WindowWin(void);
bool IsKeyPressed(KeyCodes::Key key);
//void AddWindowDemander(IWindowDemander* demander);
void Update();
void SetCaption(const String& caption);
int GetWindowHandle(){return (int)g_hwnd;}
void SetSize(int w, int h);
bool IsFullScreen();
void SetFullScreen(bool state);
bool SwitchMode(bool fullscreen);
void SetFullscreenMode(LifeCore::DisplayMode mode);
void OnActivate();
void OnDeactivate();
void OnResize();
//void OnInput();
bool IsActive();
bool IsModeSwitching();
void SetCursorVisible(bool state);
bool IsCursorVisible();
void CenterWindow();
int GetWidth()
{
return width;
}
virtual int GetHeight()
{
return height;
}
const String& GetCaption()
{
return caption;
}
void SetAltEnterLocked(bool state)
{
bAltEnterLocked = state;
}
bool IsAltEnterLocked()
{
return bAltEnterLocked;
}
protected:
KeyCodes::Key ConvertKeyCode(unsigned long key_code);
std::vector<IWindowDemander*> window_demanders;
bool bAltEnterLocked;
HINSTANCE g_hInst;
HWND g_hwnd;
DEVMODE mode;
};
}
+125
View File
@@ -0,0 +1,125 @@
#ifndef Delegate_h__
#define Delegate_h__
class CDelegate
{
};
// 0 parameters...
#define SUFFIX 0
#define TEMPLATE_PARAMS
#define TEMPLATE_ARGS
#define PARAMS
#define ARGS
#include "Delegate_base.h"
#undef SUFFIX
#undef TEMPLATE_PARAMS
#undef TEMPLATE_ARGS
#undef PARAMS
#undef ARGS
// 1 parameter...
#define SUFFIX 1
#define TEMPLATE_PARAMS \
, class TP1
#define TEMPLATE_ARGS , TP1
#define PARAMS TP1 p1
#define ARGS p1
#include "Delegate_base.h"
#undef SUFFIX
#undef TEMPLATE_PARAMS
#undef TEMPLATE_ARGS
#undef PARAMS
#undef ARGS
// 2 parameters...
#define SUFFIX 2
#define TEMPLATE_PARAMS \
, class TP1, class TP2
#define TEMPLATE_ARGS \
,TP1, TP2
#define PARAMS TP1 p1, TP2 p2
#define ARGS p1, p2
#include "Delegate_base.h"
#undef SUFFIX
#undef TEMPLATE_PARAMS
#undef TEMPLATE_ARGS
#undef PARAMS
#undef ARGS
// 3 parameters...
#define SUFFIX 3
#define TEMPLATE_PARAMS \
, class TP1, class TP2, class TP3
#define TEMPLATE_ARGS \
,TP1, TP2, TP3
#define PARAMS TP1 p1, TP2 p2, TP3 p3
#define ARGS p1, p2, p3
#include "Delegate_base.h"
#undef SUFFIX
#undef TEMPLATE_PARAMS
#undef TEMPLATE_ARGS
#undef PARAMS
#undef ARGS
// 4 parameters...
#define SUFFIX 4
#define TEMPLATE_PARAMS \
, class TP1, class TP2, class TP3, class TP4
#define TEMPLATE_ARGS \
,TP1, TP2, TP3, TP4
#define PARAMS TP1 p1, TP2 p2, TP3 p3, TP4 p4
#define ARGS p1, p2, p3, p4
#include "Delegate_base.h"
#undef SUFFIX
#undef TEMPLATE_PARAMS
#undef TEMPLATE_ARGS
#undef PARAMS
#undef ARGS
// 5 parameters...
#define SUFFIX 5
#define TEMPLATE_PARAMS \
, class TP1, class TP2, class TP3, class TP4, class TP5
#define TEMPLATE_ARGS \
,TP1, TP2, TP3, TP4, TP5
#define PARAMS TP1 p1, TP2 p2, TP3 p3, TP4 p4, TP5 p5
#define ARGS p1, p2, p3, p4, p5
#include "Delegate_base.h"
#undef SUFFIX
#undef TEMPLATE_PARAMS
#undef TEMPLATE_ARGS
#undef PARAMS
#undef ARGS
//event declarations
#define EVENT(NAME) typedef Event0<void> NAME;
#define EVENT0(NAME) typedef Event0<void> NAME; //same as previous
#define EVENT1(NAME, P1) typedef Event1<void, P1> NAME;
#define EVENT2(NAME, P1, P2) typedef Event2<void, P1, P2> NAME;
#define EVENT3(NAME, P1, P2, P3) typedef Event3<void, P1, P2, P3> NAME;
#define EVENT4(NAME, P1, P2, P3, P4) typedef Event4<void, P1, P2, P3, P4> NAME;
#define EVENT5(NAME, P1, P2, P3, P4, P5) typedef Event5<void, P1, P2, P3, P4, P5> NAME;
//delegate declarations
#define DELEGATE0(NAME) typedef Delegate0<void> ##NAME;
#endif // Delegate_h__
+164
View File
@@ -0,0 +1,164 @@
#include <list>
#define COMBINE(a,b) COMBINE1(a,b)
#define COMBINE1(a,b) a##b
#define COMBINE3(a,b,c) COMBINE3(a,b,c)
#define COMBINE31(a,b,c) a##b##c
#define I_DELEGATE COMBINE(Delegate, SUFFIX)
#define I_EVENT COMBINE(Event, SUFFIX)
#define C_STATIC_DELEGATE COMBINE(StaticDelegate, SUFFIX)
#define C_METHOD_DELEGATE COMBINE(MethodDelegate, SUFFIX)
template<class TRet TEMPLATE_PARAMS>
class I_DELEGATE : public CDelegate
{
public:
virtual ~I_DELEGATE(){}
virtual TRet Invoke(PARAMS) = 0;
virtual bool Compare(I_DELEGATE<TRet TEMPLATE_ARGS>* other) = 0;
};
template<class TRet TEMPLATE_PARAMS>
class C_STATIC_DELEGATE : public I_DELEGATE<TRet TEMPLATE_ARGS>
{
public:
typedef TRet (*Func)(PARAMS);
C_STATIC_DELEGATE(Func func)
{
pFunc = func;
}
C_STATIC_DELEGATE(const C_STATIC_DELEGATE& other)
{
pFunc = other.pFunc;
}
const C_STATIC_DELEGATE& operator=(const C_STATIC_DELEGATE& other)
{
this->pFunc = other.pFunc;
return *this;
}
virtual TRet Invoke(PARAMS)
{
return pFunc(ARGS);
}
virtual bool Compare(I_DELEGATE<TRet TEMPLATE_ARGS>* other)
{
return true;
}
private:
Func pFunc;
};
template<class TBase, class TRet TEMPLATE_PARAMS>
class C_METHOD_DELEGATE : public I_DELEGATE<TRet TEMPLATE_ARGS>
{
public:
typedef TRet (TBase::*Func)(PARAMS);
C_METHOD_DELEGATE(TBase* base, Func func)
{
pBase = base;
pFunc = func;
}
C_METHOD_DELEGATE(const C_METHOD_DELEGATE& other)
{
pBase = other.pBase;
pFunc = other.pFunc;
}
const C_METHOD_DELEGATE& operator=(const C_METHOD_DELEGATE& other)
{
this->pFunc = other.pFunc;
this->pBase = other.pBase;
return *this;
}
virtual TRet Invoke(PARAMS)
{
return (pBase->*pFunc)(ARGS);
}
virtual bool Compare(I_DELEGATE<TRet TEMPLATE_ARGS>* other)
{
return true;
}
private:
Func pFunc;
TBase* pBase;
};
template<class TRet TEMPLATE_PARAMS>
__forceinline I_DELEGATE<TRet TEMPLATE_ARGS>* NewDelegate(TRet (*pFunc)(PARAMS))
{
return new C_STATIC_DELEGATE<TRet TEMPLATE_ARGS>(pFunc);
}
template<class TBase, class TRet TEMPLATE_PARAMS>
__forceinline I_DELEGATE<TRet TEMPLATE_ARGS>* NewDelegate(TBase* base, TRet (TBase::*pFunc)(PARAMS))
{
return new C_METHOD_DELEGATE<TBase, TRet TEMPLATE_ARGS>(base, pFunc);
}
template<class TRet TEMPLATE_PARAMS>
class I_EVENT
{
public:
typedef I_DELEGATE<TRet TEMPLATE_ARGS> IDelegate;
typedef std::list<IDelegate*> DelegateList;
DelegateList delegates;
void Clear()
{
for(DelegateList::iterator it = delegates.begin(); it != delegates.end(); ++it)
{
delete (*it);
}
delegates.clear();
}
void Remove(CDelegate* del)
{
for(DelegateList::iterator it = delegates.begin(); it != delegates.end(); ++it)
{
if(del == (*it))
{
delete (*it);
delegates.erase(it);
break;
}
}
}
void AddDelegate(IDelegate* pDelegate)
{
if(pDelegate)
{
delegates.push_back(pDelegate);
}
}
void Invoke(PARAMS)
{
for(DelegateList::iterator it = delegates.begin(); it != delegates.end(); ++it)
{
(*it)->Invoke(ARGS);
}
}
I_EVENT<TRet TEMPLATE_ARGS>& operator =(IDelegate* pDelegate)
{
Clear();
AddDelegate(pDelegate);
return *this;
}
I_EVENT<TRet TEMPLATE_ARGS>& operator +=(IDelegate* pDelegate)
{
AddDelegate(pDelegate);
return *this;
}
I_EVENT<TRet TEMPLATE_ARGS>& operator +=(CDelegate* pDelegate)
{
AddDelegate((IDelegate*)pDelegate);
return *this;
}
};
+33
View File
@@ -0,0 +1,33 @@
#include "CLog.h"
namespace LifeCore
{
CLog::CLog()
:logToConsole(true)
{
hLogFile = CreateFile(String(_text("engine_log.txt")).c_str(), GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
SetFilePointer(hLogFile,0,NULL, FILE_END);
Write(String(_text("\nLogging started!")).c_str());
}
void CLog::LogToConsole(bool condition)
{
logToConsole = condition;
}
CLog::~CLog()
{
if(hLogFile)
{
Write(_text("Closing log"));
CloseHandle(hLogFile);
}
}
void CLog::Write(const String& message)
{
DWORD nb = 0;
WriteFile(hLogFile, message.c_str(), string_size(message), &nb, NULL);
WriteFile(hLogFile, L"\n", 1, &nb, NULL);
if(logToConsole)
printf("Log: %s\n", message.c_str());
}
}
+28
View File
@@ -0,0 +1,28 @@
#ifndef CLOG_H__
#define CLOG_H__
#include "../Singleton.h"
#include "../LString.h"
#include <windows.h>
namespace LifeCore
{
#define LOG_MESSAGE(message) LifeCore::CLog::me()->Write(STR(##message##))
#define LOG_ERROR(message, module, method) LifeCore::CLog::me()->Write("Error occured in method: " + STR(##module##) + "::" + STR(##method##) + "\n" + STR(##message##))
class CLog;
class CLog : public Singleton<CLog>
{
public:
CLog();
~CLog();
void Write(const String& message);
void LogToConsole(bool condition);
private:
HANDLE hLogFile;
bool logToConsole;
};
}
#endif
+94
View File
@@ -0,0 +1,94 @@
#include "NLog.h"
//#include <io.h>
#include <cstdio>
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <tchar.h>
namespace LifeCore {
NettleLog::NettleLog(LOG_LEVEL _level)
: AbortOnError(true), bOutConsole(true), bOutFile(false), bOutInterface(false), level(_level) {
//TODO: remove allocation of stringstream
stm = new std::stringstream();
}
NettleLog::~NettleLog() {
//std::stringstream stm;
*stm << "\n";
/*stm->seekg (0, std::ios::end);
size_t length = (size_t)stm->tellg();
stm->seekg (0, std::ios::beg);
char* buffer = new char [length + 1];
buffer[length] = 0;
stm->read (buffer,length);*/
//_write(1, buffer, length);
std::string str = stm->str();
std::cout << str;
#if defined(NOS_WINDOWS) && defined(_DEBUG)
OutputDebugString(str.c_str());
#endif
delete stm;
// delete[] buffer;
}
NettleLog& NettleLog::operator <<(bool val) {
*stm << (val ? "true" : "false");
return *this;
}
NettleLog& NettleLog::operator <<(uint32 val) {
*stm << val;
return *this;
}
NettleLog& NettleLog::operator <<(long val) {
*stm << val;
return *this;
}
NettleLog& NettleLog::operator <<(unsigned long val) {
*stm << val;
return *this;
}
NettleLog& NettleLog::operator <<(uint16 val) {
*stm << val;
return *this;
}
NettleLog& NettleLog::operator <<(uint64 val) {
*stm << val;
return *this;
}
NettleLog& NettleLog::operator <<(int64 val) {
*stm << val;
return *this;
}
NettleLog& NettleLog::operator <<(int32 val) {
*stm << val;
return *this;
}
NettleLog& NettleLog::operator <<(int16 val) {
*stm << val;
return *this;
}
NettleLog& NettleLog::operator <<(int8 val) {
*stm << val;
return *this;
}
NettleLog& NettleLog::operator <<(float val) {
*stm << val;
return *this;
}
NettleLog& NettleLog::operator <<(double val) {
*stm << val;
return *this;
}
NettleLog& NettleLog::operator <<(const String& val) {
*stm << val.c_str();
return *this;
}
NettleLog& NettleLog::operator <<(const char* val) {
*stm << val;
return *this;
}
}
+55
View File
@@ -0,0 +1,55 @@
#ifndef NLog_h__
#define NLog_h__
#include <sstream>
#include <ostream>
#include <strstream>
#include <iostream>
#include "../Types.h"
namespace LifeCore {
enum LOG_LEVEL {
LOG_WARNING,
LOG_ERROR,
LOG_INFO
};
class ILogOutput {
public:
virtual bool Write(LOG_LEVEL level, const String& message) = 0;
};
class NettleLog {
public:
std::stringstream* stm;
//std::stringstream stm;
NettleLog(LOG_LEVEL _level);
~NettleLog();
NettleLog& operator <<(int8 val);
NettleLog& operator <<(int16 val);
NettleLog& operator <<(uint16 val);
NettleLog& operator <<(int32 val);
NettleLog& operator <<(uint32 val);
NettleLog& operator <<(uint64 val);
NettleLog& operator <<(int64 val);
NettleLog& operator <<(long val);
NettleLog& operator <<(unsigned long val);
NettleLog& operator <<(float val);
NettleLog& operator <<(double val);
NettleLog& operator <<(const String& val);
NettleLog& operator <<(const char* val);
NettleLog& operator <<(bool val);
private:
LOG_LEVEL level;
bool AbortOnError;
bool bOutConsole;
bool bOutFile;
bool bOutInterface;
};
inline NettleLog LogWarning() { return NettleLog(LOG_WARNING); }
inline NettleLog LogError() { return NettleLog(LOG_ERROR); }
inline NettleLog LogInfo() { return NettleLog(LOG_INFO); }
}
#endif // NLog_h__
+125
View File
@@ -0,0 +1,125 @@
#include "LifeMath.h"
namespace LifeMath
{
extern INLINE void Mat4x4Invert(const Matrix4x4* matrix, Matrix4x4* result)
{
float num5 = matrix->M11;
float num4 = matrix->M12;
float num3 = matrix->M13;
float num2 = matrix->M14;
float num9 = matrix->M21;
float num8 = matrix->M22;
float num7 = matrix->M23;
float num6 = matrix->M24;
float num17 = matrix->M31;
float num16 = matrix->M32;
float num15 = matrix->M33;
float num14 = matrix->M34;
float num13 = matrix->M41;
float num12 = matrix->M42;
float num11 = matrix->M43;
float num10 = matrix->M44;
float num23 = (num15 * num10) - (num14 * num11);
float num22 = (num16 * num10) - (num14 * num12);
float num21 = (num16 * num11) - (num15 * num12);
float num20 = (num17 * num10) - (num14 * num13);
float num19 = (num17 * num11) - (num15 * num13);
float num18 = (num17 * num12) - (num16 * num13);
float num39 = ((num8 * num23) - (num7 * num22)) + (num6 * num21);
float num38 = -(((num9 * num23) - (num7 * num20)) + (num6 * num19));
float num37 = ((num9 * num22) - (num8 * num20)) + (num6 * num18);
float num36 = -(((num9 * num21) - (num8 * num19)) + (num7 * num18));
float num = 1.0f / ((((num5 * num39) + (num4 * num38)) + (num3 * num37)) + (num2 * num36));
result->M11 = num39 * num;
result->M21 = num38 * num;
result->M31 = num37 * num;
result->M41 = num36 * num;
result->M12 = -(((num4 * num23) - (num3 * num22)) + (num2 * num21)) * num;
result->M22 = (((num5 * num23) - (num3 * num20)) + (num2 * num19)) * num;
result->M32 = -(((num5 * num22) - (num4 * num20)) + (num2 * num18)) * num;
result->M42 = (((num5 * num21) - (num4 * num19)) + (num3 * num18)) * num;
float num35 = (num7 * num10) - (num6 * num11);
float num34 = (num8 * num10) - (num6 * num12);
float num33 = (num8 * num11) - (num7 * num12);
float num32 = (num9 * num10) - (num6 * num13);
float num31 = (num9 * num11) - (num7 * num13);
float num30 = (num9 * num12) - (num8 * num13);
result->M13 = (((num4 * num35) - (num3 * num34)) + (num2 * num33)) * num;
result->M23 = -(((num5 * num35) - (num3 * num32)) + (num2 * num31)) * num;
result->M33 = (((num5 * num34) - (num4 * num32)) + (num2 * num30)) * num;
result->M43 = -(((num5 * num33) - (num4 * num31)) + (num3 * num30)) * num;
float num29 = (num7 * num14) - (num6 * num15);
float num28 = (num8 * num14) - (num6 * num16);
float num27 = (num8 * num15) - (num7 * num16);
float num26 = (num9 * num14) - (num6 * num17);
float num25 = (num9 * num15) - (num7 * num17);
float num24 = (num9 * num16) - (num8 * num17);
result->M14 = -(((num4 * num29) - (num3 * num28)) + (num2 * num27)) * num;
result->M24 = (((num5 * num29) - (num3 * num26)) + (num2 * num25)) * num;
result->M34 = -(((num5 * num28) - (num4 * num26)) + (num2 * num24)) * num;
result->M44 = (((num5 * num27) - (num4 * num25)) + (num3 * num24)) * num;
}
extern INLINE void QuatRotationYawPitchRoll(float yaw, float pitch, float roll, Quaternion& result)
{
float num13 = roll * 0.5f;
float num2 = sinf(num13);
float num = cosf(num13);
float num12 = pitch * 0.5f;
float num11 = sinf(num12);
float num10 = cosf(num12);
float num9 = yaw * 0.5f;
float num8 = sinf(num9);
float num7 = cosf(num9);
float num6 = num7 * num11;
float num5 = num8 * num10;
result.X = ((num2 * num5) + (num * num6));
result.Y = ((num * num5) - (num2 * num6));
float num4 = num7 * num10;
float num3 = num8 * num11;
result.Z = ((num2 * num4) - (num * num3));
result.W = ((num2 * num3) + (num * num4));
}
extern INLINE void QuatRotationMatrix(const Matrix4x4& matrix, Quaternion& dst)
{
float num8 = (matrix.M11 + matrix.M22) + matrix.M33;
if (num8 > 0.0f)
{
float num = sqrtf(num8 + 1.0f);
dst.W = num * 0.5f;
num = 0.5f / num;
dst.X = (matrix.M23 - matrix.M32) * num;
dst.Y = (matrix.M31 - matrix.M13) * num;
dst.Z = (matrix.M12 - matrix.M21) * num;
}
else if ((matrix.M11 >= matrix.M22) && (matrix.M11 >= matrix.M33))
{
float num7 = sqrtf((((1.0f + matrix.M11) - matrix.M22) - matrix.M33));
float num4 = 0.5f / num7;
dst.X = 0.5f * num7;
dst.Y = (matrix.M12 + matrix.M21) * num4;
dst.Z = (matrix.M13 + matrix.M31) * num4;
dst.W = (matrix.M23 - matrix.M32) * num4;
}
else if (matrix.M22 > matrix.M33)
{
float num6 = sqrtf((((1.0f + matrix.M22) - matrix.M11) - matrix.M33));
float num3 = 0.5f / num6;
dst.X = (matrix.M21 + matrix.M12) * num3;
dst.Y = 0.5f * num6;
dst.Z = (matrix.M32 + matrix.M23) * num3;
dst.W = (matrix.M31 - matrix.M13) * num3;
}
else
{
float num5 = sqrtf((((1.0f + matrix.M33) - matrix.M11) - matrix.M22));
float num2 = 0.5f / num5;
dst.X = (matrix.M31 + matrix.M13) * num2;
dst.Y = (matrix.M32 + matrix.M23) * num2;
dst.Z = 0.5f * num5;
dst.W = (matrix.M12 - matrix.M21) * num2;
}
}
}
File diff suppressed because it is too large Load Diff
+274
View File
@@ -0,0 +1,274 @@
#ifndef __MATRIX4X4__
#define __MATRIX4X4__
#include "Math.h"
namespace LifeMath
{
#undef INLINE
#ifdef _WIN32
#ifdef _MSC_VER
#define INLINE __forceinline
#define ALIGN_MATRIX __declspec(align(16))
#endif
#else
#define ALIGN_MATRIX
#ifdef __GNUC__
#define INLINE __attribute__((always_inline))
#endif
#endif
#ifndef INLINE
#define INLINE inline
#endif
typedef ALIGN_MATRIX struct Matrix4x4
{
public:
float M11;
float M12;
float M13;
float M14;
float M21;
float M22;
float M23;
float M24;
float M31;
float M32;
float M33;
float M34;
float M41;
float M42;
float M43;
float M44;
void setup(
float _m11, float _m12, float _m13, float _m14,
float _m21, float _m22, float _m23, float _m24,
float _m31, float _m32, float _m33, float _m34,
float _m41, float _m42, float _m43, float _m44)
{
M11 = _m11;
M12 = _m12;
M13 = _m13;
M14 = _m14;
M21 = _m21;
M22 = _m22;
M23 = _m23;
M24 = _m24;
M31 = _m31;
M32 = _m32;
M33 = _m33;
M34 = _m34;
M41 = _m41;
M42 = _m42;
M43 = _m43;
M44 = _m44;
}
INLINE Matrix4x4 operator *(const Matrix4x4& matrix2) const
{
Matrix4x4 matrix;
matrix.M11 = (((this->M11 * matrix2.M11) + (this->M12 * matrix2.M21)) + (this->M13 * matrix2.M31)) + (this->M14 * matrix2.M41);
matrix.M12 = (((this->M11 * matrix2.M12) + (this->M12 * matrix2.M22)) + (this->M13 * matrix2.M32)) + (this->M14 * matrix2.M42);
matrix.M13 = (((this->M11 * matrix2.M13) + (this->M12 * matrix2.M23)) + (this->M13 * matrix2.M33)) + (this->M14 * matrix2.M43);
matrix.M14 = (((this->M11 * matrix2.M14) + (this->M12 * matrix2.M24)) + (this->M13 * matrix2.M34)) + (this->M14 * matrix2.M44);
matrix.M21 = (((this->M21 * matrix2.M11) + (this->M22 * matrix2.M21)) + (this->M23 * matrix2.M31)) + (this->M24 * matrix2.M41);
matrix.M22 = (((this->M21 * matrix2.M12) + (this->M22 * matrix2.M22)) + (this->M23 * matrix2.M32)) + (this->M24 * matrix2.M42);
matrix.M23 = (((this->M21 * matrix2.M13) + (this->M22 * matrix2.M23)) + (this->M23 * matrix2.M33)) + (this->M24 * matrix2.M43);
matrix.M24 = (((this->M21 * matrix2.M14) + (this->M22 * matrix2.M24)) + (this->M23 * matrix2.M34)) + (this->M24 * matrix2.M44);
matrix.M31 = (((this->M31 * matrix2.M11) + (this->M32 * matrix2.M21)) + (this->M33 * matrix2.M31)) + (this->M34 * matrix2.M41);
matrix.M32 = (((this->M31 * matrix2.M12) + (this->M32 * matrix2.M22)) + (this->M33 * matrix2.M32)) + (this->M34 * matrix2.M42);
matrix.M33 = (((this->M31 * matrix2.M13) + (this->M32 * matrix2.M23)) + (this->M33 * matrix2.M33)) + (this->M34 * matrix2.M43);
matrix.M34 = (((this->M31 * matrix2.M14) + (this->M32 * matrix2.M24)) + (this->M33 * matrix2.M34)) + (this->M34 * matrix2.M44);
matrix.M41 = (((this->M41 * matrix2.M11) + (this->M42 * matrix2.M21)) + (this->M43 * matrix2.M31)) + (this->M44 * matrix2.M41);
matrix.M42 = (((this->M41 * matrix2.M12) + (this->M42 * matrix2.M22)) + (this->M43 * matrix2.M32)) + (this->M44 * matrix2.M42);
matrix.M43 = (((this->M41 * matrix2.M13) + (this->M42 * matrix2.M23)) + (this->M43 * matrix2.M33)) + (this->M44 * matrix2.M43);
matrix.M44 = (((this->M41 * matrix2.M14) + (this->M42 * matrix2.M24)) + (this->M43 * matrix2.M34)) + (this->M44 * matrix2.M44);
return matrix;
}
/* public MatrixBasis Basis
{
get
{
MatrixBasis basis = new MatrixBasis();
basis.M11 = this.M11;
basis.M12 = this.M12;
basis.M13 = this.M13;
basis.M21 = this.M21;
basis.M22 = this.M22;
basis.M23 = this.M23;
basis.M31 = this.M31;
basis.M32 = this.M32;
basis.M33 = this.M33;
return basis;
}
set
{
this.M11 = value.M11;
this.M12 = value.M12;
this.M13 = value.M13;
this.M21 = value.M21;
this.M22 = value.M22;
this.M23 = value.M23;
this.M31 = value.M31;
this.M32 = value.M32;
this.M33 = value.M33;
}
}*/
/*
#region Decomposition
public Vec3f Up
{
get
{
Vec3f vector;
vector.X = this.M21;
vector.Y = this.M22;
vector.Z = this.M23;
return vector;
}
set
{
this.M21 = value.X;
this.M22 = value.Y;
this.M23 = value.Z;
}
}
public Vec3f Down
{
get
{
Vec3f vector;
vector.X = -this.M21;
vector.Y = -this.M22;
vector.Z = -this.M23;
return vector;
}
set
{
this.M21 = -value.X;
this.M22 = -value.Y;
this.M23 = -value.Z;
}
}
public Vec3f Right
{
get
{
Vec3f vector;
vector.X = this.M11;
vector.Y = this.M12;
vector.Z = this.M13;
return vector;
}
set
{
this.M11 = value.X;
this.M12 = value.Y;
this.M13 = value.Z;
}
}
public Vec3f Left
{
get
{
Vec3f vector;
vector.X = -this.M11;
vector.Y = -this.M12;
vector.Z = -this.M13;
return vector;
}
set
{
this.M11 = -value.X;
this.M12 = -value.Y;
this.M13 = -value.Z;
}
}
public Vec3f Forward
{
get
{
Vec3f vector;
vector.X = -this.M31;
vector.Y = -this.M32;
vector.Z = -this.M33;
return vector;
}
set
{
this.M31 = -value.X;
this.M32 = -value.Y;
this.M33 = -value.Z;
}
}
public Vec3f Backward
{
get
{
Vec3f vector;
vector.X = this.M31;
vector.Y = this.M32;
vector.Z = this.M33;
return vector;
}
set
{
this.M31 = value.X;
this.M32 = value.Y;
this.M33 = value.Z;
}
}
public Vec3f Position
{
get
{
Vec3f vector;
vector.X = this.M41;
vector.Y = this.M42;
vector.Z = this.M43;
return vector;
}
set
{
this.M41 = value.X;
this.M42 = value.Y;
this.M43 = value.Z;
}
}
public void Decompose(out Vec3f scale, out CQuaternion rotation, out Vec3f translation)
{
MatrixBasis b = this.Basis;
scale = b.Scaling;
translation.X = this.M41;
translation.Y = this.M42;
translation.Z = this.M43;
b.Scaling = new Vec3f(1, 1, 1);
rotation = CQuaternion.RotationBasis(b);
}
#endregion*/
} Matrix4x4, *PMatrix4x4, **LPMatrix4x4;
typedef Matrix4x4 float4x4;
}
#endif
+96
View File
@@ -0,0 +1,96 @@
#ifndef Plane_h__
#define Plane_h__
#include "Vector3D.h"
#include "Vector4D.h"
#include <cmath>
namespace LifeMath
{
#undef INLINE
#ifdef _WIN32
#ifdef _MSC_VER
#define INLINE __forceinline
#endif
#else
#ifdef __GNUC__
#define INLINE __attribute__((always_inline))
#endif
#endif
#ifndef INLINE
#define INLINE inline
#endif
class Plane
{
public:
Vec3f Normal;
float D;
Plane(float a, float b, float c, float d)
{
Normal.X = a;
Normal.Y = b;
Normal.Z = c;
D = d;
}
Plane()
{
Normal.X = 0.0f;
Normal.Y = 1.0f;
Normal.Z = 0.0f;
D = 0.0f;
}
Plane(const Vec3f& _normal, float d)
{
Normal = _normal;
D = d;
}
Plane(const Vec3f& point, const Vec3f& normal)
{
Normal = normal;
D = -(((normal.Y * point.Y) + (normal.X * point.X)) + (normal.Z * point.Z));
}
Plane(const Vec4f& val)
{
Normal.X = val.X;
Normal.Y = val.Y;
Normal.Z = val.Z;
D = val.W;
}
Plane(Vec3f& point1, Vec3f& point2, Vec3f& point3)
{
float num10 = point2.X - point1.X;
float num9 = point2.Y - point1.Y;
float num8 = point2.Z - point1.Z;
float num7 = point3.X - point1.X;
float num6 = point3.Y - point1.Y;
float num5 = point3.Z - point1.Z;
float num4 = (num9 * num5) - (num8 * num6);
float num3 = (num8 * num7) - (num10 * num5);
float num2 = (num10 * num6) - (num9 * num7);
float num11 = ((num4 * num4) + (num3 * num3)) + (num2 * num2);
float num = 1.0f / sqrtf(num11);
Normal.X = num4 * num;
Normal.Y = num3 * num;
Normal.Z = num2 * num;
D = -(((Normal.X * point1.X) + (Normal.Y * point1.Y)) + (Normal.Z * point1.Z));
}
INLINE bool operator ==(const Plane& other) const
{
return (other.Normal == this->Normal && other.D == this->D);
}
INLINE bool operator !=(const Plane& other) const
{
if(this->Normal == other.Normal)
{
return (this->D != other.D);
}
return true;
}
};
}
#endif // Plane_h__
+93
View File
@@ -0,0 +1,93 @@
#ifndef __QUATERNION__
#define __QUATERNION__
#include "Math.h"
#include <cmath>
namespace LifeMath
{
#undef INLINE
#ifdef _WIN32
#ifdef _MSC_VER
#define INLINE __forceinline
#endif
#else
#ifdef __GNUC__
#define INLINE __attribute__((always_inline))
#endif
#endif
#ifndef INLINE
#define INLINE inline
#endif
struct Quaternion
{
public:
float X,Y,Z,W;
INLINE Quaternion()
{
X = Y = Z = W = 0.0f;
}
INLINE Quaternion operator -() const
{
return Quaternion(-X, -Y, -Z, -W);
}
INLINE bool operator == (const Quaternion& right) const
{
return (X == right.X && Y == right.Y && Z == right.Z && W == right.W);
}
INLINE bool operator != (const Quaternion& right) const
{
return (X != right.X || Y != right.Y || Z != right.Z || W != right.W);
}
INLINE Quaternion(float x, float y, float z, float w)
{
X = x;
Y = y;
Z = z;
W = w;
}
INLINE Quaternion& operator =(const Quaternion& other)
{
X = other.X;
Y = other.Y;
Z = other.Z;
W = other.W;
return *this;
}
INLINE Quaternion operator *(float other) const
{
return Quaternion(X * other, Y * other, Z * other, W * other);
}
INLINE Quaternion operator +(const Quaternion& other) const
{
return Quaternion(X + other.X, Y + other.Y, Z + other.Z, W + other.W);
}
INLINE Quaternion operator *(const Quaternion& other) const
{
Quaternion quaternion;
float x = this->X;
float y = this->Y;
float z = this->Z;
float w = this->W;
float num4 = other.X;
float num3 = other.Y;
float num2 = other.Z;
float num = other.W;
float num12 = (y * num2) - (z * num3);
float num11 = (z * num4) - (x * num2);
float num10 = (x * num3) - (y * num4);
float num9 = ((x * num4) + (y * num3)) + (z * num2);
quaternion.X = ((x * num) + (num4 * w)) + num12;
quaternion.Y = ((y * num) + (num3 * w)) + num11;
quaternion.Z = ((z * num) + (num2 * w)) + num10;
quaternion.W = (w * num) - num9;
return quaternion;
}
};
}
#endif
+127
View File
@@ -0,0 +1,127 @@
#ifndef Rectangle_h__
#define Rectangle_h__
#include "math/Vector2D.h"
namespace LifeMath
{
template<typename T>
struct Rectangle
{
T x;
T y;
T width;
T height;
Rectangle()
{
x = y = width = height = 0;
}
Rectangle(T _width, T _height)
{
width = _width;
height = _height;
x = y = 0;
}
Rectangle(T _x, T _y, T _width, T _height)
{
width = _width;
height = _height;
x = _x;
y = _y;
}
bool operator ==(const Rectangle<T>& other)
{
return ((x == other.x) && (y == other.y) && (width == other.width) && (height == other.height));
}
bool operator !=(const Rectangle<T>& other)
{
return ((x != other.x) || (y != other.y) || (width != other.width) || (height != other.height));
}
//get rectangle minimum corner coordinate
Vector2D<T> GetMin() const
{
return Vector2D<T>(x, y);
}
//get rectangle maximum corner coordinate
Vector2D<T> GetMax() const
{
return Vector2D<T>(x + (width), y + (height));
}
//get rectangle maximum X
T GetMaxX() const
{
return x + (width);
}
//get rectangle maximum Y
T GetMaxY() const
{
return y + (height);
}
//get rectangle square
T GetSquare() const
{
return width * height;
}
//merge 2 rectangles into 1 bounding rectangle
void Merge(const Rectangle<T>& other)
{
int minX = std::min<T>(x, other.x);
int maxX = std::max<T>(this->GetMaxX(), other.GetMaxX());
int minY = std::min<T>(y, other.y);
int maxY = std::max<T>(this->GetMaxY(), other.GetMaxY());
this->x = minX;
this->y = minY;
this->width = maxX - minX;
this->height = maxY - minY;
}
//crop this rectangle by other rectangle
void Crop(const Rectangle<T>& other)
{
if(this->x < other.x)
{
T diff = other.x - this->x;
this->x += diff;
this->width -= diff;
}
if(this->y < other.y)
{
T diff = other.y - this->y;
this->y += diff;
this->height -= diff;
}
if(this->GetMaxX() > other.GetMaxX())
{
T diff = this->GetMaxX() - other.GetMaxX();
this->width -= diff;
}
if(this->GetMaxY() > other.GetMaxY())
{
T diff = this->GetMaxY() - other.GetMaxY();
this->height -= diff;
}
if(width < 0)
width = 0;
if(height < 0)
height = 0;
}
bool InRect(const T x, const T y)
{
return (x >= this->x && y >= this->y && x <= (this->x + width) && y <=(this->y + height));
}
bool InRect(const Vector2D<T>& point)
{
return InRect(point.X, point.Y);
}
};
typedef Rectangle<int> Rect2i;
typedef Rectangle<float> Rect2f;
typedef Rectangle<double> Rect2d;
}
#endif // Rectangle_h__
+22
View File
@@ -0,0 +1,22 @@
#ifndef Spline_h__
#define Spline_h__
namespace LifeCore
{
template<typename T>
static inline T LinearBezier(float t, const T& v1, const T& v2)
{
return (v1 * (1-t)) + (v2 * t);
}
template<typename T>
static inline T QuadraticBezier(float t, const T& v1, const T& v2, const T& v3)
{
return (LinearBezier<T>(t, v1, v2) * (1 - t)) + (LinearBezier<T>(t, v2, v3) * (t));
}
template<typename T>
static inline T CubicBezier(float t, const T& v1, const T& v2, const T& v3, const T& v4)
{
return (QuadraticBezier<T>(t, v1, v2, v3) * (1 - t)) + (QuadraticBezier<T>(t, v2, v3, v4) * (t));
}
}
#endif // Spline_h__
+175
View File
@@ -0,0 +1,175 @@
#ifndef __Vector2D__
#define __Vector2D__
#include "Math.h"
namespace LifeMath
{
#undef INLINE
#ifdef _WIN32
#ifdef _MSC_VER
#define INLINE __forceinline
#endif
#else
#ifdef __GNUC__
#define INLINE __attribute__((always_inline))
#endif
#endif
#ifndef INLINE
#define INLINE inline
#endif
template<typename T>
struct Vector2D
{
public:
T X, Y;
INLINE Vector2D(T x, T y)
{
this->X = x;
this->Y = y;
}
INLINE void Set(T x, T y)
{
this->X = x;
this->Y = y;
}
INLINE Vector2D(void)
{
this->X = this->Y = 0;
}
INLINE Vector2D(T val)
{
this->X = val;
this->Y = val;
}
INLINE Vector2D& operator=(const Vector2D& other)
{
X = other.X;
Y = other.Y;
return *this;
}
//unary operators
INLINE Vector2D operator -() const
{
return Vector2D(-X, -Y);
}
INLINE Vector2D operator +() const
{
return *this;
}
//binary operators
INLINE Vector2D<T> operator +(const LifeMath::Vector2D<T> &other) const
{
return Vector2D<T>(X + other.X, Y + other.Y);
}
INLINE Vector2D<T> operator -(const LifeMath::Vector2D<T> &other) const
{
return Vector2D<T>(X - other.X, Y - other.Y);
}
INLINE Vector2D<T> operator *(T other) const
{
return Vector2D<T>(X * other, Y * other);
}
INLINE Vector2D<T> operator /(T other) const
{
return Vector2D<T>(X / other, Y / other);
}
INLINE operator T * ()
{
return &X;
}
INLINE operator const T * () const
{
return &X;
}
INLINE bool operator == (const Vector2D& vector) const
{
return (X == vector.X && Y == vector.Y);
}
INLINE bool operator != (const Vector2D& vector) const
{
return (X != vector.X || Y != vector.Y);
}
INLINE Vector2D<T>& operator += (const Vector2D& Vector)
{
X += Vector.X;
Y += Vector.Y;
return *this;
}
INLINE Vector2D<T>& operator -= (const Vector2D& Vector)
{
X -= Vector.X;
Y -= Vector.Y;
return *this;
}
INLINE Vector2D<T>& operator *= (T Value)
{
X *= Value;
Y *= Value;
return *this;
}
INLINE Vector2D<T>& operator /= (T Value)
{
//assert(Value && "Zero Value");
//*this *= (1.0f / Value);
this->X /= Value;
this->Y /= Value;
return *this;
}
INLINE Vector2D<T>& operator += (T Value)
{
X += Value;
Y += Value;
return *this;
}
INLINE Vector2D<T>& operator -= (T Value)
{
X -= Value;
Y -= Value;
return *this;
}
INLINE Vector2D<T>& operator /= (const Vector2D<T>& vector)
{
X /= vector.X;
Y /= vector.Y;
return *this;
}
INLINE Vector2D<T>& operator *= (const Vector2D<T>& vector)
{
X *= vector.X;
Y *= vector.Y;
return *this;
}
INLINE float& operator [](int index)
{
//assert(index < 3 && "Out Of Range");
return *(index + (&X));
}
INLINE float operator [] (int index) const
{
//assert(index < 2 && "Out Of Range");
return * (index + (&X));
}
INLINE bool operator > (const Vector2D<T>& v) const
{
return X > v.X && Y > v.Y;
}
INLINE bool operator < (const Vector2D<T>& v) const
{
return X < v.X && Y < v.Y;
}
};
typedef Vector2D<float> Vec2f;
typedef Vector2D<int> Vec2i;
typedef Vector2D<float> float2;
}
#endif
+180
View File
@@ -0,0 +1,180 @@
#ifndef __VECTOR3D__
#define __VECTOR3D__
#include "Math.h"
namespace LifeMath
{
#undef INLINE
#ifdef _WIN32
#ifdef _MSC_VER
#define INLINE __forceinline
#endif
#else
#ifdef __GNUC__
#define INLINE __attribute__((always_inline))
#endif
#endif
#ifndef INLINE
#define INLINE inline
#endif
template<typename T>
struct Vector3D
{
public:
T X, Y, Z;
INLINE Vector3D<T>(T x, T y, T z)
{
this->X = x;
this->Y = y;
this->Z = z;
}
INLINE Vector3D<T>(void)
{
this->X = 0.0f;
this->Y = 0.0f;
this->Z = 0.0f;
}
INLINE Vector3D<T>(T val)
{
this->X = val;
this->Y = val;
this->Z = val;
}
INLINE Vector3D<T>& operator=(const Vector3D<T>& other)
{
X = other.X;
Y = other.Y;
Z = other.Z;
return *this;
}
//unary operators
INLINE Vector3D<T> operator -() const
{
return Vector3D<T>(-X, -Y, -Z);
}
INLINE Vector3D<T> operator +() const
{
return *this;
}
//binary operators
INLINE Vector3D<T> operator +(const Vector3D<T> &other) const
{
return Vector3D<T>(X + other.X, Y + other.Y, Z + other.Z);
}
INLINE Vector3D<T> operator -(const Vector3D<T> &other) const
{
return Vector3D<T>(X - other.X, Y - other.Y, Z - other.Z);
}
INLINE Vector3D<T> operator *(T other) const
{
return Vector3D<T>(X * other, Y * other, Z * other);
}
INLINE Vector3D<T> operator /(T other) const
{
return Vector3D<T>(X / other, Y / other, Z / other);
}
INLINE operator T * ()
{
return &X;
}
INLINE operator const T * () const
{
return &X;
}
INLINE bool operator == (const Vector3D<T>& vector) const
{
return (X == vector.X && Y == vector.Y && Z == vector.Z);
}
INLINE bool operator != (const Vector3D<T>& vector) const
{
return (X != vector.X || Y != vector.Y || Z != vector.Z);
}
INLINE Vector3D<T>& operator += (const Vector3D<T>& Vector)
{
X += Vector.X;
Y += Vector.Y;
Z += Vector.Z;
return *this;
}
INLINE Vector3D<T>& operator -= (const Vector3D<T>& Vector)
{
X -= Vector.X;
Y -= Vector.Y;
Z -= Vector.Z;
return *this;
}
INLINE Vector3D<T>& operator *= (T Value)
{
X *= Value;
Y *= Value;
Z *= Value;
return *this;
}
INLINE Vector3D<T>& operator /= (T Value)
{
//assert(Value && "Zero Value");
*this *= (1.0f / Value);
return *this;
}
INLINE Vector3D<T>& operator += (T Value)
{
X += Value;
Y += Value;
Z += Value;
return *this;
}
INLINE Vector3D<T>& operator -= (T Value)
{
X -= Value;
Y -= Value;
Z -= Value;
return *this;
}
INLINE Vector3D<T>& operator /= (const Vector3D<T>& vector)
{
X /= vector.X;
Y /= vector.Y;
Z /= vector.Z;
return *this;
}
INLINE Vector3D<T>& operator *= (const Vector3D<T>& vector)
{
X *= vector.X;
Y *= vector.Y;
Z *= vector.Z;
return *this;
}
INLINE T& operator [](int index)
{
//assert(index < 3 && "Out Of Range");
return *(index + (&X));
}
INLINE T operator [] (int index) const
{
//assert(index < 2 && "Out Of Range");
return * (index + (&X));
}
INLINE bool operator > (const Vector3D<T>& v) const
{
return X > v.X && Y > v.Y && Z > v.Z;
}
INLINE bool operator < (const Vector3D<T>& v) const
{
return X < v.X && Y < v.Y && Z < v.Z;
}
};
typedef Vector3D<float> Vec3f;
typedef Vector3D<int> Vec3i;
typedef Vector3D<float> float3;
}
#endif
+192
View File
@@ -0,0 +1,192 @@
#ifndef __VECTOR4D__
#define __VECTOR4D__
#include "Math.h"
namespace LifeMath
{
#undef INLINE
#ifdef _WIN32
#ifdef _MSC_VER
#define INLINE __forceinline
#endif
#else
#ifdef __GNUC__
#define INLINE __attribute__((always_inline))
#endif
#endif
#ifndef INLINE
#define INLINE inline
#endif
// struct Vector4D;
// struct Vector4D;
template<typename T>
struct Vector4D
{
public:
T X, Y, Z, W;
INLINE Vector4D<T>(T x, T y, T z, T w)
{
this->X = x;
this->Y = y;
this->Z = z;
this->W = w;
}
INLINE Vector4D<T>(void)
{
this->X = 0;
this->Y = 0;
this->Z = 0;
this->W = 0;
}
INLINE Vector4D<T>(T val)
{
this->X = val;
this->Y = val;
this->Z = val;
this->W = val;
}
//unary operators
INLINE Vector4D<T> operator -() const
{
return Vector4D<T>(-X, -Y, -Z, -W);
}
INLINE Vector4D<T> operator +() const
{
return *this;
}
INLINE Vector4D<T>& operator=(const Vector4D<T>& other)
{
X = other.X;
Y = other.Y;
Z = other.Z;
W = other.W;
return *this;
}
//binary operators
INLINE Vector4D<T> operator +(const Vector4D<T> &other) const
{
return Vector4D<T>(X + other.X, Y + other.Y, Z + other.Z, W + other.W);
}
INLINE Vector4D<T> operator -(const Vector4D<T> &other) const
{
return Vector4D<T>(X - other.X, Y - other.Y, Z - other.Z, W - other.W);
}
INLINE Vector4D<T> operator *(T other) const
{
return Vector4D<T>(X * other, Y * other, Z * other, W * other);
}
INLINE Vector4D<T> operator /(T other) const
{
return Vector4D<T>(X / other, Y / other, Z / other, W / other);
}
INLINE operator T * ()
{
return &X;
}
INLINE operator const T * () const
{
return &X;
}
INLINE bool operator == (const Vector4D<T>& vector) const
{
return (X == vector.X && Y == vector.Y && Z == vector.Z && W == vector.W);
}
INLINE bool operator != (const Vector4D<T>& vector) const
{
return (X != vector.X || Y != vector.Y || Z != vector.Z || W != vector.W);
}
INLINE Vector4D<T>& operator += (const Vector4D<T>& Vector)
{
X += Vector.X;
Y += Vector.Y;
Z += Vector.Z;
W += Vector.W;
return *this;
}
INLINE Vector4D<T>& operator -= (const Vector4D<T>& Vector)
{
X -= Vector.X;
Y -= Vector.Y;
Z -= Vector.Z;
W -= Vector.W;
return *this;
}
INLINE Vector4D<T>& operator *= (T Value)
{
X *= Value;
Y *= Value;
Z *= Value;
W *= Value;
return *this;
}
INLINE Vector4D<T>& operator /= (T Value)
{
//assert(Value && "Zero Value");
*this *= (1.0f / Value);
return *this;
}
INLINE Vector4D<T>& operator += (T Value)
{
X += Value;
Y += Value;
Z += Value;
W += Value;
return *this;
}
INLINE Vector4D<T>& operator -= (T Value)
{
X -= Value;
Y -= Value;
Z -= Value;
W -= Value;
return *this;
}
INLINE Vector4D<T>& operator /= (const Vector4D<T>& vector)
{
X /= vector.X;
Y /= vector.Y;
Z /= vector.Z;
W /= vector.W;
return *this;
}
INLINE Vector4D<T>& operator *= (const Vector4D<T>& vector)
{
X *= vector.X;
Y *= vector.Y;
Z *= vector.Z;
W *= vector.W;
return *this;
}
INLINE T& operator [](int index)
{
//assert(index < 3 && "Out Of Range");
return *(index + (&X));
}
INLINE T operator [] (int index) const
{
//assert(index < 2 && "Out Of Range");
return * (index + (&X));
}
INLINE bool operator > (const Vector4D<T>& v) const
{
return X > v.X && Y > v.Y && Z > v.Z && W > v.W;
}
INLINE bool operator < (const Vector4D<T>& v) const
{
return X < v.X && Y < v.Y && Z < v.Z && W < v.W;
}
};
typedef Vector4D<float> Vec4f;
typedef Vector4D<int> Vec4i;
typedef Vector4D<float> float4;
}
#endif
+17
View File
@@ -0,0 +1,17 @@
#ifndef vector_base_h__
#define vector_base_h__
namespace LifeMath
{
template<typename T_val, int Size>
class vector_base
{
public:
vector_base();
~vector_base();
private:
};
}
#endif // vector_base_h__
+225
View File
@@ -0,0 +1,225 @@
#include "WebCamera.h"
#include "../Utils.h"
#include "../log/NLog.h"
#include "../Com.h"
namespace LifeCore {
class WinWebCameraDescription : public WebCameraDescription {
public:
friend class WebCamera;
WinWebCameraDescription(IMFActivate* act, int id)
: activate(act), deviceId(id)
{
if(activate != nullptr)
activate->AddRef();
}
~WinWebCameraDescription() {
SafeRelease(&activate);
}
std::wstring GetName() override{
if(activate == nullptr)
return std::wstring(L"");
WCHAR *szFriendlyName = NULL;
UINT32 cchName;
auto hr = activate->GetAllocatedString(MF_DEVSOURCE_ATTRIBUTE_FRIENDLY_NAME, &szFriendlyName, &cchName);
if(hr != S_OK)
return std::wstring(L"");
std::wstring result(szFriendlyName);
CoTaskMemFree(szFriendlyName);
return result;
}
int deviceId;
protected:
IMFActivate* activate;
};
struct ChooseDeviceParam {
ChooseDeviceParam() : ppDevices(NULL), count(0) {}
~ChooseDeviceParam() {
for(DWORD i = 0; i < count; i++) {
SafeRelease(&ppDevices[i]);
}
CoTaskMemFree(ppDevices);
}
IMFActivate **ppDevices;
UINT32 count;
UINT32 selection;
};
class WinWebCamCallback : IMFCaptureEngineOnEventCallback {
public:
WinWebCamCallback(WebCamera* cam)
: m_cRef(1), camera(cam), sleeping(false)
{
}
// IUnknown
STDMETHODIMP QueryInterface(REFIID riid, void** ppv) {
static const QITAB qit[] = {
QITABENT(WinWebCamCallback, IMFCaptureEngineOnEventCallback), { 0 }
};
return QISearch(this, qit, riid, ppv);
}
STDMETHODIMP_(ULONG) AddRef() {
return InterlockedIncrement(&m_cRef);
}
STDMETHODIMP_(ULONG) Release() {
LONG cRef = InterlockedDecrement(&m_cRef);
if(cRef == 0) {
delete this;
}
return cRef;
}
// IMFCaptureEngineOnEventCallback
STDMETHODIMP OnEvent(_In_ IMFMediaEvent* pEvent) {
if(sleeping && camera != nullptr) {
// We're about to fall asleep, that means we've just asked the CE to stop the preview
// and record. We need to handle it here since our message pump may be gone.
GUID guidType;
HRESULT hrStatus;
HRESULT hr = pEvent->GetStatus(&hrStatus);
if(FAILED(hr)) {
hrStatus = hr;
}
hr = pEvent->GetExtendedType(&guidType);
if(SUCCEEDED(hr)) {
if(guidType == MF_CAPTURE_ENGINE_PREVIEW_STOPPED) {
LogInfo() << "Preview stopped";
//m_pManager->OnPreviewStopped(hrStatus);
// SetEvent(m_pManager->m_hEvent);
} else if(guidType == MF_CAPTURE_ENGINE_RECORD_STOPPED) {
LogInfo() << "Engine stopped";
//m_pManager->OnRecordStopped(hrStatus);
//SetEvent(m_pManager->m_hEvent);
} else {
// This is an event we don't know about, we don't really care and there's
// no clean way to report the error so just set the event and fall through.
//SetEvent(m_pManager->m_hEvent);
}
}
return S_OK;
} else {
LogInfo() << "Capture event";
pEvent->AddRef(); // The application will release the pointer when it handles the message.
camera->OnCaptureEvent(pEvent);
//PostMessage(m_hwnd, WM_APP_CAPTURE_EVENT, (WPARAM)pEvent, 0L);
}
return S_OK;
}
protected:
bool sleeping;
long m_cRef;
WebCamera* camera;
};
WebCamera::WebCamera(webcam_desc_ptr desc)
: description(desc), FrameNumber(0), pSource(nullptr), grabber(nullptr)
{
callback = new WinWebCamCallback(this);
}
void WebCamera::OnCaptureEvent(IMFMediaEvent* pEvent) {
HRESULT hrStatus;
GUID eventType;
pEvent->GetStatus(&hrStatus);
pEvent->GetExtendedType(&eventType);
}
RawBuffer<uint8>* WebCamera::GetImage() {
return grabber->GetImage();
}
void WebCamera::OnImageGrabbed(WinMfImageGrabber* grabber, RawBuffer<uint8>* image) {
FrameNumber++;
Event_ImageCapture.Call(this, image);
}
bool WebCamera::Open() {
IMFActivate* pActivate = dynamic_cast<WinWebCameraDescription*>(description.get())->activate;
HRESULT hr = pActivate->ActivateObject(__uuidof(IMFMediaSource), (void**)&pSource);
if(FAILED(hr)) {
LogInfo() << "Failed to activate camera!";
return false;
}
grabber = new WinMfImageGrabber(this);
if(FAILED(grabber->initImageGrabber(pSource, MFVideoFormat_RGB24)) || FAILED(grabber->startGrabbing())) {
LogInfo() << "Failed to init camera grabber";
pActivate->ShutdownObject();
FINAL_RELEASE(grabber);
FINAL_RELEASE(pSource);
return false;
}
return true;
}
void WebCamera::Close() {
IMFActivate* pActivate = dynamic_cast<WinWebCameraDescription*>(description.get())->activate;
if(grabber != nullptr)
grabber->stopGrabbing();
FINAL_RELEASE(grabber);
FINAL_RELEASE(pSource);
pActivate->ShutdownObject();
pActivate->AddRef();
auto val = pActivate->Release();
LogInfo() << "Initial 2 pActivate refCount = " << val;
FrameNumber = 0;
}
int2 WebCamera::GetSize() {
return int2();
}
int32 WebCamera::GetBpp() {
return -1;
}
bool WebCamera::Read(int2 size, uint8* buffer) {
return false;
}
void WebCamera::Update() {
grabber->processGrabbing();
}
std::vector<webcam_desc_ptr> WebCamera::GetConnectedDevices() {
std::vector<webcam_desc_ptr> result;
IMFAttributes *pAttributes = NULL;
ChooseDeviceParam param;
HRESULT hr = MFCreateAttributes(&pAttributes, 1);
if(FAILED(hr)) {
printf("Failed\n");
goto Exit;
}
// Ask for source type = video capture devices
hr = pAttributes->SetGUID(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE,
MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID);
if(FAILED(hr)) {
printf("Failed\n");
goto Exit;
}
// Enumerate devices.
hr = MFEnumDeviceSources(pAttributes, &param.ppDevices, &param.count);
if(FAILED(hr)) {
printf("Failed\n");
goto Exit;
}
for(UINT32 i = 0; i < param.count; ++i) {
result.push_back(webcam_desc_ptr(new WinWebCameraDescription(param.ppDevices[i], i)));
}
Exit:
if(NULL != pAttributes) {
pAttributes->Release();
pAttributes = NULL;
}
return result;
}
}
+54
View File
@@ -0,0 +1,54 @@
#ifndef WebCamera_h__
#define WebCamera_h__
#include "../ICamera.h"
#include "../IImage.h"
#include <mfapi.h>
#include <mfidl.h>
#include <mferror.h>
#include <mfcaptureengine.h>
#include "WinMfImageGrabber.h"
#include <shlwapi.h>
#pragma comment(lib, "mf.lib")
#pragma comment(lib, "mfplat.lib")
#pragma comment(lib, "mfuuid.lib")
#pragma comment(lib, "shlwapi.lib")
#include <memory>
#include <vector>
#include "../Delegate.h"
namespace LifeCore {
class WebCameraDescription {
public:
virtual ~WebCameraDescription() {}
virtual std::wstring GetName() = 0;
};
typedef std::shared_ptr<WebCameraDescription> webcam_desc_ptr;
class WebCamera : public ICamera, public IImage
{
public:
Delegate<WebCamera*, RawBuffer<uint8>*> Event_ImageCapture;
WebCamera(webcam_desc_ptr desc);
int2 GetSize();
int32 GetBpp();
bool Read(int2 size, uint8* buffer);
static std::vector<webcam_desc_ptr> GetConnectedDevices();
bool Open();
void Close();
void OnImageGrabbed(WinMfImageGrabber* grabber, RawBuffer<uint8>* image);
void OnCaptureEvent(IMFMediaEvent* pEvent);
void Update();
RawBuffer<uint8>* GetImage();
int FrameNumber;
private:
webcam_desc_ptr description;
WinMfImageGrabber* grabber;
IMFMediaSource *pSource;
void* callback;
};
}
#endif // WebCamera_h__
+461
View File
@@ -0,0 +1,461 @@
#include "WinMfFormatReader.h"
#include "Strsafe.h"
#include <Mfapi.h>
#include <mfobjects.h>
namespace LifeCore {
LPCWSTR GetGUIDNameConstNew(const GUID& guid);
HRESULT GetGUIDNameNew(const GUID& guid, WCHAR **ppwsz);
HRESULT LogAttributeValueByIndexNew(IMFAttributes *pAttr, DWORD index);
HRESULT SpecialCaseAttributeValueNew(GUID guid, const PROPVARIANT& var, WinMfMediaType &out);
unsigned int *GetParametr(GUID guid, WinMfMediaType &out) {
if(guid == MF_MT_YUV_MATRIX)
return &(out.MF_MT_YUV_MATRIX);
if(guid == MF_MT_VIDEO_LIGHTING)
return &(out.MF_MT_VIDEO_LIGHTING);
if(guid == MF_MT_DEFAULT_STRIDE)
return &(out.MF_MT_DEFAULT_STRIDE);
if(guid == MF_MT_VIDEO_CHROMA_SITING)
return &(out.MF_MT_VIDEO_CHROMA_SITING);
if(guid == MF_MT_VIDEO_NOMINAL_RANGE)
return &(out.MF_MT_VIDEO_NOMINAL_RANGE);
if(guid == MF_MT_ALL_SAMPLES_INDEPENDENT)
return &(out.MF_MT_ALL_SAMPLES_INDEPENDENT);
if(guid == MF_MT_FIXED_SIZE_SAMPLES)
return &(out.MF_MT_FIXED_SIZE_SAMPLES);
if(guid == MF_MT_SAMPLE_SIZE)
return &(out.MF_MT_SAMPLE_SIZE);
if(guid == MF_MT_VIDEO_PRIMARIES)
return &(out.MF_MT_VIDEO_PRIMARIES);
if(guid == MF_MT_INTERLACE_MODE)
return &(out.MF_MT_INTERLACE_MODE);
return NULL;
}
HRESULT LogAttributeValueByIndexNew(IMFAttributes *pAttr, DWORD index, WinMfMediaType &out) {
WCHAR *pGuidName = NULL;
WCHAR *pGuidValName = NULL;
GUID guid = { 0 };
PROPVARIANT var;
PropVariantInit(&var);
HRESULT hr = pAttr->GetItemByIndex(index, &guid, &var);
if(FAILED(hr)) {
goto done;
}
hr = GetGUIDNameNew(guid, &pGuidName);
if(FAILED(hr)) {
goto done;
}
hr = SpecialCaseAttributeValueNew(guid, var, out);
unsigned int *p;
if(FAILED(hr)) {
goto done;
}
if(hr == S_FALSE) {
switch(var.vt) {
case VT_UI4:
p = GetParametr(guid, out);
if(p) {
*p = var.ulVal;
}
break;
case VT_UI8:
break;
case VT_R8:
break;
case VT_CLSID:
if(guid == MF_MT_AM_FORMAT_TYPE) {
hr = GetGUIDNameNew(*var.puuid, &pGuidValName);
if(SUCCEEDED(hr)) {
out.MF_MT_AM_FORMAT_TYPE = MF_MT_AM_FORMAT_TYPE;
out.pMF_MT_AM_FORMAT_TYPEName = pGuidValName;
pGuidValName = NULL;
}
}
if(guid == MF_MT_MAJOR_TYPE) {
hr = GetGUIDNameNew(*var.puuid, &pGuidValName);
if(SUCCEEDED(hr)) {
out.MF_MT_MAJOR_TYPE = MF_MT_MAJOR_TYPE;
out.pMF_MT_MAJOR_TYPEName = pGuidValName;
pGuidValName = NULL;
}
}
if(guid == MF_MT_SUBTYPE) {
hr = GetGUIDNameNew(*var.puuid, &pGuidValName);
if(SUCCEEDED(hr)) {
out.MF_MT_SUBTYPE = MF_MT_SUBTYPE;
out.pMF_MT_SUBTYPEName = pGuidValName;
pGuidValName = NULL;
}
}
break;
case VT_LPWSTR:
break;
case VT_VECTOR | VT_UI1:
break;
case VT_UNKNOWN:
break;
default:
break;
}
}
done:
CoTaskMemFree(pGuidName);
CoTaskMemFree(pGuidValName);
PropVariantClear(&var);
return hr;
}
HRESULT GetGUIDNameNew(const GUID& guid, WCHAR **ppwsz) {
HRESULT hr = S_OK;
WCHAR *pName = NULL;
LPCWSTR pcwsz = GetGUIDNameConstNew(guid);
if(pcwsz) {
size_t cchLength = 0;
hr = StringCchLengthW(pcwsz, STRSAFE_MAX_CCH, &cchLength);
if(FAILED(hr)) {
goto done;
}
pName = (WCHAR*)CoTaskMemAlloc((cchLength + 1) * sizeof(WCHAR));
if(pName == NULL) {
hr = E_OUTOFMEMORY;
goto done;
}
hr = StringCchCopyW(pName, cchLength + 1, pcwsz);
if(FAILED(hr)) {
goto done;
}
} else {
hr = StringFromCLSID(guid, &pName);
}
done:
if(FAILED(hr)) {
*ppwsz = NULL;
CoTaskMemFree(pName);
} else {
*ppwsz = pName;
}
return hr;
}
void LogUINT32AsUINT64New(const PROPVARIANT& var, UINT32 &uHigh, UINT32 &uLow) {
Unpack2UINT32AsUINT64(var.uhVal.QuadPart, &uHigh, &uLow);
}
float OffsetToFloatNew(const MFOffset& offset) {
return offset.value + (static_cast<float>(offset.fract) / 65536.0f);
}
HRESULT LogVideoAreaNew(const PROPVARIANT& var) {
if(var.caub.cElems < sizeof(MFVideoArea)) {
return S_OK;
}
MFVideoArea *pArea = (MFVideoArea*)var.caub.pElems;
return S_OK;
}
HRESULT SpecialCaseAttributeValueNew(GUID guid, const PROPVARIANT& var, WinMfMediaType &out) {
if(guid == MF_MT_FRAME_SIZE) {
UINT32 uHigh = 0, uLow = 0;
LogUINT32AsUINT64New(var, uHigh, uLow);
out.width = uHigh;
out.height = uLow;
out.MF_MT_FRAME_SIZE = out.width * out.height;
} else
if(guid == MF_MT_FRAME_RATE) {
UINT32 uHigh = 0, uLow = 0;
LogUINT32AsUINT64New(var, uHigh, uLow);
out.MF_MT_FRAME_RATE = uHigh;
out.MF_MT_FRAME_RATE_low = uLow;
} else
if(guid == MF_MT_FRAME_RATE_RANGE_MAX) {
UINT32 uHigh = 0, uLow = 0;
LogUINT32AsUINT64New(var, uHigh, uLow);
out.MF_MT_FRAME_RATE_RANGE_MAX = uHigh;
out.MF_MT_FRAME_RATE_RANGE_MAX_low = uLow;
} else
if(guid == MF_MT_FRAME_RATE_RANGE_MIN) {
UINT32 uHigh = 0, uLow = 0;
LogUINT32AsUINT64New(var, uHigh, uLow);
out.MF_MT_FRAME_RATE_RANGE_MIN = uHigh;
out.MF_MT_FRAME_RATE_RANGE_MIN_low = uLow;
} else
if(guid == MF_MT_PIXEL_ASPECT_RATIO) {
UINT32 uHigh = 0, uLow = 0;
LogUINT32AsUINT64New(var, uHigh, uLow);
out.MF_MT_PIXEL_ASPECT_RATIO = uHigh;
out.MF_MT_PIXEL_ASPECT_RATIO_low = uLow;
} else {
return S_FALSE;
}
return S_OK;
}
#ifndef IF_EQUAL_RETURN
#define IF_EQUAL_RETURN(param, val) if(val == param) return L#val
#endif
LPCWSTR GetGUIDNameConstNew(const GUID& guid) {
IF_EQUAL_RETURN(guid, MF_MT_MAJOR_TYPE);
IF_EQUAL_RETURN(guid, MF_MT_MAJOR_TYPE);
IF_EQUAL_RETURN(guid, MF_MT_SUBTYPE);
IF_EQUAL_RETURN(guid, MF_MT_ALL_SAMPLES_INDEPENDENT);
IF_EQUAL_RETURN(guid, MF_MT_FIXED_SIZE_SAMPLES);
IF_EQUAL_RETURN(guid, MF_MT_COMPRESSED);
IF_EQUAL_RETURN(guid, MF_MT_SAMPLE_SIZE);
IF_EQUAL_RETURN(guid, MF_MT_WRAPPED_TYPE);
IF_EQUAL_RETURN(guid, MF_MT_AUDIO_NUM_CHANNELS);
IF_EQUAL_RETURN(guid, MF_MT_AUDIO_SAMPLES_PER_SECOND);
IF_EQUAL_RETURN(guid, MF_MT_AUDIO_FLOAT_SAMPLES_PER_SECOND);
IF_EQUAL_RETURN(guid, MF_MT_AUDIO_AVG_BYTES_PER_SECOND);
IF_EQUAL_RETURN(guid, MF_MT_AUDIO_BLOCK_ALIGNMENT);
IF_EQUAL_RETURN(guid, MF_MT_AUDIO_BITS_PER_SAMPLE);
IF_EQUAL_RETURN(guid, MF_MT_AUDIO_VALID_BITS_PER_SAMPLE);
IF_EQUAL_RETURN(guid, MF_MT_AUDIO_SAMPLES_PER_BLOCK);
IF_EQUAL_RETURN(guid, MF_MT_AUDIO_CHANNEL_MASK);
IF_EQUAL_RETURN(guid, MF_MT_AUDIO_FOLDDOWN_MATRIX);
IF_EQUAL_RETURN(guid, MF_MT_AUDIO_WMADRC_PEAKREF);
IF_EQUAL_RETURN(guid, MF_MT_AUDIO_WMADRC_PEAKTARGET);
IF_EQUAL_RETURN(guid, MF_MT_AUDIO_WMADRC_AVGREF);
IF_EQUAL_RETURN(guid, MF_MT_AUDIO_WMADRC_AVGTARGET);
IF_EQUAL_RETURN(guid, MF_MT_AUDIO_PREFER_WAVEFORMATEX);
IF_EQUAL_RETURN(guid, MF_MT_AAC_PAYLOAD_TYPE);
IF_EQUAL_RETURN(guid, MF_MT_AAC_AUDIO_PROFILE_LEVEL_INDICATION);
IF_EQUAL_RETURN(guid, MF_MT_FRAME_SIZE);
IF_EQUAL_RETURN(guid, MF_MT_FRAME_RATE);
IF_EQUAL_RETURN(guid, MF_MT_FRAME_RATE_RANGE_MAX);
IF_EQUAL_RETURN(guid, MF_MT_FRAME_RATE_RANGE_MIN);
IF_EQUAL_RETURN(guid, MF_MT_PIXEL_ASPECT_RATIO);
IF_EQUAL_RETURN(guid, MF_MT_DRM_FLAGS);
IF_EQUAL_RETURN(guid, MF_MT_PAD_CONTROL_FLAGS);
IF_EQUAL_RETURN(guid, MF_MT_SOURCE_CONTENT_HINT);
IF_EQUAL_RETURN(guid, MF_MT_VIDEO_CHROMA_SITING);
IF_EQUAL_RETURN(guid, MF_MT_INTERLACE_MODE);
IF_EQUAL_RETURN(guid, MF_MT_TRANSFER_FUNCTION);
IF_EQUAL_RETURN(guid, MF_MT_VIDEO_PRIMARIES);
IF_EQUAL_RETURN(guid, MF_MT_CUSTOM_VIDEO_PRIMARIES);
IF_EQUAL_RETURN(guid, MF_MT_YUV_MATRIX);
IF_EQUAL_RETURN(guid, MF_MT_VIDEO_LIGHTING);
IF_EQUAL_RETURN(guid, MF_MT_VIDEO_NOMINAL_RANGE);
IF_EQUAL_RETURN(guid, MF_MT_GEOMETRIC_APERTURE);
IF_EQUAL_RETURN(guid, MF_MT_MINIMUM_DISPLAY_APERTURE);
IF_EQUAL_RETURN(guid, MF_MT_PAN_SCAN_APERTURE);
IF_EQUAL_RETURN(guid, MF_MT_PAN_SCAN_ENABLED);
IF_EQUAL_RETURN(guid, MF_MT_AVG_BITRATE);
IF_EQUAL_RETURN(guid, MF_MT_AVG_BIT_ERROR_RATE);
IF_EQUAL_RETURN(guid, MF_MT_MAX_KEYFRAME_SPACING);
IF_EQUAL_RETURN(guid, MF_MT_DEFAULT_STRIDE);
IF_EQUAL_RETURN(guid, MF_MT_PALETTE);
IF_EQUAL_RETURN(guid, MF_MT_USER_DATA);
IF_EQUAL_RETURN(guid, MF_MT_AM_FORMAT_TYPE);
IF_EQUAL_RETURN(guid, MF_MT_MPEG_START_TIME_CODE);
IF_EQUAL_RETURN(guid, MF_MT_MPEG2_PROFILE);
IF_EQUAL_RETURN(guid, MF_MT_MPEG2_LEVEL);
IF_EQUAL_RETURN(guid, MF_MT_MPEG2_FLAGS);
IF_EQUAL_RETURN(guid, MF_MT_MPEG_SEQUENCE_HEADER);
IF_EQUAL_RETURN(guid, MF_MT_DV_AAUX_SRC_PACK_0);
IF_EQUAL_RETURN(guid, MF_MT_DV_AAUX_CTRL_PACK_0);
IF_EQUAL_RETURN(guid, MF_MT_DV_AAUX_SRC_PACK_1);
IF_EQUAL_RETURN(guid, MF_MT_DV_AAUX_CTRL_PACK_1);
IF_EQUAL_RETURN(guid, MF_MT_DV_VAUX_SRC_PACK);
IF_EQUAL_RETURN(guid, MF_MT_DV_VAUX_CTRL_PACK);
IF_EQUAL_RETURN(guid, MF_MT_ARBITRARY_HEADER);
IF_EQUAL_RETURN(guid, MF_MT_ARBITRARY_FORMAT);
IF_EQUAL_RETURN(guid, MF_MT_IMAGE_LOSS_TOLERANT);
IF_EQUAL_RETURN(guid, MF_MT_MPEG4_SAMPLE_DESCRIPTION);
IF_EQUAL_RETURN(guid, MF_MT_MPEG4_CURRENT_SAMPLE_ENTRY);
IF_EQUAL_RETURN(guid, MF_MT_ORIGINAL_4CC);
IF_EQUAL_RETURN(guid, MF_MT_ORIGINAL_WAVE_FORMAT_TAG);
// Media types
IF_EQUAL_RETURN(guid, MFMediaType_Audio);
IF_EQUAL_RETURN(guid, MFMediaType_Video);
IF_EQUAL_RETURN(guid, MFMediaType_Protected);
IF_EQUAL_RETURN(guid, MFMediaType_SAMI);
IF_EQUAL_RETURN(guid, MFMediaType_Script);
IF_EQUAL_RETURN(guid, MFMediaType_Image);
IF_EQUAL_RETURN(guid, MFMediaType_HTML);
IF_EQUAL_RETURN(guid, MFMediaType_Binary);
IF_EQUAL_RETURN(guid, MFMediaType_FileTransfer);
IF_EQUAL_RETURN(guid, MFVideoFormat_AI44); // FCC('AI44')
IF_EQUAL_RETURN(guid, MFVideoFormat_ARGB32); // D3DFMT_A8R8G8B8
IF_EQUAL_RETURN(guid, MFVideoFormat_AYUV); // FCC('AYUV')
IF_EQUAL_RETURN(guid, MFVideoFormat_DV25); // FCC('dv25')
IF_EQUAL_RETURN(guid, MFVideoFormat_DV50); // FCC('dv50')
IF_EQUAL_RETURN(guid, MFVideoFormat_DVH1); // FCC('dvh1')
IF_EQUAL_RETURN(guid, MFVideoFormat_DVSD); // FCC('dvsd')
IF_EQUAL_RETURN(guid, MFVideoFormat_DVSL); // FCC('dvsl')
IF_EQUAL_RETURN(guid, MFVideoFormat_H264); // FCC('H264')
IF_EQUAL_RETURN(guid, MFVideoFormat_I420); // FCC('I420')
IF_EQUAL_RETURN(guid, MFVideoFormat_IYUV); // FCC('IYUV')
IF_EQUAL_RETURN(guid, MFVideoFormat_M4S2); // FCC('M4S2')
IF_EQUAL_RETURN(guid, MFVideoFormat_MJPG);
IF_EQUAL_RETURN(guid, MFVideoFormat_MP43); // FCC('MP43')
IF_EQUAL_RETURN(guid, MFVideoFormat_MP4S); // FCC('MP4S')
IF_EQUAL_RETURN(guid, MFVideoFormat_MP4V); // FCC('MP4V')
IF_EQUAL_RETURN(guid, MFVideoFormat_MPG1); // FCC('MPG1')
IF_EQUAL_RETURN(guid, MFVideoFormat_MSS1); // FCC('MSS1')
IF_EQUAL_RETURN(guid, MFVideoFormat_MSS2); // FCC('MSS2')
IF_EQUAL_RETURN(guid, MFVideoFormat_NV11); // FCC('NV11')
IF_EQUAL_RETURN(guid, MFVideoFormat_NV12); // FCC('NV12')
IF_EQUAL_RETURN(guid, MFVideoFormat_P010); // FCC('P010')
IF_EQUAL_RETURN(guid, MFVideoFormat_P016); // FCC('P016')
IF_EQUAL_RETURN(guid, MFVideoFormat_P210); // FCC('P210')
IF_EQUAL_RETURN(guid, MFVideoFormat_P216); // FCC('P216')
IF_EQUAL_RETURN(guid, MFVideoFormat_RGB24); // D3DFMT_R8G8B8
IF_EQUAL_RETURN(guid, MFVideoFormat_RGB32); // D3DFMT_X8R8G8B8
IF_EQUAL_RETURN(guid, MFVideoFormat_RGB555); // D3DFMT_X1R5G5B5
IF_EQUAL_RETURN(guid, MFVideoFormat_RGB565); // D3DFMT_R5G6B5
IF_EQUAL_RETURN(guid, MFVideoFormat_RGB8);
IF_EQUAL_RETURN(guid, MFVideoFormat_UYVY); // FCC('UYVY')
IF_EQUAL_RETURN(guid, MFVideoFormat_v210); // FCC('v210')
IF_EQUAL_RETURN(guid, MFVideoFormat_v410); // FCC('v410')
IF_EQUAL_RETURN(guid, MFVideoFormat_WMV1); // FCC('WMV1')
IF_EQUAL_RETURN(guid, MFVideoFormat_WMV2); // FCC('WMV2')
IF_EQUAL_RETURN(guid, MFVideoFormat_WMV3); // FCC('WMV3')
IF_EQUAL_RETURN(guid, MFVideoFormat_WVC1); // FCC('WVC1')
IF_EQUAL_RETURN(guid, MFVideoFormat_Y210); // FCC('Y210')
IF_EQUAL_RETURN(guid, MFVideoFormat_Y216); // FCC('Y216')
IF_EQUAL_RETURN(guid, MFVideoFormat_Y410); // FCC('Y410')
IF_EQUAL_RETURN(guid, MFVideoFormat_Y416); // FCC('Y416')
IF_EQUAL_RETURN(guid, MFVideoFormat_Y41P);
IF_EQUAL_RETURN(guid, MFVideoFormat_Y41T);
IF_EQUAL_RETURN(guid, MFVideoFormat_YUY2); // FCC('YUY2')
IF_EQUAL_RETURN(guid, MFVideoFormat_YV12); // FCC('YV12')
IF_EQUAL_RETURN(guid, MFVideoFormat_YVYU);
IF_EQUAL_RETURN(guid, MFAudioFormat_PCM); // WAVE_FORMAT_PCM
IF_EQUAL_RETURN(guid, MFAudioFormat_Float); // WAVE_FORMAT_IEEE_FLOAT
IF_EQUAL_RETURN(guid, MFAudioFormat_DTS); // WAVE_FORMAT_DTS
IF_EQUAL_RETURN(guid, MFAudioFormat_Dolby_AC3_SPDIF); // WAVE_FORMAT_DOLBY_AC3_SPDIF
IF_EQUAL_RETURN(guid, MFAudioFormat_DRM); // WAVE_FORMAT_DRM
IF_EQUAL_RETURN(guid, MFAudioFormat_WMAudioV8); // WAVE_FORMAT_WMAUDIO2
IF_EQUAL_RETURN(guid, MFAudioFormat_WMAudioV9); // WAVE_FORMAT_WMAUDIO3
IF_EQUAL_RETURN(guid, MFAudioFormat_WMAudio_Lossless); // WAVE_FORMAT_WMAUDIO_LOSSLESS
IF_EQUAL_RETURN(guid, MFAudioFormat_WMASPDIF); // WAVE_FORMAT_WMASPDIF
IF_EQUAL_RETURN(guid, MFAudioFormat_MSP1); // WAVE_FORMAT_WMAVOICE9
IF_EQUAL_RETURN(guid, MFAudioFormat_MP3); // WAVE_FORMAT_MPEGLAYER3
IF_EQUAL_RETURN(guid, MFAudioFormat_MPEG); // WAVE_FORMAT_MPEG
IF_EQUAL_RETURN(guid, MFAudioFormat_AAC); // WAVE_FORMAT_MPEG_HEAAC
IF_EQUAL_RETURN(guid, MFAudioFormat_ADTS); // WAVE_FORMAT_MPEG_ADTS_AAC
return NULL;
}
WinMfFormatReader::WinMfFormatReader(void) {}
WinMfMediaType WinMfFormatReader::Read(IMFMediaType *pType) {
UINT32 count = 0;
HRESULT hr = S_OK;
WinMfMediaType out;
hr = pType->LockStore();
if(FAILED(hr)) {
return out;
}
hr = pType->GetCount(&count);
if(FAILED(hr)) {
return out;
}
for(UINT32 i = 0; i < count; i++) {
hr = LogAttributeValueByIndexNew(pType, i, out);
if(FAILED(hr)) {
break;
}
}
hr = pType->UnlockStore();
if(FAILED(hr)) {
return out;
}
return out;
}
WinMfFormatReader::~WinMfFormatReader(void) {}
}
+21
View File
@@ -0,0 +1,21 @@
#ifndef WinMfFormatReader_h__
#define WinMfFormatReader_h__
#include <guiddef.h>
#include "WinMfMediaType.h"
struct IMFMediaType;
namespace LifeCore {
/// Class for parsing info from IMFMediaType into the local MediaType
class WinMfFormatReader {
public:
static WinMfMediaType Read(IMFMediaType *pType);
~WinMfFormatReader(void);
private:
WinMfFormatReader(void);
};
}
#endif // WinMfFormatReader_h__
+342
View File
@@ -0,0 +1,342 @@
#include "WinMfImageGrabber.h"
#include <mfapi.h>
#include "../log/NLog.h"
#include "../Utils.h"
#include "WinMfFormatReader.h"
#include "WinMfMediaType.h"
#include <shlwapi.h>
#include "WebCamera.h"
#include "../Com.h"
namespace LifeCore {
WinMfImageGrabber::WinMfImageGrabber(WebCamera* cam)
: m_cRef(1), ig_pSession(nullptr), camera(cam)
{
}
WinMfImageGrabber::~WinMfImageGrabber() {
LogInfo() << "~WinMfImageGrabber ";
/*if(ig_pSession) {
LogInfo() << "~WinMfImageGrabber shutdown session";
ig_pSession->Shutdown();
}*/
}
HRESULT WinMfImageGrabber::initImageGrabber(IMFMediaSource *pSource, GUID VideoFormat) {
IMFActivate *pSinkActivate = NULL;/**/
IMFMediaType *pType = NULL;/**/
IMFPresentationDescriptor *pPD = NULL;/**/
IMFStreamDescriptor *pSD = NULL;/**/
IMFMediaTypeHandler *pHandler = NULL;/**/
IMFMediaType *pCurrentType = NULL;/**/
WinMfMediaType MT;
auto hr = pSource->CreatePresentationDescriptor(&pPD);
if(FAILED(hr)) {
LogError() << "Failed to create presentation descriptor!";
goto err;
}
BOOL fSelected;
hr = pPD->GetStreamDescriptorByIndex(0, &fSelected, &pSD);
if(FAILED(hr)) {
goto err;
}
hr = pSD->GetMediaTypeHandler(&pHandler);
if(FAILED(hr)) {
goto err;
}
DWORD cTypes = 0;
hr = pHandler->GetMediaTypeCount(&cTypes);
if(FAILED(hr)) {
goto err;
}
if(cTypes > 0) {
hr = pHandler->GetCurrentMediaType(&pCurrentType);
if(FAILED(hr)) {
goto err;
}
MT = WinMfFormatReader::Read(pCurrentType);
}
err:
SafeRelease(&pPD);
SafeRelease(&pSD);
SafeRelease(&pHandler);
SafeRelease(&pCurrentType);
unsigned int sizeRawImage = 0;
if(VideoFormat == MFVideoFormat_RGB24) {
sizeRawImage = MT.MF_MT_FRAME_SIZE * 3;
} else if(VideoFormat == MFVideoFormat_RGB32) {
sizeRawImage = MT.MF_MT_FRAME_SIZE * 4;
}
buffer_first = new RawBuffer<uint8>(sizeRawImage, MT);
buffer_second = new RawBuffer<uint8>(sizeRawImage, MT);
buffer_active = buffer_second;
hr = MFCreateMediaType(&pType);
hr = pType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video);
hr = pType->SetGUID(MF_MT_SUBTYPE, VideoFormat);
// Create the sample grabber sink.
hr = MFCreateSampleGrabberSinkActivate(pType, this, &pSinkActivate);
// To run as fast as possible, set this attribute (requires Windows 7):
hr = pSinkActivate->SetUINT32(MF_SAMPLEGRABBERSINK_IGNORE_CLOCK, TRUE);
// Create the Media Session.
hr = MFCreateMediaSession(NULL, &ig_pSession);
// Create the topology.
hr = CreateTopology(pSource, pSinkActivate, &ig_pTopology);
SafeRelease(&pSinkActivate);
SafeRelease(&pType);
return S_OK;
}
RawBuffer<uint8>* WinMfImageGrabber::GetImage() {
return buffer_active;
}
#define CHECK_HR(x) if (FAILED(x)) { goto done; }
HRESULT WinMfImageGrabber::CreateTopology(IMFMediaSource *pSource, IMFActivate *pSinkActivate, IMFTopology **ppTopo) {
IMFTopology *pTopology = NULL;
IMFPresentationDescriptor *pPD = NULL;
IMFStreamDescriptor *pSD = NULL;
IMFMediaTypeHandler *pHandler = NULL;
IMFTopologyNode *pNode1 = NULL;
IMFTopologyNode *pNode2 = NULL;
HRESULT hr = S_OK;
DWORD cStreams = 0;
CHECK_HR(hr = MFCreateTopology(&pTopology));
CHECK_HR(hr = pSource->CreatePresentationDescriptor(&pPD));
CHECK_HR(hr = pPD->GetStreamDescriptorCount(&cStreams));
for(DWORD i = 0; i < cStreams; i++) {
// In this example, we look for audio streams and connect them to the sink.
BOOL fSelected = FALSE;
GUID majorType;
CHECK_HR(hr = pPD->GetStreamDescriptorByIndex(i, &fSelected, &pSD));
CHECK_HR(hr = pSD->GetMediaTypeHandler(&pHandler));
CHECK_HR(hr = pHandler->GetMajorType(&majorType));
if(majorType == MFMediaType_Video && fSelected) {
CHECK_HR(hr = AddSourceNode(pTopology, pSource, pPD, pSD, &pNode1));
CHECK_HR(hr = AddOutputNode(pTopology, pSinkActivate, 0, &pNode2));
CHECK_HR(hr = pNode1->ConnectOutput(0, pNode2, 0));
break;
} else {
CHECK_HR(hr = pPD->DeselectStream(i));
}
SafeRelease(&pSD);
SafeRelease(&pHandler);
}
*ppTopo = pTopology;
(*ppTopo)->AddRef();
done:
SAFE_RELEASE(pTopology);
SAFE_RELEASE(pNode1);
SAFE_RELEASE(pNode2);
SAFE_RELEASE(pPD);
SAFE_RELEASE(pSD);
SAFE_RELEASE(pHandler);
return hr;
}
HRESULT WinMfImageGrabber::AddSourceNode(
IMFTopology *pTopology, // Topology.
IMFMediaSource *pSource, // Media source.
IMFPresentationDescriptor *pPD, // Presentation descriptor.
IMFStreamDescriptor *pSD, // Stream descriptor.
IMFTopologyNode **ppNode) // Receives the node pointer.
{
IMFTopologyNode *pNode = NULL;
HRESULT hr = S_OK;
CHECK_HR(hr = MFCreateTopologyNode(MF_TOPOLOGY_SOURCESTREAM_NODE, &pNode));
CHECK_HR(hr = pNode->SetUnknown(MF_TOPONODE_SOURCE, pSource));
CHECK_HR(hr = pNode->SetUnknown(MF_TOPONODE_PRESENTATION_DESCRIPTOR, pPD));
CHECK_HR(hr = pNode->SetUnknown(MF_TOPONODE_STREAM_DESCRIPTOR, pSD));
CHECK_HR(hr = pTopology->AddNode(pNode));
// Return the pointer to the caller.
*ppNode = pNode;
(*ppNode)->AddRef();
done:
SafeRelease(&pNode);
return hr;
}
HRESULT WinMfImageGrabber::AddOutputNode(
IMFTopology *pTopology, // Topology.
IMFActivate *pActivate, // Media sink activation object.
DWORD dwId, // Identifier of the stream sink.
IMFTopologyNode **ppNode) // Receives the node pointer.
{
IMFTopologyNode *pNode = NULL;
HRESULT hr = S_OK;
CHECK_HR(hr = MFCreateTopologyNode(MF_TOPOLOGY_OUTPUT_NODE, &pNode));
CHECK_HR(hr = pNode->SetObject(pActivate));
CHECK_HR(hr = pNode->SetUINT32(MF_TOPONODE_STREAMID, dwId));
CHECK_HR(hr = pNode->SetUINT32(MF_TOPONODE_NOSHUTDOWN_ON_REMOVE, FALSE));
CHECK_HR(hr = pTopology->AddNode(pNode));
// Return the pointer to the caller.
*ppNode = pNode;
(*ppNode)->AddRef();
done:
SafeRelease(&pNode);
return hr;
}
HRESULT WinMfImageGrabber::startGrabbing(void) {
PROPVARIANT var;
PropVariantInit(&var);
HRESULT hr = S_OK;
hr = ig_pSession->SetTopology(0, ig_pTopology);
hr = ig_pSession->Start(&GUID_NULL, &var);
return hr;
}
bool WinMfImageGrabber::processGrabbing() {
HRESULT hrStatus = S_OK;
MediaEventType met;
HRESULT hr;
IMFMediaEvent *pEvent = NULL;
if(!ig_pSession) return false;
hr = ig_pSession->GetEvent(0, &pEvent);
if(!SUCCEEDED(hr)) {
hr = S_OK;
return false;
}
hr = pEvent->GetStatus(&hrStatus);
if(!SUCCEEDED(hr)) {
hr = S_OK;
return false;
}
hr = pEvent->GetType(&met);
if(!SUCCEEDED(hr)) {
hr = S_OK;
return false;
}
if(met == MESessionEnded) {
LogInfo() << "IMAGEGRABBER VIDEODEVICE %i: MESessionEnded ";
ig_pSession->Stop();
return false;
}
if(met == MESessionStopped) {
LogInfo() << "IMAGEGRABBER VIDEODEVICE %i: MESessionStopped";
return false;
}
if(met == MEVideoCaptureDeviceRemoved) {
LogInfo() << "IMAGEGRABBER VIDEODEVICE %i: MEVideoCaptureDeviceRemoved";
return false;
}
SafeRelease(&pEvent);
return true;
}
void WinMfImageGrabber::stopGrabbing() {
if(ig_pSession) {
ig_pSession->Stop();
ig_pSession->Shutdown();
SAFE_RELEASE(ig_pSession);
SAFE_RELEASE(ig_pTopology);
}
/*IMFMediaSource *ig_pSource;
IMFMediaSession *ig_pSession;
IMFTopology *ig_pTopology;*/
}
// IUnknown methods
STDMETHODIMP WinMfImageGrabber::QueryInterface(REFIID iid, void** ppv) {
// Creation tab of shifting interfaces from start of this class
static const QITAB qit[] = {
QITABENT(WinMfImageGrabber, IMFSampleGrabberSinkCallback),
QITABENT(WinMfImageGrabber, IMFClockStateSink), { 0 }
};
return QISearch(this, qit, iid, ppv);
}
STDMETHODIMP_(ULONG) WinMfImageGrabber::AddRef() {
return InterlockedIncrement(&m_cRef);
}
STDMETHODIMP_(ULONG) WinMfImageGrabber::Release() {
ULONG cRef = InterlockedDecrement(&m_cRef);
if(cRef == 0) {
delete this;
}
return cRef;
}
// IMFClockStateSink methods
STDMETHODIMP WinMfImageGrabber::OnClockStart(MFTIME hnsSystemTime, LONGLONG llClockStartOffset) {
return S_OK;
}
STDMETHODIMP WinMfImageGrabber::OnClockStop(MFTIME hnsSystemTime) {
return S_OK;
}
STDMETHODIMP WinMfImageGrabber::OnClockPause(MFTIME hnsSystemTime) {
return S_OK;
}
STDMETHODIMP WinMfImageGrabber::OnClockRestart(MFTIME hnsSystemTime) {
return S_OK;
}
STDMETHODIMP WinMfImageGrabber::OnClockSetRate(MFTIME hnsSystemTime, float flRate) {
return S_OK;
}
// IMFSampleGrabberSinkCallback methods
STDMETHODIMP WinMfImageGrabber::OnSetPresentationClock(IMFPresentationClock* pClock) {
return S_OK;
}
STDMETHODIMP WinMfImageGrabber::OnProcessSample(REFGUID guidMajorMediaType, DWORD dwSampleFlags,
LONGLONG llSampleTime, LONGLONG llSampleDuration, const BYTE * pSampleBuffer,
DWORD dwSampleSize)
{
LogInfo() << "Process sample";
buffer_active->SetData((void*)pSampleBuffer);
camera->OnImageGrabbed(this, buffer_active);
return 0;
}
STDMETHODIMP WinMfImageGrabber::OnShutdown() {
return S_OK;
}
}
+65
View File
@@ -0,0 +1,65 @@
#ifndef WinMfImageGrabber_h__
#define WinMfImageGrabber_h__
#include <mfidl.h>
#include "../RawBuffer.h"
#include "../Types.h"
namespace LifeCore {
class WebCamera;
class WinMfImageGrabber : IMFSampleGrabberSinkCallback {
public:
WinMfImageGrabber(WebCamera* cam);
~WinMfImageGrabber();
HRESULT initImageGrabber(IMFMediaSource *pSource, GUID VideoFormat);
HRESULT startGrabbing(void);
void stopGrabbing();
// IUnknown methods
STDMETHODIMP QueryInterface(REFIID iid, void** ppv);
STDMETHODIMP_(ULONG) AddRef();
STDMETHODIMP_(ULONG) Release();
// IMFClockStateSink methods
STDMETHODIMP OnClockStart(MFTIME hnsSystemTime, LONGLONG llClockStartOffset);
STDMETHODIMP OnClockStop(MFTIME hnsSystemTime);
STDMETHODIMP OnClockPause(MFTIME hnsSystemTime);
STDMETHODIMP OnClockRestart(MFTIME hnsSystemTime);
STDMETHODIMP OnClockSetRate(MFTIME hnsSystemTime, float flRate);
// IMFSampleGrabberSinkCallback methods
STDMETHODIMP OnSetPresentationClock(IMFPresentationClock* pClock);
STDMETHODIMP OnProcessSample(REFGUID guidMajorMediaType, DWORD dwSampleFlags,
LONGLONG llSampleTime, LONGLONG llSampleDuration, const BYTE * pSampleBuffer,
DWORD dwSampleSize);
STDMETHODIMP OnShutdown();
bool processGrabbing();
RawBuffer<uint8>* GetImage();
private:
WebCamera* camera;
long m_cRef;
//IMFMediaSource *ig_pSource;
IMFMediaSession *ig_pSession;
IMFTopology *ig_pTopology;
RawBuffer<uint8>* buffer_first;
RawBuffer<uint8>* buffer_second;
RawBuffer<uint8>* buffer_active;
HRESULT CreateTopology(IMFMediaSource *pSource, IMFActivate *pSinkActivate, IMFTopology **ppTopo);
HRESULT AddSourceNode(
IMFTopology *pTopology,
IMFMediaSource *pSource,
IMFPresentationDescriptor *pPD,
IMFStreamDescriptor *pSD,
IMFTopologyNode **ppNode);
HRESULT AddOutputNode(
IMFTopology *pTopology,
IMFActivate *pActivate,
DWORD dwId,
IMFTopologyNode **ppNode);
};
}
#endif // WinMfImageGrabber_h__
+129
View File
@@ -0,0 +1,129 @@
#ifndef WinMfMediaType_h__
#define WinMfMediaType_h__
#include <guiddef.h>
namespace LifeCore {
// Structure for collecting info about types of video, which are supported by current video device
struct WinMfMediaType {
unsigned int MF_MT_FRAME_SIZE;
unsigned int height;
unsigned int width;
unsigned int MF_MT_YUV_MATRIX;
unsigned int MF_MT_VIDEO_LIGHTING;
unsigned int MF_MT_DEFAULT_STRIDE;
unsigned int MF_MT_VIDEO_CHROMA_SITING;
GUID MF_MT_AM_FORMAT_TYPE;
wchar_t *pMF_MT_AM_FORMAT_TYPEName;
unsigned int MF_MT_FIXED_SIZE_SAMPLES;
unsigned int MF_MT_VIDEO_NOMINAL_RANGE;
unsigned int MF_MT_FRAME_RATE;
unsigned int MF_MT_FRAME_RATE_low;
unsigned int MF_MT_PIXEL_ASPECT_RATIO;
unsigned int MF_MT_PIXEL_ASPECT_RATIO_low;
unsigned int MF_MT_ALL_SAMPLES_INDEPENDENT;
unsigned int MF_MT_FRAME_RATE_RANGE_MIN;
unsigned int MF_MT_FRAME_RATE_RANGE_MIN_low;
unsigned int MF_MT_SAMPLE_SIZE;
unsigned int MF_MT_VIDEO_PRIMARIES;
unsigned int MF_MT_INTERLACE_MODE;
unsigned int MF_MT_FRAME_RATE_RANGE_MAX;
unsigned int MF_MT_FRAME_RATE_RANGE_MAX_low;
GUID MF_MT_MAJOR_TYPE;
wchar_t *pMF_MT_MAJOR_TYPEName;
GUID MF_MT_SUBTYPE;
wchar_t *pMF_MT_SUBTYPEName;
WinMfMediaType() {
pMF_MT_AM_FORMAT_TYPEName = NULL;
pMF_MT_MAJOR_TYPEName = NULL;
pMF_MT_SUBTYPEName = NULL;
Clear();
}
~WinMfMediaType() {
Clear();
}
void Clear() {
MF_MT_FRAME_SIZE = 0;
height = 0;
width = 0;
MF_MT_YUV_MATRIX = 0;
MF_MT_VIDEO_LIGHTING = 0;
MF_MT_DEFAULT_STRIDE = 0;
MF_MT_VIDEO_CHROMA_SITING = 0;
MF_MT_FIXED_SIZE_SAMPLES = 0;
MF_MT_VIDEO_NOMINAL_RANGE = 0;
MF_MT_FRAME_RATE = 0;
MF_MT_FRAME_RATE_low = 0;
MF_MT_PIXEL_ASPECT_RATIO = 0;
MF_MT_PIXEL_ASPECT_RATIO_low = 0;
MF_MT_ALL_SAMPLES_INDEPENDENT = 0;
MF_MT_FRAME_RATE_RANGE_MIN = 0;
MF_MT_FRAME_RATE_RANGE_MIN_low = 0;
MF_MT_SAMPLE_SIZE = 0;
MF_MT_VIDEO_PRIMARIES = 0;
MF_MT_INTERLACE_MODE = 0;
MF_MT_FRAME_RATE_RANGE_MAX = 0;
MF_MT_FRAME_RATE_RANGE_MAX_low = 0;
memset(&MF_MT_MAJOR_TYPE, 0, sizeof(GUID));
memset(&MF_MT_AM_FORMAT_TYPE, 0, sizeof(GUID));
memset(&MF_MT_SUBTYPE, 0, sizeof(GUID));
}
};
}
#endif // WinMfMediaType_h__
+129
View File
@@ -0,0 +1,129 @@
/* crypt.h -- base code for crypt/uncrypt ZIPfile
Version 1.01e, February 12th, 2005
Copyright (C) 1998-2005 Gilles Vollant
This code is a modified version of crypting code in Infozip distribution
The encryption/decryption parts of this source code (as opposed to the
non-echoing password parts) were originally written in Europe. The
whole source package can be freely distributed, including from the USA.
(Prior to January 2000, re-export from the US was a violation of US law.)
This encryption code is a direct transcription of the algorithm from
Roger Schlafly, described by Phil Katz in the file appnote.txt. This
file (appnote.txt) is distributed with the PKZIP program (even in the
version without encryption capabilities).
If you don't need crypting in your application, just define symbols
NOCRYPT and NOUNCRYPT.
This code support the "Traditional PKWARE Encryption".
The new AES encryption added on Zip format by Winzip (see the page
http://www.winzip.com/aes_info.htm ) and PKWare PKZip 5.x Strong
Encryption is not supported.
*/
#define CRC32(c, b) ((*(pcrc_32_tab+(((int)(c) ^ (b)) & 0xff))) ^ ((c) >> 8))
/***********************************************************************
* Return the next byte in the pseudo-random sequence
*/
static int decrypt_byte(unsigned long* pkeys, const unsigned long* pcrc_32_tab)
{
unsigned temp; /* POTENTIAL BUG: temp*(temp^1) may overflow in an
* unpredictable manner on 16-bit systems; not a problem
* with any known compiler so far, though */
temp = ((unsigned)(*(pkeys+2)) & 0xffff) | 2;
return (int)(((temp * (temp ^ 1)) >> 8) & 0xff);
}
/***********************************************************************
* Update the encryption keys with the next byte of plain text
*/
static int update_keys(unsigned long* pkeys,const unsigned long* pcrc_32_tab,int c)
{
(*(pkeys+0)) = CRC32((*(pkeys+0)), c);
(*(pkeys+1)) += (*(pkeys+0)) & 0xff;
(*(pkeys+1)) = (*(pkeys+1)) * 134775813L + 1;
{
register int keyshift = (int)((*(pkeys+1)) >> 24);
(*(pkeys+2)) = CRC32((*(pkeys+2)), keyshift);
}
return c;
}
/***********************************************************************
* Initialize the encryption keys and the random header according to
* the given password.
*/
static void init_keys(const char* passwd,unsigned long* pkeys,const unsigned long* pcrc_32_tab)
{
*(pkeys+0) = 305419896L;
*(pkeys+1) = 591751049L;
*(pkeys+2) = 878082192L;
while (*passwd != '\0') {
update_keys(pkeys,pcrc_32_tab,(int)*passwd);
passwd++;
}
}
#define zdecode(pkeys,pcrc_32_tab,c) \
(update_keys(pkeys,pcrc_32_tab,c ^= decrypt_byte(pkeys,pcrc_32_tab)))
#define zencode(pkeys,pcrc_32_tab,c,t) \
(t=decrypt_byte(pkeys,pcrc_32_tab), update_keys(pkeys,pcrc_32_tab,c), t^(c))
#ifdef INCLUDECRYPTINGCODE_IFCRYPTALLOWED
#define RAND_HEAD_LEN 12
/* "last resort" source for second part of crypt seed pattern */
# ifndef ZCR_SEED2
# define ZCR_SEED2 3141592654UL /* use PI as default pattern */
# endif
static int crypthead(const char* passwd, /* password string */
unsigned char* buf, /* where to write header */
int bufSize,
unsigned long* pkeys,
const unsigned long* pcrc_32_tab,
unsigned long crcForCrypting)
{
int n; /* index in random header */
int t; /* temporary */
int c; /* random byte */
unsigned char header[RAND_HEAD_LEN-2]; /* random header */
static unsigned calls = 0; /* ensure different random header each time */
if (bufSize<RAND_HEAD_LEN)
return 0;
/* First generate RAND_HEAD_LEN-2 random bytes. We encrypt the
* output of rand() to get less predictability, since rand() is
* often poorly implemented.
*/
if (++calls == 1)
{
srand((unsigned)(time(NULL) ^ ZCR_SEED2));
}
init_keys(passwd, pkeys, pcrc_32_tab);
for (n = 0; n < RAND_HEAD_LEN-2; n++)
{
c = (rand() >> 7) & 0xff;
header[n] = (unsigned char)zencode(pkeys, pcrc_32_tab, c, t);
}
/* Encrypt random header (last two bytes is high word of crc) */
init_keys(passwd, pkeys, pcrc_32_tab);
for (n = 0; n < RAND_HEAD_LEN-2; n++)
{
buf[n] = (unsigned char)zencode(pkeys, pcrc_32_tab, header[n], t);
}
buf[n++] = (unsigned char)zencode(pkeys, pcrc_32_tab, (int)(crcForCrypting >> 16) & 0xff, t);
buf[n++] = (unsigned char)zencode(pkeys, pcrc_32_tab, (int)(crcForCrypting >> 24) & 0xff, t);
return n;
}
#endif
+230
View File
@@ -0,0 +1,230 @@
/* ioapi.h -- IO base function header for compress/uncompress .zip
part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
Modifications for Zip64 support
Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
For more info read MiniZip_info.txt
*/
#if (defined(_WIN32))
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "ioapi.h"
voidpf call_zopen64 (const zlib_filefunc64_32_def* pfilefunc,const void*filename,int mode)
{
if (pfilefunc->zfile_func64.zopen64_file != NULL)
return (*(pfilefunc->zfile_func64.zopen64_file)) (pfilefunc->zfile_func64.opaque,filename,mode);
else
{
return (*(pfilefunc->zopen32_file))(pfilefunc->zfile_func64.opaque,(const char*)filename,mode);
}
}
long call_zseek64 (const zlib_filefunc64_32_def* pfilefunc,voidpf filestream, ZPOS64_T offset, int origin)
{
if (pfilefunc->zfile_func64.zseek64_file != NULL)
return (*(pfilefunc->zfile_func64.zseek64_file)) (pfilefunc->zfile_func64.opaque,filestream,offset,origin);
else
{
uLong offsetTruncated = (uLong)offset;
if (offsetTruncated != offset)
return -1;
else
return (*(pfilefunc->zseek32_file))(pfilefunc->zfile_func64.opaque,filestream,offsetTruncated,origin);
}
}
ZPOS64_T call_ztell64 (const zlib_filefunc64_32_def* pfilefunc,voidpf filestream)
{
if (pfilefunc->zfile_func64.zseek64_file != NULL)
return (*(pfilefunc->zfile_func64.ztell64_file)) (pfilefunc->zfile_func64.opaque,filestream);
else
{
uLong tell_uLong = (*(pfilefunc->ztell32_file))(pfilefunc->zfile_func64.opaque,filestream);
if ((tell_uLong) == ((uLong)-1))
return (ZPOS64_T)-1;
else
return tell_uLong;
}
}
void fill_zlib_filefunc64_32_def_from_filefunc32(zlib_filefunc64_32_def* p_filefunc64_32,const zlib_filefunc_def* p_filefunc32)
{
p_filefunc64_32->zfile_func64.zopen64_file = NULL;
p_filefunc64_32->zopen32_file = p_filefunc32->zopen_file;
p_filefunc64_32->zfile_func64.zerror_file = p_filefunc32->zerror_file;
p_filefunc64_32->zfile_func64.zread_file = p_filefunc32->zread_file;
p_filefunc64_32->zfile_func64.zwrite_file = p_filefunc32->zwrite_file;
p_filefunc64_32->zfile_func64.ztell64_file = NULL;
p_filefunc64_32->zfile_func64.zseek64_file = NULL;
p_filefunc64_32->zfile_func64.zclose_file = p_filefunc32->zclose_file;
p_filefunc64_32->zfile_func64.zerror_file = p_filefunc32->zerror_file;
p_filefunc64_32->zfile_func64.opaque = p_filefunc32->opaque;
p_filefunc64_32->zseek32_file = p_filefunc32->zseek_file;
p_filefunc64_32->ztell32_file = p_filefunc32->ztell_file;
}
static voidpf ZCALLBACK fopen_file_func OF((voidpf opaque, const char* filename, int mode));
static uLong ZCALLBACK fread_file_func OF((voidpf opaque, voidpf stream, void* buf, uLong size));
static uLong ZCALLBACK fwrite_file_func OF((voidpf opaque, voidpf stream, const void* buf,uLong size));
static ZPOS64_T ZCALLBACK ftell64_file_func OF((voidpf opaque, voidpf stream));
static long ZCALLBACK fseek64_file_func OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin));
static int ZCALLBACK fclose_file_func OF((voidpf opaque, voidpf stream));
static int ZCALLBACK ferror_file_func OF((voidpf opaque, voidpf stream));
static voidpf ZCALLBACK fopen_file_func (voidpf opaque, const char* filename, int mode)
{
FILE* file = NULL;
const char* mode_fopen = NULL;
if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ)
mode_fopen = "rb";
else
if (mode & ZLIB_FILEFUNC_MODE_EXISTING)
mode_fopen = "r+b";
else
if (mode & ZLIB_FILEFUNC_MODE_CREATE)
mode_fopen = "wb";
if ((filename!=NULL) && (mode_fopen != NULL))
file = fopen(filename, mode_fopen);
return file;
}
static voidpf ZCALLBACK fopen64_file_func (voidpf opaque, const void* filename, int mode)
{
FILE* file = NULL;
const char* mode_fopen = NULL;
if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ)
mode_fopen = "rb";
else
if (mode & ZLIB_FILEFUNC_MODE_EXISTING)
mode_fopen = "r+b";
else
if (mode & ZLIB_FILEFUNC_MODE_CREATE)
mode_fopen = "wb";
if ((filename!=NULL) && (mode_fopen != NULL))
file = fopen64((const char*)filename, mode_fopen);
return file;
}
static uLong ZCALLBACK fread_file_func (voidpf opaque, voidpf stream, void* buf, uLong size)
{
uLong ret;
ret = (uLong)fread(buf, 1, (size_t)size, (FILE *)stream);
return ret;
}
static uLong ZCALLBACK fwrite_file_func (voidpf opaque, voidpf stream, const void* buf, uLong size)
{
uLong ret;
ret = (uLong)fwrite(buf, 1, (size_t)size, (FILE *)stream);
return ret;
}
static long ZCALLBACK ftell_file_func (voidpf opaque, voidpf stream)
{
long ret;
ret = ftell((FILE *)stream);
return ret;
}
static ZPOS64_T ZCALLBACK ftell64_file_func (voidpf opaque, voidpf stream)
{
ZPOS64_T ret;
ret = ftello64((FILE *)stream);
return ret;
}
static long ZCALLBACK fseek_file_func (voidpf opaque, voidpf stream, uLong offset, int origin)
{
int fseek_origin=0;
long ret;
switch (origin)
{
case ZLIB_FILEFUNC_SEEK_CUR :
fseek_origin = SEEK_CUR;
break;
case ZLIB_FILEFUNC_SEEK_END :
fseek_origin = SEEK_END;
break;
case ZLIB_FILEFUNC_SEEK_SET :
fseek_origin = SEEK_SET;
break;
default: return -1;
}
ret = 0;
if (fseek((FILE *)stream, offset, fseek_origin) != 0)
ret = -1;
return ret;
}
static long ZCALLBACK fseek64_file_func (voidpf opaque, voidpf stream, ZPOS64_T offset, int origin)
{
int fseek_origin=0;
long ret;
switch (origin)
{
case ZLIB_FILEFUNC_SEEK_CUR :
fseek_origin = SEEK_CUR;
break;
case ZLIB_FILEFUNC_SEEK_END :
fseek_origin = SEEK_END;
break;
case ZLIB_FILEFUNC_SEEK_SET :
fseek_origin = SEEK_SET;
break;
default: return -1;
}
ret = 0;
if(fseeko64((FILE *)stream, offset, fseek_origin) != 0)
ret = -1;
return ret;
}
static int ZCALLBACK fclose_file_func (voidpf opaque, voidpf stream)
{
int ret;
ret = fclose((FILE *)stream);
return ret;
}
static int ZCALLBACK ferror_file_func (voidpf opaque, voidpf stream)
{
int ret;
ret = ferror((FILE *)stream);
return ret;
}
void fill_fopen_filefunc (pzlib_filefunc_def)
zlib_filefunc_def* pzlib_filefunc_def;
{
pzlib_filefunc_def->zopen_file = fopen_file_func;
pzlib_filefunc_def->zread_file = fread_file_func;
pzlib_filefunc_def->zwrite_file = fwrite_file_func;
pzlib_filefunc_def->ztell_file = ftell_file_func;
pzlib_filefunc_def->zseek_file = fseek_file_func;
pzlib_filefunc_def->zclose_file = fclose_file_func;
pzlib_filefunc_def->zerror_file = ferror_file_func;
pzlib_filefunc_def->opaque = NULL;
}
void fill_fopen64_filefunc (zlib_filefunc64_def* pzlib_filefunc_def)
{
pzlib_filefunc_def->zopen64_file = fopen64_file_func;
pzlib_filefunc_def->zread_file = fread_file_func;
pzlib_filefunc_def->zwrite_file = fwrite_file_func;
pzlib_filefunc_def->ztell64_file = ftell64_file_func;
pzlib_filefunc_def->zseek64_file = fseek64_file_func;
pzlib_filefunc_def->zclose_file = fclose_file_func;
pzlib_filefunc_def->zerror_file = ferror_file_func;
pzlib_filefunc_def->opaque = NULL;
}
+190
View File
@@ -0,0 +1,190 @@
/* ioapi.h -- IO base function header for compress/uncompress .zip
part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
Modifications for Zip64 support
Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
For more info read MiniZip_info.txt
Changes
Oct-2009 - Defined ZPOS64_T to fpos_t on windows and u_int64_t on linux. (might need to find a better why for this)
Oct-2009 - Change to fseeko64, ftello64 and fopen64 so large files would work on linux.
More if/def section may be needed to support other platforms
Oct-2009 - Defined fxxxx64 calls to normal fopen/ftell/fseek so they would compile on windows.
(but you should use iowin32.c for windows instead)
*/
#ifndef _ZLIBIOAPI64_H
#define _ZLIBIOAPI64_H
#if (!defined(_WIN32)) && (!defined(WIN32))
// Linux needs this to support file operation on files larger then 4+GB
// But might need better if/def to select just the platforms that needs them.
#ifndef __USE_FILE_OFFSET64
#define __USE_FILE_OFFSET64
#endif
#ifndef __USE_LARGEFILE64
#define __USE_LARGEFILE64
#endif
#ifndef _LARGEFILE64_SOURCE
#define _LARGEFILE64_SOURCE
#endif
#ifndef _FILE_OFFSET_BIT
#define _FILE_OFFSET_BIT 64
#endif
#endif
#include <stdio.h>
#include <stdlib.h>
#include "zlib.h"
#if defined(USE_FILE32API)
#define fopen64 fopen
#define ftello64 ftell
#define fseeko64 fseek
#else
#ifdef _MSC_VER
#define fopen64 fopen
#if (_MSC_VER >= 1400) && (!(defined(NO_MSCVER_FILE64_FUNC)))
#define ftello64 _ftelli64
#define fseeko64 _fseeki64
#else // old MSC
#define ftello64 ftell
#define fseeko64 fseek
#endif
#endif
#endif
/*
#ifndef ZPOS64_T
#ifdef _WIN32
#define ZPOS64_T fpos_t
#else
#include <stdint.h>
#define ZPOS64_T uint64_t
#endif
#endif
*/
#ifdef HAVE_MINIZIP64_CONF_H
#include "mz64conf.h"
#endif
/* a type choosen by DEFINE */
#ifdef HAVE_64BIT_INT_CUSTOM
typedef 64BIT_INT_CUSTOM_TYPE ZPOS64_T;
#else
#ifdef HAS_STDINT_H
#include "stdint.h"
typedef uint64_t ZPOS64_T;
#else
#if defined(_MSC_VER) || defined(__BORLANDC__)
typedef unsigned __int64 ZPOS64_T;
#else
typedef unsigned long long int ZPOS64_T;
#endif
#endif
#endif
#ifdef __cplusplus
extern "C" {
#endif
#define ZLIB_FILEFUNC_SEEK_CUR (1)
#define ZLIB_FILEFUNC_SEEK_END (2)
#define ZLIB_FILEFUNC_SEEK_SET (0)
#define ZLIB_FILEFUNC_MODE_READ (1)
#define ZLIB_FILEFUNC_MODE_WRITE (2)
#define ZLIB_FILEFUNC_MODE_READWRITEFILTER (3)
#define ZLIB_FILEFUNC_MODE_EXISTING (4)
#define ZLIB_FILEFUNC_MODE_CREATE (8)
#ifndef ZCALLBACK
#if (defined(WIN32) || defined(_WIN32) || defined (WINDOWS) || defined (_WINDOWS)) && defined(CALLBACK) && defined (USEWINDOWS_CALLBACK)
#define ZCALLBACK CALLBACK
#else
#define ZCALLBACK
#endif
#endif
typedef voidpf (ZCALLBACK *open_file_func) OF((voidpf opaque, const char* filename, int mode));
typedef uLong (ZCALLBACK *read_file_func) OF((voidpf opaque, voidpf stream, void* buf, uLong size));
typedef uLong (ZCALLBACK *write_file_func) OF((voidpf opaque, voidpf stream, const void* buf, uLong size));
typedef int (ZCALLBACK *close_file_func) OF((voidpf opaque, voidpf stream));
typedef int (ZCALLBACK *testerror_file_func) OF((voidpf opaque, voidpf stream));
typedef long (ZCALLBACK *tell_file_func) OF((voidpf opaque, voidpf stream));
typedef long (ZCALLBACK *seek_file_func) OF((voidpf opaque, voidpf stream, uLong offset, int origin));
/* here is the "old" 32 bits structure structure */
typedef struct zlib_filefunc_def_s
{
open_file_func zopen_file;
read_file_func zread_file;
write_file_func zwrite_file;
tell_file_func ztell_file;
seek_file_func zseek_file;
close_file_func zclose_file;
testerror_file_func zerror_file;
voidpf opaque;
} zlib_filefunc_def;
typedef ZPOS64_T (ZCALLBACK *tell64_file_func) OF((voidpf opaque, voidpf stream));
typedef long (ZCALLBACK *seek64_file_func) OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin));
typedef voidpf (ZCALLBACK *open64_file_func) OF((voidpf opaque, const void* filename, int mode));
typedef struct zlib_filefunc64_def_s
{
open64_file_func zopen64_file;
read_file_func zread_file;
write_file_func zwrite_file;
tell64_file_func ztell64_file;
seek64_file_func zseek64_file;
close_file_func zclose_file;
testerror_file_func zerror_file;
voidpf opaque;
} zlib_filefunc64_def;
void fill_fopen64_filefunc OF((zlib_filefunc64_def* pzlib_filefunc_def));
void fill_fopen_filefunc OF((zlib_filefunc_def* pzlib_filefunc_def));
/* now internal definition, only for zip.c and unzip.h */
typedef struct zlib_filefunc64_32_def_s
{
zlib_filefunc64_def zfile_func64;
open_file_func zopen32_file;
tell_file_func ztell32_file;
seek_file_func zseek32_file;
} zlib_filefunc64_32_def;
#define ZREAD64(filefunc,filestream,buf,size) ((*((filefunc).zfile_func64.zread_file)) ((filefunc).zfile_func64.opaque,filestream,buf,size))
#define ZWRITE64(filefunc,filestream,buf,size) ((*((filefunc).zfile_func64.zwrite_file)) ((filefunc).zfile_func64.opaque,filestream,buf,size))
//#define ZTELL64(filefunc,filestream) ((*((filefunc).ztell64_file)) ((filefunc).opaque,filestream))
//#define ZSEEK64(filefunc,filestream,pos,mode) ((*((filefunc).zseek64_file)) ((filefunc).opaque,filestream,pos,mode))
#define ZCLOSE64(filefunc,filestream) ((*((filefunc).zfile_func64.zclose_file)) ((filefunc).zfile_func64.opaque,filestream))
#define ZERROR64(filefunc,filestream) ((*((filefunc).zfile_func64.zerror_file)) ((filefunc).zfile_func64.opaque,filestream))
voidpf call_zopen64 OF((const zlib_filefunc64_32_def* pfilefunc,const void*filename,int mode));
long call_zseek64 OF((const zlib_filefunc64_32_def* pfilefunc,voidpf filestream, ZPOS64_T offset, int origin));
ZPOS64_T call_ztell64 OF((const zlib_filefunc64_32_def* pfilefunc,voidpf filestream));
void fill_zlib_filefunc64_32_def_from_filefunc32(zlib_filefunc64_32_def* p_filefunc64_32,const zlib_filefunc_def* p_filefunc32);
#define ZOPEN64(filefunc,filename,mode) (call_zopen64((&(filefunc)),(filename),(mode)))
#define ZTELL64(filefunc,filestream) (call_ztell64((&(filefunc)),(filestream)))
#define ZSEEK64(filefunc,filestream,pos,mode) (call_zseek64((&(filefunc)),(filestream),(pos),(mode)))
#ifdef __cplusplus
}
#endif
#endif
+380
View File
@@ -0,0 +1,380 @@
/* iowin32.c -- IO base function header for compress/uncompress .zip
Version 1.1, February 14h, 2010
part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
Modifications for Zip64 support
Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
For more info read MiniZip_info.txt
*/
#include <stdlib.h>
#include "zlib.h"
#include "ioapi.h"
#include "iowin32.h"
#ifndef INVALID_HANDLE_VALUE
#define INVALID_HANDLE_VALUE (0xFFFFFFFF)
#endif
#ifndef INVALID_SET_FILE_POINTER
#define INVALID_SET_FILE_POINTER ((DWORD)-1)
#endif
voidpf ZCALLBACK win32_open_file_func OF((voidpf opaque, const char* filename, int mode));
uLong ZCALLBACK win32_read_file_func OF((voidpf opaque, voidpf stream, void* buf, uLong size));
uLong ZCALLBACK win32_write_file_func OF((voidpf opaque, voidpf stream, const void* buf, uLong size));
ZPOS64_T ZCALLBACK win32_tell64_file_func OF((voidpf opaque, voidpf stream));
long ZCALLBACK win32_seek64_file_func OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin));
int ZCALLBACK win32_close_file_func OF((voidpf opaque, voidpf stream));
int ZCALLBACK win32_error_file_func OF((voidpf opaque, voidpf stream));
typedef struct
{
HANDLE hf;
int error;
} WIN32FILE_IOWIN;
static void win32_translate_open_mode(int mode,
DWORD* lpdwDesiredAccess,
DWORD* lpdwCreationDisposition,
DWORD* lpdwShareMode,
DWORD* lpdwFlagsAndAttributes)
{
*lpdwDesiredAccess = *lpdwShareMode = *lpdwFlagsAndAttributes = *lpdwCreationDisposition = 0;
if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ)
{
*lpdwDesiredAccess = GENERIC_READ;
*lpdwCreationDisposition = OPEN_EXISTING;
*lpdwShareMode = FILE_SHARE_READ;
}
else if (mode & ZLIB_FILEFUNC_MODE_EXISTING)
{
*lpdwDesiredAccess = GENERIC_WRITE | GENERIC_READ;
*lpdwCreationDisposition = OPEN_EXISTING;
}
else if (mode & ZLIB_FILEFUNC_MODE_CREATE)
{
*lpdwDesiredAccess = GENERIC_WRITE | GENERIC_READ;
*lpdwCreationDisposition = CREATE_ALWAYS;
}
}
static voidpf win32_build_iowin(HANDLE hFile)
{
voidpf ret=NULL;
if ((hFile != NULL) && (hFile != INVALID_HANDLE_VALUE))
{
WIN32FILE_IOWIN w32fiow;
w32fiow.hf = hFile;
w32fiow.error = 0;
ret = malloc(sizeof(WIN32FILE_IOWIN));
if (ret==NULL)
CloseHandle(hFile);
else
*((WIN32FILE_IOWIN*)ret) = w32fiow;
}
return ret;
}
voidpf ZCALLBACK win32_open64_file_func (voidpf opaque,const void* filename,int mode)
{
const char* mode_fopen = NULL;
DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ;
HANDLE hFile = NULL;
win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes);
if ((filename!=NULL) && (dwDesiredAccess != 0))
hFile = CreateFile((LPCTSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL);
return win32_build_iowin(hFile);
}
voidpf ZCALLBACK win32_open64_file_funcA (voidpf opaque,const void* filename,int mode)
{
const char* mode_fopen = NULL;
DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ;
HANDLE hFile = NULL;
win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes);
if ((filename!=NULL) && (dwDesiredAccess != 0))
hFile = CreateFileA((LPCSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL);
return win32_build_iowin(hFile);
}
voidpf ZCALLBACK win32_open64_file_funcW (voidpf opaque,const void* filename,int mode)
{
const char* mode_fopen = NULL;
DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ;
HANDLE hFile = NULL;
win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes);
if ((filename!=NULL) && (dwDesiredAccess != 0))
hFile = CreateFileW((LPCWSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL);
return win32_build_iowin(hFile);
}
voidpf ZCALLBACK win32_open_file_func (voidpf opaque,const char* filename,int mode)
{
const char* mode_fopen = NULL;
DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ;
HANDLE hFile = NULL;
win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes);
if ((filename!=NULL) && (dwDesiredAccess != 0))
hFile = CreateFile((LPCTSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL);
return win32_build_iowin(hFile);
}
uLong ZCALLBACK win32_read_file_func (voidpf opaque, voidpf stream, void* buf,uLong size)
{
uLong ret=0;
HANDLE hFile = NULL;
if (stream!=NULL)
hFile = ((WIN32FILE_IOWIN*)stream) -> hf;
if (hFile != NULL)
{
if (!ReadFile(hFile, buf, size, &ret, NULL))
{
DWORD dwErr = GetLastError();
if (dwErr == ERROR_HANDLE_EOF)
dwErr = 0;
((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
}
}
return ret;
}
uLong ZCALLBACK win32_write_file_func (voidpf opaque,voidpf stream,const void* buf,uLong size)
{
uLong ret=0;
HANDLE hFile = NULL;
if (stream!=NULL)
hFile = ((WIN32FILE_IOWIN*)stream) -> hf;
if (hFile != NULL)
{
if (!WriteFile(hFile, buf, size, &ret, NULL))
{
DWORD dwErr = GetLastError();
if (dwErr == ERROR_HANDLE_EOF)
dwErr = 0;
((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
}
}
return ret;
}
long ZCALLBACK win32_tell_file_func (voidpf opaque,voidpf stream)
{
long ret=-1;
HANDLE hFile = NULL;
if (stream!=NULL)
hFile = ((WIN32FILE_IOWIN*)stream) -> hf;
if (hFile != NULL)
{
DWORD dwSet = SetFilePointer(hFile, 0, NULL, FILE_CURRENT);
if (dwSet == INVALID_SET_FILE_POINTER)
{
DWORD dwErr = GetLastError();
((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
ret = -1;
}
else
ret=(long)dwSet;
}
return ret;
}
ZPOS64_T ZCALLBACK win32_tell64_file_func (voidpf opaque, voidpf stream)
{
ZPOS64_T ret= (ZPOS64_T)-1;
HANDLE hFile = NULL;
if (stream!=NULL)
hFile = ((WIN32FILE_IOWIN*)stream)->hf;
if (hFile)
{
LARGE_INTEGER li;
li.QuadPart = 0;
li.u.LowPart = SetFilePointer(hFile, li.u.LowPart, &li.u.HighPart, FILE_CURRENT);
if ( (li.LowPart == 0xFFFFFFFF) && (GetLastError() != NO_ERROR))
{
DWORD dwErr = GetLastError();
((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
ret = (ZPOS64_T)-1;
}
else
ret=li.QuadPart;
}
return ret;
}
long ZCALLBACK win32_seek_file_func (voidpf opaque,voidpf stream,uLong offset,int origin)
{
DWORD dwMoveMethod=0xFFFFFFFF;
HANDLE hFile = NULL;
long ret=-1;
if (stream!=NULL)
hFile = ((WIN32FILE_IOWIN*)stream) -> hf;
switch (origin)
{
case ZLIB_FILEFUNC_SEEK_CUR :
dwMoveMethod = FILE_CURRENT;
break;
case ZLIB_FILEFUNC_SEEK_END :
dwMoveMethod = FILE_END;
break;
case ZLIB_FILEFUNC_SEEK_SET :
dwMoveMethod = FILE_BEGIN;
break;
default: return -1;
}
if (hFile != NULL)
{
DWORD dwSet = SetFilePointer(hFile, offset, NULL, dwMoveMethod);
if (dwSet == INVALID_SET_FILE_POINTER)
{
DWORD dwErr = GetLastError();
((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
ret = -1;
}
else
ret=0;
}
return ret;
}
long ZCALLBACK win32_seek64_file_func (voidpf opaque, voidpf stream,ZPOS64_T offset,int origin)
{
DWORD dwMoveMethod=0xFFFFFFFF;
HANDLE hFile = NULL;
long ret=-1;
if (stream!=NULL)
hFile = ((WIN32FILE_IOWIN*)stream)->hf;
switch (origin)
{
case ZLIB_FILEFUNC_SEEK_CUR :
dwMoveMethod = FILE_CURRENT;
break;
case ZLIB_FILEFUNC_SEEK_END :
dwMoveMethod = FILE_END;
break;
case ZLIB_FILEFUNC_SEEK_SET :
dwMoveMethod = FILE_BEGIN;
break;
default: return -1;
}
if (hFile)
{
LARGE_INTEGER* li = (LARGE_INTEGER*)&offset;
DWORD dwSet = SetFilePointer(hFile, li->u.LowPart, &li->u.HighPart, dwMoveMethod);
if (dwSet == INVALID_SET_FILE_POINTER)
{
DWORD dwErr = GetLastError();
((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
ret = -1;
}
else
ret=0;
}
return ret;
}
int ZCALLBACK win32_close_file_func (voidpf opaque, voidpf stream)
{
int ret=-1;
if (stream!=NULL)
{
HANDLE hFile;
hFile = ((WIN32FILE_IOWIN*)stream) -> hf;
if (hFile != NULL)
{
CloseHandle(hFile);
ret=0;
}
free(stream);
}
return ret;
}
int ZCALLBACK win32_error_file_func (voidpf opaque,voidpf stream)
{
int ret=-1;
if (stream!=NULL)
{
ret = ((WIN32FILE_IOWIN*)stream) -> error;
}
return ret;
}
void fill_win32_filefunc (zlib_filefunc_def* pzlib_filefunc_def)
{
pzlib_filefunc_def->zopen_file = win32_open_file_func;
pzlib_filefunc_def->zread_file = win32_read_file_func;
pzlib_filefunc_def->zwrite_file = win32_write_file_func;
pzlib_filefunc_def->ztell_file = win32_tell_file_func;
pzlib_filefunc_def->zseek_file = win32_seek_file_func;
pzlib_filefunc_def->zclose_file = win32_close_file_func;
pzlib_filefunc_def->zerror_file = win32_error_file_func;
pzlib_filefunc_def->opaque = NULL;
}
void fill_win32_filefunc64(zlib_filefunc64_def* pzlib_filefunc_def)
{
pzlib_filefunc_def->zopen64_file = win32_open64_file_func;
pzlib_filefunc_def->zread_file = win32_read_file_func;
pzlib_filefunc_def->zwrite_file = win32_write_file_func;
pzlib_filefunc_def->ztell64_file = win32_tell64_file_func;
pzlib_filefunc_def->zseek64_file = win32_seek64_file_func;
pzlib_filefunc_def->zclose_file = win32_close_file_func;
pzlib_filefunc_def->zerror_file = win32_error_file_func;
pzlib_filefunc_def->opaque = NULL;
}
void fill_win32_filefunc64A(zlib_filefunc64_def* pzlib_filefunc_def)
{
pzlib_filefunc_def->zopen64_file = win32_open64_file_funcA;
pzlib_filefunc_def->zread_file = win32_read_file_func;
pzlib_filefunc_def->zwrite_file = win32_write_file_func;
pzlib_filefunc_def->ztell64_file = win32_tell64_file_func;
pzlib_filefunc_def->zseek64_file = win32_seek64_file_func;
pzlib_filefunc_def->zclose_file = win32_close_file_func;
pzlib_filefunc_def->zerror_file = win32_error_file_func;
pzlib_filefunc_def->opaque = NULL;
}
void fill_win32_filefunc64W(zlib_filefunc64_def* pzlib_filefunc_def)
{
pzlib_filefunc_def->zopen64_file = win32_open64_file_funcW;
pzlib_filefunc_def->zread_file = win32_read_file_func;
pzlib_filefunc_def->zwrite_file = win32_write_file_func;
pzlib_filefunc_def->ztell64_file = win32_tell64_file_func;
pzlib_filefunc_def->zseek64_file = win32_seek64_file_func;
pzlib_filefunc_def->zclose_file = win32_close_file_func;
pzlib_filefunc_def->zerror_file = win32_error_file_func;
pzlib_filefunc_def->opaque = NULL;
}
+27
View File
@@ -0,0 +1,27 @@
/* iowin32.h -- IO base function header for compress/uncompress .zip
Version 1.1, February 14h, 2010
part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
Modifications for Zip64 support
Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
For more info read MiniZip_info.txt
*/
#include <windows.h>
#ifdef __cplusplus
extern "C" {
#endif
void fill_win32_filefunc OF((zlib_filefunc_def* pzlib_filefunc_def));
void fill_win32_filefunc64 OF((zlib_filefunc64_def* pzlib_filefunc_def));
void fill_win32_filefunc64A OF((zlib_filefunc64_def* pzlib_filefunc_def));
void fill_win32_filefunc64W OF((zlib_filefunc64_def* pzlib_filefunc_def));
#ifdef __cplusplus
}
#endif
+638
View File
@@ -0,0 +1,638 @@
/*
miniunz.c
Version 1.1, February 14h, 2010
sample part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
Modifications of Unzip for Zip64
Copyright (C) 2007-2008 Even Rouault
Modifications for Zip64 support on both zip and unzip
Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
#ifndef _WIN32
#ifndef __USE_FILE_OFFSET64
#define __USE_FILE_OFFSET64
#endif
#ifndef __USE_LARGEFILE64
#define __USE_LARGEFILE64
#endif
#ifndef _LARGEFILE64_SOURCE
#define _LARGEFILE64_SOURCE
#endif
#ifndef _FILE_OFFSET_BIT
#define _FILE_OFFSET_BIT 64
#endif
#endif
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <fcntl.h>
#ifdef unix
# include <unistd.h>
# include <utime.h>
#else
# include <direct.h>
# include <io.h>
#endif
#include "unzip.h"
#define CASESENSITIVITY (0)
#define WRITEBUFFERSIZE (8192)
#define MAXFILENAME (256)
#ifdef _WIN32
#define USEWIN32IOAPI
#include "iowin32.h"
#endif
mini unzip, demo of unzip package
usage :
Usage : miniunz [-exvlo] file.zip [file_to_extract] [-d extractdir]
list the file in the zipfile, and print the content of FILE_ID.ZIP or README.TXT
if it exists
change_file_date : change the date/time of a file
filename : the filename of the file where date/time must be modified
dosdate : the new date at the MSDos format (4 bytes)
tmu_date : the SAME new date at the tm_unz format void change_file_date(filename,dosdate,tmu_date)
const char *filename;
uLong dosdate;
tm_unz tmu_date;
{
#ifdef _WIN32
HANDLE hFile;
FILETIME ftm,ftLocal,ftCreate,ftLastAcc,ftLastWrite;
hFile = CreateFileA(filename,GENERIC_READ | GENERIC_WRITE,
0,NULL,OPEN_EXISTING,0,NULL);
GetFileTime(hFile,&ftCreate,&ftLastAcc,&ftLastWrite);
DosDateTimeToFileTime((WORD)(dosdate>>16),(WORD)dosdate,&ftLocal);
LocalFileTimeToFileTime(&ftLocal,&ftm);
SetFileTime(hFile,&ftm,&ftLastAcc,&ftm);
CloseHandle(hFile);
#else
#ifdef unix
struct utimbuf ut;
struct tm newdate;
newdate.tm_sec = tmu_date.tm_sec;
newdate.tm_min=tmu_date.tm_min;
newdate.tm_hour=tmu_date.tm_hour;
newdate.tm_mday=tmu_date.tm_mday;
newdate.tm_mon=tmu_date.tm_mon;
if (tmu_date.tm_year > 1900)
newdate.tm_year=tmu_date.tm_year - 1900;
else
newdate.tm_year=tmu_date.tm_year ;
newdate.tm_isdst=-1;
ut.actime=ut.modtime=mktime(&newdate);
utime(filename,&ut);
#endif
#endif
}
mymkdir and change_file_date are not 100 % portable
As I don't know well Unix, I wait feedback for the unix portion
int mymkdir(dirname)
const char* dirname;
{
int ret=0;
#ifdef _WIN32
ret = _mkdir(dirname);
#else
#ifdef unix
ret = mkdir (dirname,0775);
#endif
#endif
return ret;
}
int makedir (newdir)
char *newdir;
{
char *buffer ;
char *p;
int len = (int)strlen(newdir);
if (len <= 0)
return 0;
buffer = (char*)malloc(len+1);
if (buffer==NULL)
{
printf("Error allocating memory\n");
return UNZ_INTERNALERROR;
}
strcpy(buffer,newdir);
if (buffer[len-1] == '/') {
buffer[len-1] = '\0';
}
if (mymkdir(buffer) == 0)
{
free(buffer);
return 1;
}
p = buffer+1;
while (1)
{
char hold;
while(*p && *p != '\\' && *p != '/')
p++;
hold = *p;
*p = 0;
if ((mymkdir(buffer) == -1) && (errno == ENOENT))
{
printf("couldn't create directory %s\n",buffer);
free(buffer);
return 0;
}
if (hold == 0)
break;
*p++ = hold;
}
free(buffer);
return 1;
}
void do_banner()
{
printf("MiniUnz 1.01b, demo of zLib + Unz package written by Gilles Vollant\n");
printf("more info at http://www.winimage.com/zLibDll/unzip.html\n\n");
}
void do_help()
{
printf("Usage : miniunz [-e] [-x] [-v] [-l] [-o] [-p password] file.zip [file_to_extr.] [-d extractdir]\n\n" \
" -e Extract without pathname (junk paths)\n" \
" -x Extract with pathname\n" \
" -v list files\n" \
" -l list files\n" \
" -d directory to extract into\n" \
" -o overwrite files without prompting\n" \
" -p extract crypted file using password\n\n");
}
void Display64BitsSize(ZPOS64_T n, int size_char)
{
to avoid compatibility problem , we do here the conversion char number[21];
int offset=19;
int pos_string = 19;
number[20]=0;
for (;;) {
number[offset]=(char)((n%10)+'0');
if (number[offset] != '0')
pos_string=offset;
n/=10;
if (offset==0)
break;
offset--;
}
{
int size_display_string = 19-pos_string;
while (size_char > size_display_string)
{
size_char--;
printf(" ");
}
}
printf("%s",&number[pos_string]);
}
int do_list(uf)
unzFile uf;
{
uLong i;
unz_global_info64 gi;
int err;
err = unzGetGlobalInfo64(uf,&gi);
if (err!=UNZ_OK)
printf("error %d with zipfile in unzGetGlobalInfo \n",err);
printf(" Length Method Size Ratio Date Time CRC-32 Name\n");
printf(" ------ ------ ---- ----- ---- ---- ------ ----\n");
for (i=0;i<gi.number_entry;i++)
{
char filename_inzip[256];
unz_file_info64 file_info;
uLong ratio=0;
const char *string_method;
char charCrypt=' ';
err = unzGetCurrentFileInfo64(uf,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0);
if (err!=UNZ_OK)
{
printf("error %d with zipfile in unzGetCurrentFileInfo\n",err);
break;
}
if (file_info.uncompressed_size>0)
ratio = (uLong)((file_info.compressed_size*100)/file_info.uncompressed_size);
display a '*' if the file is crypted if ((file_info.flag & 1) != 0)
charCrypt='*';
if (file_info.compression_method==0)
string_method="Stored";
else
if (file_info.compression_method==Z_DEFLATED)
{
uInt iLevel=(uInt)((file_info.flag & 0x6)/2);
if (iLevel==0)
string_method="Defl:N";
else if (iLevel==1)
string_method="Defl:X";
else if ((iLevel==2) || (iLevel==3))
string_method="Defl:F"; 2:fast , 3 : extra fast }
else
if (file_info.compression_method==Z_BZIP2ED)
{
string_method="BZip2 ";
}
else
string_method="Unkn. ";
Display64BitsSize(file_info.uncompressed_size,7);
printf(" %6s%c",string_method,charCrypt);
Display64BitsSize(file_info.compressed_size,7);
printf(" %3lu%% %2.2lu-%2.2lu-%2.2lu %2.2lu:%2.2lu %8.8lx %s\n",
ratio,
(uLong)file_info.tmu_date.tm_mon + 1,
(uLong)file_info.tmu_date.tm_mday,
(uLong)file_info.tmu_date.tm_year % 100,
(uLong)file_info.tmu_date.tm_hour,(uLong)file_info.tmu_date.tm_min,
(uLong)file_info.crc,filename_inzip);
if ((i+1)<gi.number_entry)
{
err = unzGoToNextFile(uf);
if (err!=UNZ_OK)
{
printf("error %d with zipfile in unzGoToNextFile\n",err);
break;
}
}
}
return 0;
}
int do_extract_currentfile(uf,popt_extract_without_path,popt_overwrite,password)
unzFile uf;
const int* popt_extract_without_path;
int* popt_overwrite;
const char* password;
{
char filename_inzip[256];
char* filename_withoutpath;
char* p;
int err=UNZ_OK;
FILE *fout=NULL;
void* buf;
uInt size_buf;
unz_file_info64 file_info;
uLong ratio=0;
err = unzGetCurrentFileInfo64(uf,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0);
if (err!=UNZ_OK)
{
printf("error %d with zipfile in unzGetCurrentFileInfo\n",err);
return err;
}
size_buf = WRITEBUFFERSIZE;
buf = (void*)malloc(size_buf);
if (buf==NULL)
{
printf("Error allocating memory\n");
return UNZ_INTERNALERROR;
}
p = filename_withoutpath = filename_inzip;
while ((*p) != '\0')
{
if (((*p)=='/') || ((*p)=='\\'))
filename_withoutpath = p+1;
p++;
}
if ((*filename_withoutpath)=='\0')
{
if ((*popt_extract_without_path)==0)
{
printf("creating directory: %s\n",filename_inzip);
mymkdir(filename_inzip);
}
}
else
{
const char* write_filename;
int skip=0;
if ((*popt_extract_without_path)==0)
write_filename = filename_inzip;
else
write_filename = filename_withoutpath;
err = unzOpenCurrentFilePassword(uf,password);
if (err!=UNZ_OK)
{
printf("error %d with zipfile in unzOpenCurrentFilePassword\n",err);
}
if (((*popt_overwrite)==0) && (err==UNZ_OK))
{
char rep=0;
FILE* ftestexist;
ftestexist = fopen64(write_filename,"rb");
if (ftestexist!=NULL)
{
fclose(ftestexist);
do
{
char answer[128];
int ret;
printf("The file %s exists. Overwrite ? [y]es, [n]o, [A]ll: ",write_filename);
ret = scanf("%1s",answer);
if (ret != 1)
{
exit(EXIT_FAILURE);
}
rep = answer[0] ;
if ((rep>='a') && (rep<='z'))
rep -= 0x20;
}
while ((rep!='Y') && (rep!='N') && (rep!='A'));
}
if (rep == 'N')
skip = 1;
if (rep == 'A')
*popt_overwrite=1;
}
if ((skip==0) && (err==UNZ_OK))
{
fout=fopen64(write_filename,"wb");
some zipfile don't contain directory alone before file if ((fout==NULL) && ((*popt_extract_without_path)==0) &&
(filename_withoutpath!=(char*)filename_inzip))
{
char c=*(filename_withoutpath-1);
*(filename_withoutpath-1)='\0';
makedir(write_filename);
*(filename_withoutpath-1)=c;
fout=fopen64(write_filename,"wb");
}
if (fout==NULL)
{
printf("error opening %s\n",write_filename);
}
}
if (fout!=NULL)
{
printf(" extracting: %s\n",write_filename);
do
{
err = unzReadCurrentFile(uf,buf,size_buf);
if (err<0)
{
printf("error %d with zipfile in unzReadCurrentFile\n",err);
break;
}
if (err>0)
if (fwrite(buf,err,1,fout)!=1)
{
printf("error in writing extracted file\n");
err=UNZ_ERRNO;
break;
}
}
while (err>0);
if (fout)
fclose(fout);
if (err==0)
change_file_date(write_filename,file_info.dosDate,
file_info.tmu_date);
}
if (err==UNZ_OK)
{
err = unzCloseCurrentFile (uf);
if (err!=UNZ_OK)
{
printf("error %d with zipfile in unzCloseCurrentFile\n",err);
}
}
else
unzCloseCurrentFile(uf); don't lose the error }
free(buf);
return err;
}
int do_extract(uf,opt_extract_without_path,opt_overwrite,password)
unzFile uf;
int opt_extract_without_path;
int opt_overwrite;
const char* password;
{
uLong i;
unz_global_info64 gi;
int err;
FILE* fout=NULL;
err = unzGetGlobalInfo64(uf,&gi);
if (err!=UNZ_OK)
printf("error %d with zipfile in unzGetGlobalInfo \n",err);
for (i=0;i<gi.number_entry;i++)
{
if (do_extract_currentfile(uf,&opt_extract_without_path,
&opt_overwrite,
password) != UNZ_OK)
break;
if ((i+1)<gi.number_entry)
{
err = unzGoToNextFile(uf);
if (err!=UNZ_OK)
{
printf("error %d with zipfile in unzGoToNextFile\n",err);
break;
}
}
}
return 0;
}
int do_extract_onefile(uf,filename,opt_extract_without_path,opt_overwrite,password)
unzFile uf;
const char* filename;
int opt_extract_without_path;
int opt_overwrite;
const char* password;
{
int err = UNZ_OK;
if (unzLocateFile(uf,filename,CASESENSITIVITY)!=UNZ_OK)
{
printf("file %s not found in the zipfile\n",filename);
return 2;
}
if (do_extract_currentfile(uf,&opt_extract_without_path,
&opt_overwrite,
password) == UNZ_OK)
return 0;
else
return 1;
}
int main(argc,argv)
int argc;
char *argv[];
{
const char *zipfilename=NULL;
const char *filename_to_extract=NULL;
const char *password=NULL;
char filename_try[MAXFILENAME+16] = "";
int i;
int ret_value=0;
int opt_do_list=0;
int opt_do_extract=1;
int opt_do_extract_withoutpath=0;
int opt_overwrite=0;
int opt_extractdir=0;
const char *dirname=NULL;
unzFile uf=NULL;
do_banner();
if (argc==1)
{
do_help();
return 0;
}
else
{
for (i=1;i<argc;i++)
{
if ((*argv[i])=='-')
{
const char *p=argv[i]+1;
while ((*p)!='\0')
{
char c=*(p++);;
if ((c=='l') || (c=='L'))
opt_do_list = 1;
if ((c=='v') || (c=='V'))
opt_do_list = 1;
if ((c=='x') || (c=='X'))
opt_do_extract = 1;
if ((c=='e') || (c=='E'))
opt_do_extract = opt_do_extract_withoutpath = 1;
if ((c=='o') || (c=='O'))
opt_overwrite=1;
if ((c=='d') || (c=='D'))
{
opt_extractdir=1;
dirname=argv[i+1];
}
if (((c=='p') || (c=='P')) && (i+1<argc))
{
password=argv[i+1];
i++;
}
}
}
else
{
if (zipfilename == NULL)
zipfilename = argv[i];
else if ((filename_to_extract==NULL) && (!opt_extractdir))
filename_to_extract = argv[i] ;
}
}
}
if (zipfilename!=NULL)
{
# ifdef USEWIN32IOAPI
zlib_filefunc64_def ffunc;
# endif
strncpy(filename_try, zipfilename,MAXFILENAME-1);
strncpy doesnt append the trailing NULL, of the string is too long. filename_try[ MAXFILENAME ] = '\0';
# ifdef USEWIN32IOAPI
fill_win32_filefunc64A(&ffunc);
uf = unzOpen2_64(zipfilename,&ffunc);
# else
uf = unzOpen64(zipfilename);
# endif
if (uf==NULL)
{
strcat(filename_try,".zip");
# ifdef USEWIN32IOAPI
uf = unzOpen2_64(filename_try,&ffunc);
# else
uf = unzOpen64(filename_try);
# endif
}
}
if (uf==NULL)
{
printf("Cannot open %s or %s.zip\n",zipfilename,zipfilename);
return 1;
}
printf("%s opened\n",filename_try);
if (opt_do_list==1)
ret_value = do_list(uf);
else if (opt_do_extract==1)
{
#ifdef _WIN32
if (opt_extractdir && _chdir(dirname))
#else
if (opt_extractdir && chdir(dirname))
#endif
{
printf("Error changing into %s, aborting\n", dirname);
exit(-1);
}
if (filename_to_extract == NULL)
ret_value = do_extract(uf, opt_do_extract_withoutpath, opt_overwrite, password);
else
ret_value = do_extract_onefile(uf, filename_to_extract, opt_do_extract_withoutpath, opt_overwrite, password);
}
unzClose(uf);
return ret_value;
}
*/
+485
View File
@@ -0,0 +1,485 @@
/*
minizip.c
Version 1.1, February 14h, 2010
sample part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
Modifications of Unzip for Zip64
Copyright (C) 2007-2008 Even Rouault
Modifications for Zip64 support on both zip and unzip
Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
#ifndef _WIN32
#ifndef __USE_FILE_OFFSET64
#define __USE_FILE_OFFSET64
#endif
#ifndef __USE_LARGEFILE64
#define __USE_LARGEFILE64
#endif
#ifndef _LARGEFILE64_SOURCE
#define _LARGEFILE64_SOURCE
#endif
#ifndef _FILE_OFFSET_BIT
#define _FILE_OFFSET_BIT 64
#endif
#endif
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <fcntl.h>
#ifdef unix
# include <unistd.h>
# include <utime.h>
# include <sys/types.h>
# include <sys/stat.h>
#else
# include <direct.h>
# include <io.h>
#endif
#include "zip.h"
#ifdef _WIN32
#define USEWIN32IOAPI
#include "iowin32.h"
#endif
#define WRITEBUFFERSIZE (16384)
#define MAXFILENAME (256)
#ifdef _WIN32
uLong filetime(f, tmzip, dt)
char *f; name of file to get info on tm_zip *tmzip; return value: access, modific. and creation times uLong *dt; dostime {
int ret = 0;
{
FILETIME ftLocal;
HANDLE hFind;
WIN32_FIND_DATAA ff32;
hFind = FindFirstFileA(f,&ff32);
if (hFind != INVALID_HANDLE_VALUE)
{
FileTimeToLocalFileTime(&(ff32.ftLastWriteTime),&ftLocal);
FileTimeToDosDateTime(&ftLocal,((LPWORD)dt)+1,((LPWORD)dt)+0);
FindClose(hFind);
ret = 1;
}
}
return ret;
}
#else
#ifdef unix
uLong filetime(f, tmzip, dt)
char *f; name of file to get info on tm_zip *tmzip; return value: access, modific. and creation times uLong *dt; dostime {
int ret=0;
struct stat s; results of stat() struct tm* filedate;
time_t tm_t=0;
if (strcmp(f,"-")!=0)
{
char name[MAXFILENAME+1];
int len = strlen(f);
if (len > MAXFILENAME)
len = MAXFILENAME;
strncpy(name, f,MAXFILENAME-1);
strncpy doesnt append the trailing NULL, of the string is too long. name[ MAXFILENAME ] = '\0';
if (name[len - 1] == '/')
name[len - 1] = '\0';
not all systems allow stat'ing a file with / appended if (stat(name,&s)==0)
{
tm_t = s.st_mtime;
ret = 1;
}
}
filedate = localtime(&tm_t);
tmzip->tm_sec = filedate->tm_sec;
tmzip->tm_min = filedate->tm_min;
tmzip->tm_hour = filedate->tm_hour;
tmzip->tm_mday = filedate->tm_mday;
tmzip->tm_mon = filedate->tm_mon ;
tmzip->tm_year = filedate->tm_year;
return ret;
}
#else
uLong filetime(f, tmzip, dt)
char *f; name of file to get info on tm_zip *tmzip; return value: access, modific. and creation times uLong *dt; dostime {
return 0;
}
#endif
#endif
int check_exist_file(filename)
const char* filename;
{
FILE* ftestexist;
int ret = 1;
ftestexist = fopen64(filename,"rb");
if (ftestexist==NULL)
ret = 0;
else
fclose(ftestexist);
return ret;
}
void do_banner()
{
printf("MiniZip 1.1, demo of zLib + MiniZip64 package, written by Gilles Vollant\n");
printf("more info on MiniZip at http://www.winimage.com/zLibDll/minizip.html\n\n");
}
void do_help()
{
printf("Usage : minizip [-o] [-a] [-0 to -9] [-p password] [-j] file.zip [files_to_add]\n\n" \
" -o Overwrite existing file.zip\n" \
" -a Append to existing file.zip\n" \
" -0 Store only\n" \
" -1 Compress faster\n" \
" -9 Compress better\n\n" \
" -j exclude path. store only the file name.\n\n");
}
calculate the CRC32 of a file,
because to encrypt a file, we need known the CRC32 of the file before int getFileCrc(const char* filenameinzip,void*buf,unsigned long size_buf,unsigned long* result_crc)
{
unsigned long calculate_crc=0;
int err=ZIP_OK;
FILE * fin = fopen64(filenameinzip,"rb");
unsigned long size_read = 0;
unsigned long total_read = 0;
if (fin==NULL)
{
err = ZIP_ERRNO;
}
if (err == ZIP_OK)
do
{
err = ZIP_OK;
size_read = (int)fread(buf,1,size_buf,fin);
if (size_read < size_buf)
if (feof(fin)==0)
{
printf("error in reading %s\n",filenameinzip);
err = ZIP_ERRNO;
}
if (size_read>0)
calculate_crc = crc32(calculate_crc,buf,size_read);
total_read += size_read;
} while ((err == ZIP_OK) && (size_read>0));
if (fin)
fclose(fin);
*result_crc=calculate_crc;
printf("file %s crc %lx\n", filenameinzip, calculate_crc);
return err;
}
int isLargeFile(const char* filename)
{
int largeFile = 0;
ZPOS64_T pos = 0;
FILE* pFile = fopen64(filename, "rb");
if(pFile != NULL)
{
int n = fseeko64(pFile, 0, SEEK_END);
pos = ftello64(pFile);
printf("File : %s is %lld bytes\n", filename, pos);
if(pos >= 0xffffffff)
largeFile = 1;
fclose(pFile);
}
return largeFile;
}
int main(argc,argv)
int argc;
char *argv[];
{
int i;
int opt_overwrite=0;
int opt_compress_level=Z_DEFAULT_COMPRESSION;
int opt_exclude_path=0;
int zipfilenamearg = 0;
char filename_try[MAXFILENAME+16];
int zipok;
int err=0;
int size_buf=0;
void* buf=NULL;
const char* password=NULL;
do_banner();
if (argc==1)
{
do_help();
return 0;
}
else
{
for (i=1;i<argc;i++)
{
if ((*argv[i])=='-')
{
const char *p=argv[i]+1;
while ((*p)!='\0')
{
char c=*(p++);;
if ((c=='o') || (c=='O'))
opt_overwrite = 1;
if ((c=='a') || (c=='A'))
opt_overwrite = 2;
if ((c>='0') && (c<='9'))
opt_compress_level = c-'0';
if ((c=='j') || (c=='J'))
opt_exclude_path = 1;
if (((c=='p') || (c=='P')) && (i+1<argc))
{
password=argv[i+1];
i++;
}
}
}
else
{
if (zipfilenamearg == 0)
{
zipfilenamearg = i ;
}
}
}
}
size_buf = WRITEBUFFERSIZE;
buf = (void*)malloc(size_buf);
if (buf==NULL)
{
printf("Error allocating memory\n");
return ZIP_INTERNALERROR;
}
if (zipfilenamearg==0)
{
zipok=0;
}
else
{
int i,len;
int dot_found=0;
zipok = 1 ;
strncpy(filename_try, argv[zipfilenamearg],MAXFILENAME-1);
strncpy doesnt append the trailing NULL, of the string is too long. filename_try[ MAXFILENAME ] = '\0';
len=(int)strlen(filename_try);
for (i=0;i<len;i++)
if (filename_try[i]=='.')
dot_found=1;
if (dot_found==0)
strcat(filename_try,".zip");
if (opt_overwrite==2)
{
if the file don't exist, we not append file if (check_exist_file(filename_try)==0)
opt_overwrite=1;
}
else
if (opt_overwrite==0)
if (check_exist_file(filename_try)!=0)
{
char rep=0;
do
{
char answer[128];
int ret;
printf("The file %s exists. Overwrite ? [y]es, [n]o, [a]ppend : ",filename_try);
ret = scanf("%1s",answer);
if (ret != 1)
{
exit(EXIT_FAILURE);
}
rep = answer[0] ;
if ((rep>='a') && (rep<='z'))
rep -= 0x20;
}
while ((rep!='Y') && (rep!='N') && (rep!='A'));
if (rep=='N')
zipok = 0;
if (rep=='A')
opt_overwrite = 2;
}
}
if (zipok==1)
{
zipFile zf;
int errclose;
# ifdef USEWIN32IOAPI
zlib_filefunc64_def ffunc;
fill_win32_filefunc64A(&ffunc);
zf = zipOpen2_64(filename_try,(opt_overwrite==2) ? 2 : 0,NULL,&ffunc);
# else
zf = zipOpen64(filename_try,(opt_overwrite==2) ? 2 : 0);
# endif
if (zf == NULL)
{
printf("error opening %s\n",filename_try);
err= ZIP_ERRNO;
}
else
printf("creating %s\n",filename_try);
for (i=zipfilenamearg+1;(i<argc) && (err==ZIP_OK);i++)
{
if (!((((*(argv[i]))=='-') || ((*(argv[i]))=='/')) &&
((argv[i][1]=='o') || (argv[i][1]=='O') ||
(argv[i][1]=='a') || (argv[i][1]=='A') ||
(argv[i][1]=='p') || (argv[i][1]=='P') ||
((argv[i][1]>='0') || (argv[i][1]<='9'))) &&
(strlen(argv[i]) == 2)))
{
FILE * fin;
int size_read;
const char* filenameinzip = argv[i];
const char *savefilenameinzip;
zip_fileinfo zi;
unsigned long crcFile=0;
int zip64 = 0;
zi.tmz_date.tm_sec = zi.tmz_date.tm_min = zi.tmz_date.tm_hour =
zi.tmz_date.tm_mday = zi.tmz_date.tm_mon = zi.tmz_date.tm_year = 0;
zi.dosDate = 0;
zi.internal_fa = 0;
zi.external_fa = 0;
filetime(filenameinzip,&zi.tmz_date,&zi.dosDate);
err = zipOpenNewFileInZip(zf,filenameinzip,&zi,
NULL,0,NULL,0,NULL / * comment * /,
(opt_compress_level != 0) ? Z_DEFLATED : 0,
opt_compress_level);
if ((password != NULL) && (err==ZIP_OK))
err = getFileCrc(filenameinzip,buf,size_buf,&crcFile);
zip64 = isLargeFile(filenameinzip);
The path name saved, should not include a leading slash. if it did, windows/xp and dynazip couldn't read the zip file. savefilenameinzip = filenameinzip;
while( savefilenameinzip[0] == '\\' || savefilenameinzip[0] == '/' )
{
savefilenameinzip++;
}
should the zip file contain any path at all? if( opt_exclude_path )
{
const char *tmpptr;
const char *lastslash = 0;
for( tmpptr = savefilenameinzip; *tmpptr; tmpptr++)
{
if( *tmpptr == '\\' || *tmpptr == '/')
{
lastslash = tmpptr;
}
}
if( lastslash != NULL )
{
savefilenameinzip = lastslash+1; // base filename follows last slash.
}
}
err = zipOpenNewFileInZip3_64(zf,savefilenameinzip,&zi,
NULL,0,NULL,0,NULL comment,
(opt_compress_level != 0) ? Z_DEFLATED : 0,
opt_compress_level,0,
-MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
password,crcFile, zip64);
if (err != ZIP_OK)
printf("error in opening %s in zipfile\n",filenameinzip);
else
{
fin = fopen64(filenameinzip,"rb");
if (fin==NULL)
{
err=ZIP_ERRNO;
printf("error in opening %s for reading\n",filenameinzip);
}
}
if (err == ZIP_OK)
do
{
err = ZIP_OK;
size_read = (int)fread(buf,1,size_buf,fin);
if (size_read < size_buf)
if (feof(fin)==0)
{
printf("error in reading %s\n",filenameinzip);
err = ZIP_ERRNO;
}
if (size_read>0)
{
err = zipWriteInFileInZip (zf,buf,size_read);
if (err<0)
{
printf("error in writing %s in the zipfile\n",
filenameinzip);
}
}
} while ((err == ZIP_OK) && (size_read>0));
if (fin)
fclose(fin);
if (err<0)
err=ZIP_ERRNO;
else
{
err = zipCloseFileInZip(zf);
if (err!=ZIP_OK)
printf("error in closing %s in the zipfile\n",
filenameinzip);
}
}
}
errclose = zipClose(zf,NULL);
if (errclose != ZIP_OK)
printf("error in closing %s\n",filename_try);
}
else
{
do_help();
}
free(buf);
return 0;
}
*/
+276
View File
@@ -0,0 +1,276 @@
/*
Additional tools for Minizip
Code: Xavier Roche '2004
License: Same as ZLIB (www.gzip.org)
*/
#define _CRT_SECURE_NO_WARNINGS
/* Code */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "zlib.h"
#include "unzip.h"
#define READ_8(adr) ((unsigned char)*(adr))
#define READ_16(adr) ( READ_8(adr) | (READ_8(adr+1) << 8) )
#define READ_32(adr) ( READ_16(adr) | (READ_16((adr)+2) << 16) )
#define WRITE_8(buff, n) do { \
*((unsigned char*)(buff)) = (unsigned char) ((n) & 0xff); \
} while(0)
#define WRITE_16(buff, n) do { \
WRITE_8((unsigned char*)(buff), n); \
WRITE_8(((unsigned char*)(buff)) + 1, (n) >> 8); \
} while(0)
#define WRITE_32(buff, n) do { \
WRITE_16((unsigned char*)(buff), (n) & 0xffff); \
WRITE_16((unsigned char*)(buff) + 2, (n) >> 16); \
} while(0)
extern int ZEXPORT unzRepair(file, fileOut, fileOutTmp, nRecovered, bytesRecovered)
const char* file;
const char* fileOut;
const char* fileOutTmp;
uLong* nRecovered;
uLong* bytesRecovered;
{
int err = Z_OK;
FILE* fpZip = fopen(file, "rb");
FILE* fpOut = fopen(fileOut, "wb");
FILE* fpOutCD = fopen(fileOutTmp, "wb");
if (fpZip != NULL && fpOut != NULL) {
int entries = 0;
uLong totalBytes = 0;
char header[30];
char filename[256];
char extra[1024];
int offset = 0;
int offsetCD = 0;
while ( fread(header, 1, 30, fpZip) == 30 ) {
int currentOffset = offset;
/* File entry */
if (READ_32(header) == 0x04034b50) {
unsigned int version = READ_16(header + 4);
unsigned int gpflag = READ_16(header + 6);
unsigned int method = READ_16(header + 8);
unsigned int filetime = READ_16(header + 10);
unsigned int filedate = READ_16(header + 12);
unsigned int crc = READ_32(header + 14); /* crc */
unsigned int cpsize = READ_32(header + 18); /* compressed size */
unsigned int uncpsize = READ_32(header + 22); /* uncompressed sz */
unsigned int fnsize = READ_16(header + 26); /* file name length */
unsigned int extsize = READ_16(header + 28); /* extra field length */
filename[0] = extra[0] = '\0';
/* Header */
if (fwrite(header, 1, 30, fpOut) == 30) {
offset += 30;
} else {
err = Z_ERRNO;
break;
}
/* Filename */
if (fnsize > 0) {
if (fread(filename, 1, fnsize, fpZip) == fnsize) {
if (fwrite(filename, 1, fnsize, fpOut) == fnsize) {
offset += fnsize;
} else {
err = Z_ERRNO;
break;
}
} else {
err = Z_ERRNO;
break;
}
} else {
err = Z_STREAM_ERROR;
break;
}
/* Extra field */
if (extsize > 0) {
if (fread(extra, 1, extsize, fpZip) == extsize) {
if (fwrite(extra, 1, extsize, fpOut) == extsize) {
offset += extsize;
} else {
err = Z_ERRNO;
break;
}
} else {
err = Z_ERRNO;
break;
}
}
/* Data */
{
int dataSize = cpsize;
if (dataSize == 0) {
dataSize = uncpsize;
}
if (dataSize > 0) {
char* data = malloc(dataSize);
if (data != NULL) {
if ((int)fread(data, 1, dataSize, fpZip) == dataSize) {
if ((int)fwrite(data, 1, dataSize, fpOut) == dataSize) {
offset += dataSize;
totalBytes += dataSize;
} else {
err = Z_ERRNO;
}
} else {
err = Z_ERRNO;
}
free(data);
if (err != Z_OK) {
break;
}
} else {
err = Z_MEM_ERROR;
break;
}
}
}
/* Central directory entry */
{
char header[46];
char* comment = "";
int comsize = (int) strlen(comment);
WRITE_32(header, 0x02014b50);
WRITE_16(header + 4, version);
WRITE_16(header + 6, version);
WRITE_16(header + 8, gpflag);
WRITE_16(header + 10, method);
WRITE_16(header + 12, filetime);
WRITE_16(header + 14, filedate);
WRITE_32(header + 16, crc);
WRITE_32(header + 20, cpsize);
WRITE_32(header + 24, uncpsize);
WRITE_16(header + 28, fnsize);
WRITE_16(header + 30, extsize);
WRITE_16(header + 32, comsize);
WRITE_16(header + 34, 0); /* disk # */
WRITE_16(header + 36, 0); /* int attrb */
WRITE_32(header + 38, 0); /* ext attrb */
WRITE_32(header + 42, currentOffset);
/* Header */
if (fwrite(header, 1, 46, fpOutCD) == 46) {
offsetCD += 46;
/* Filename */
if (fnsize > 0) {
if (fwrite(filename, 1, fnsize, fpOutCD) == fnsize) {
offsetCD += fnsize;
} else {
err = Z_ERRNO;
break;
}
} else {
err = Z_STREAM_ERROR;
break;
}
/* Extra field */
if (extsize > 0) {
if (fwrite(extra, 1, extsize, fpOutCD) == extsize) {
offsetCD += extsize;
} else {
err = Z_ERRNO;
break;
}
}
/* Comment field */
if (comsize > 0) {
if ((int)fwrite(comment, 1, comsize, fpOutCD) == comsize) {
offsetCD += comsize;
} else {
err = Z_ERRNO;
break;
}
}
} else {
err = Z_ERRNO;
break;
}
}
/* Success */
entries++;
} else {
break;
}
}
/* Final central directory */
{
int entriesZip = entries;
char header[22];
char* comment = ""; // "ZIP File recovered by zlib/minizip/mztools";
int comsize = (int) strlen(comment);
if (entriesZip > 0xffff) {
entriesZip = 0xffff;
}
WRITE_32(header, 0x06054b50);
WRITE_16(header + 4, 0); /* disk # */
WRITE_16(header + 6, 0); /* disk # */
WRITE_16(header + 8, entriesZip); /* hack */
WRITE_16(header + 10, entriesZip); /* hack */
WRITE_32(header + 12, offsetCD); /* size of CD */
WRITE_32(header + 16, offset); /* offset to CD */
WRITE_16(header + 20, comsize); /* comment */
/* Header */
if (fwrite(header, 1, 22, fpOutCD) == 22) {
/* Comment field */
if (comsize > 0) {
if ((int)fwrite(comment, 1, comsize, fpOutCD) != comsize) {
err = Z_ERRNO;
}
}
} else {
err = Z_ERRNO;
}
}
/* Final merge (file + central directory) */
fclose(fpOutCD);
if (err == Z_OK) {
fpOutCD = fopen(fileOutTmp, "rb");
if (fpOutCD != NULL) {
int nRead;
char buffer[8192];
while ( (nRead = (int)fread(buffer, 1, sizeof(buffer), fpOutCD)) > 0) {
if ((int)fwrite(buffer, 1, nRead, fpOut) != nRead) {
err = Z_ERRNO;
break;
}
}
fclose(fpOutCD);
}
}
/* Close */
fclose(fpZip);
fclose(fpOut);
/* Wipe temporary file */
(void)remove(fileOutTmp);
/* Number of recovered entries */
if (err == Z_OK) {
if (nRecovered != NULL) {
*nRecovered = entries;
}
if (bytesRecovered != NULL) {
*bytesRecovered = totalBytes;
}
}
} else {
err = Z_STREAM_ERROR;
}
return err;
}
+31
View File
@@ -0,0 +1,31 @@
/*
Additional tools for Minizip
Code: Xavier Roche '2004
License: Same as ZLIB (www.gzip.org)
*/
#ifndef _zip_tools_H
#define _zip_tools_H
#ifdef __cplusplus
extern "C" {
#endif
#ifndef _ZLIB_H
#include "zlib.h"
#endif
#include "unzip.h"
/* Repair a ZIP file (missing central directory)
file: file to recover
fileOut: output file after recovery
fileOutTmp: temporary file name used for recovery
*/
extern int ZEXPORT unzRepair(const char* file,
const char* fileOut,
const char* fileOutTmp,
uLong* nRecovered,
uLong* bytesRecovered);
#endif
File diff suppressed because it is too large Load Diff
+426
View File
@@ -0,0 +1,426 @@
/* unzip.h -- IO for uncompress .zip files using zlib
Version 1.1, February 14h, 2010
part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
Modifications of Unzip for Zip64
Copyright (C) 2007-2008 Even Rouault
Modifications for Zip64 support on both zip and unzip
Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
For more info read MiniZip_info.txt
---------------------------------------------------------------------------------
Condition of use and distribution are the same than zlib :
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
---------------------------------------------------------------------------------
Changes
See header of unzip64.c
*/
#ifndef _unz64_H
#define _unz64_H
#ifdef __cplusplus
extern "C" {
#endif
#ifndef _ZLIB_H
#include <zlib.h>
#endif
#ifndef _ZLIBIOAPI_H
#include "ioapi.h"
#endif
#ifdef HAVE_BZIP2
#include "bzlib.h"
#endif
#define Z_BZIP2ED 12
#if defined(STRICTUNZIP) || defined(STRICTZIPUNZIP)
/* like the STRICT of WIN32, we define a pointer that cannot be converted
from (void*) without cast */
typedef struct TagunzFile__ { int unused; } unzFile__;
typedef unzFile__ *unzFile;
#else
typedef voidp unzFile;
#endif
#define UNZ_OK (0)
#define UNZ_END_OF_LIST_OF_FILE (-100)
#define UNZ_ERRNO (Z_ERRNO)
#define UNZ_EOF (0)
#define UNZ_PARAMERROR (-102)
#define UNZ_BADZIPFILE (-103)
#define UNZ_INTERNALERROR (-104)
#define UNZ_CRCERROR (-105)
/* tm_unz contain date/time info */
typedef struct tm_unz_s
{
uInt tm_sec; /* seconds after the minute - [0,59] */
uInt tm_min; /* minutes after the hour - [0,59] */
uInt tm_hour; /* hours since midnight - [0,23] */
uInt tm_mday; /* day of the month - [1,31] */
uInt tm_mon; /* months since January - [0,11] */
uInt tm_year; /* years - [1980..2044] */
} tm_unz;
/* unz_global_info structure contain global data about the ZIPfile
These data comes from the end of central dir */
typedef struct unz_global_info64_s
{
ZPOS64_T number_entry; /* total number of entries in
the central dir on this disk */
uLong size_comment; /* size of the global comment of the zipfile */
} unz_global_info64;
typedef struct unz_global_info_s
{
uLong number_entry; /* total number of entries in
the central dir on this disk */
uLong size_comment; /* size of the global comment of the zipfile */
} unz_global_info;
/* unz_file_info contain information about a file in the zipfile */
typedef struct unz_file_info64_s
{
uLong version; /* version made by 2 bytes */
uLong version_needed; /* version needed to extract 2 bytes */
uLong flag; /* general purpose bit flag 2 bytes */
uLong compression_method; /* compression method 2 bytes */
uLong dosDate; /* last mod file date in Dos fmt 4 bytes */
uLong crc; /* crc-32 4 bytes */
ZPOS64_T compressed_size; /* compressed size 8 bytes */
ZPOS64_T uncompressed_size; /* uncompressed size 8 bytes */
uLong size_filename; /* filename length 2 bytes */
uLong size_file_extra; /* extra field length 2 bytes */
uLong size_file_comment; /* file comment length 2 bytes */
uLong disk_num_start; /* disk number start 2 bytes */
uLong internal_fa; /* internal file attributes 2 bytes */
uLong external_fa; /* external file attributes 4 bytes */
tm_unz tmu_date;
} unz_file_info64;
typedef struct unz_file_info_s
{
uLong version; /* version made by 2 bytes */
uLong version_needed; /* version needed to extract 2 bytes */
uLong flag; /* general purpose bit flag 2 bytes */
uLong compression_method; /* compression method 2 bytes */
uLong dosDate; /* last mod file date in Dos fmt 4 bytes */
uLong crc; /* crc-32 4 bytes */
uLong compressed_size; /* compressed size 4 bytes */
uLong uncompressed_size; /* uncompressed size 4 bytes */
uLong size_filename; /* filename length 2 bytes */
uLong size_file_extra; /* extra field length 2 bytes */
uLong size_file_comment; /* file comment length 2 bytes */
uLong disk_num_start; /* disk number start 2 bytes */
uLong internal_fa; /* internal file attributes 2 bytes */
uLong external_fa; /* external file attributes 4 bytes */
tm_unz tmu_date;
} unz_file_info;
extern int ZEXPORT unzStringFileNameCompare OF ((const char* fileName1,
const char* fileName2,
int iCaseSensitivity));
/*
Compare two filename (fileName1,fileName2).
If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp)
If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi
or strcasecmp)
If iCaseSenisivity = 0, case sensitivity is defaut of your operating system
(like 1 on Unix, 2 on Windows)
*/
extern unzFile ZEXPORT unzOpen OF((const char *path));
extern unzFile ZEXPORT unzOpen64 OF((const void *path));
/*
Open a Zip file. path contain the full pathname (by example,
on a Windows XP computer "c:\\zlib\\zlib113.zip" or on an Unix computer
"zlib/zlib113.zip".
If the zipfile cannot be opened (file don't exist or in not valid), the
return value is NULL.
Else, the return value is a unzFile Handle, usable with other function
of this unzip package.
the "64" function take a const void* pointer, because the path is just the
value passed to the open64_file_func callback.
Under Windows, if UNICODE is defined, using fill_fopen64_filefunc, the path
is a pointer to a wide unicode string (LPCTSTR is LPCWSTR), so const char*
does not describe the reality
*/
extern unzFile ZEXPORT unzOpen2 OF((const char *path,
zlib_filefunc_def* pzlib_filefunc_def));
/*
Open a Zip file, like unzOpen, but provide a set of file low level API
for read/write the zip file (see ioapi.h)
*/
extern unzFile ZEXPORT unzOpen2_64 OF((const void *path,
zlib_filefunc64_def* pzlib_filefunc_def));
/*
Open a Zip file, like unz64Open, but provide a set of file low level API
for read/write the zip file (see ioapi.h)
*/
extern int ZEXPORT unzClose OF((unzFile file));
/*
Close a ZipFile opened with unzipOpen.
If there is files inside the .Zip opened with unzOpenCurrentFile (see later),
these files MUST be closed with unzipCloseCurrentFile before call unzipClose.
return UNZ_OK if there is no problem. */
extern int ZEXPORT unzGetGlobalInfo OF((unzFile file,
unz_global_info *pglobal_info));
extern int ZEXPORT unzGetGlobalInfo64 OF((unzFile file,
unz_global_info64 *pglobal_info));
/*
Write info about the ZipFile in the *pglobal_info structure.
No preparation of the structure is needed
return UNZ_OK if there is no problem. */
extern int ZEXPORT unzGetGlobalComment OF((unzFile file,
char *szComment,
uLong uSizeBuf));
/*
Get the global comment string of the ZipFile, in the szComment buffer.
uSizeBuf is the size of the szComment buffer.
return the number of byte copied or an error code <0
*/
/***************************************************************************/
/* Unzip package allow you browse the directory of the zipfile */
extern int ZEXPORT unzGoToFirstFile OF((unzFile file));
/*
Set the current file of the zipfile to the first file.
return UNZ_OK if there is no problem
*/
extern int ZEXPORT unzGoToNextFile OF((unzFile file));
/*
Set the current file of the zipfile to the next file.
return UNZ_OK if there is no problem
return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest.
*/
extern int ZEXPORT unzLocateFile OF((unzFile file,
const char *szFileName,
int iCaseSensitivity));
/*
Try locate the file szFileName in the zipfile.
For the iCaseSensitivity signification, see unzStringFileNameCompare
return value :
UNZ_OK if the file is found. It becomes the current file.
UNZ_END_OF_LIST_OF_FILE if the file is not found
*/
/* ****************************************** */
/* Ryan supplied functions */
/* unz_file_info contain information about a file in the zipfile */
typedef struct unz_file_pos_s
{
uLong pos_in_zip_directory; /* offset in zip file directory */
uLong num_of_file; /* # of file */
} unz_file_pos;
extern int ZEXPORT unzGetFilePos(
unzFile file,
unz_file_pos* file_pos);
extern int ZEXPORT unzGoToFilePos(
unzFile file,
unz_file_pos* file_pos);
typedef struct unz64_file_pos_s
{
ZPOS64_T pos_in_zip_directory; /* offset in zip file directory */
ZPOS64_T num_of_file; /* # of file */
} unz64_file_pos;
extern int ZEXPORT unzGetFilePos64(
unzFile file,
unz64_file_pos* file_pos);
extern int ZEXPORT unzGoToFilePos64(
unzFile file,
const unz64_file_pos* file_pos);
/* ****************************************** */
extern int ZEXPORT unzGetCurrentFileInfo64 OF((unzFile file,
unz_file_info64 *pfile_info,
char *szFileName,
uLong fileNameBufferSize,
void *extraField,
uLong extraFieldBufferSize,
char *szComment,
uLong commentBufferSize));
extern int ZEXPORT unzGetCurrentFileInfo OF((unzFile file,
unz_file_info *pfile_info,
char *szFileName,
uLong fileNameBufferSize,
void *extraField,
uLong extraFieldBufferSize,
char *szComment,
uLong commentBufferSize));
/*
Get Info about the current file
if pfile_info!=NULL, the *pfile_info structure will contain somes info about
the current file
if szFileName!=NULL, the filemane string will be copied in szFileName
(fileNameBufferSize is the size of the buffer)
if extraField!=NULL, the extra field information will be copied in extraField
(extraFieldBufferSize is the size of the buffer).
This is the Central-header version of the extra field
if szComment!=NULL, the comment string of the file will be copied in szComment
(commentBufferSize is the size of the buffer)
*/
/** Addition for GDAL : START */
extern ZPOS64_T ZEXPORT unzGetCurrentFileZStreamPos64 OF((unzFile file));
/** Addition for GDAL : END */
/***************************************************************************/
/* for reading the content of the current zipfile, you can open it, read data
from it, and close it (you can close it before reading all the file)
*/
extern int ZEXPORT unzOpenCurrentFile OF((unzFile file));
/*
Open for reading data the current file in the zipfile.
If there is no error, the return value is UNZ_OK.
*/
extern int ZEXPORT unzOpenCurrentFilePassword OF((unzFile file,
const char* password));
/*
Open for reading data the current file in the zipfile.
password is a crypting password
If there is no error, the return value is UNZ_OK.
*/
extern int ZEXPORT unzOpenCurrentFile2 OF((unzFile file,
int* method,
int* level,
int raw));
/*
Same than unzOpenCurrentFile, but open for read raw the file (not uncompress)
if raw==1
*method will receive method of compression, *level will receive level of
compression
note : you can set level parameter as NULL (if you did not want known level,
but you CANNOT set method parameter as NULL
*/
extern int ZEXPORT unzOpenCurrentFile3 OF((unzFile file,
int* method,
int* level,
int raw,
const char* password));
/*
Same than unzOpenCurrentFile, but open for read raw the file (not uncompress)
if raw==1
*method will receive method of compression, *level will receive level of
compression
note : you can set level parameter as NULL (if you did not want known level,
but you CANNOT set method parameter as NULL
*/
extern int ZEXPORT unzCloseCurrentFile OF((unzFile file));
/*
Close the file in zip opened with unzOpenCurrentFile
Return UNZ_CRCERROR if all the file was read but the CRC is not good
*/
extern int ZEXPORT unzReadCurrentFile OF((unzFile file,
voidp buf,
unsigned len));
/*
Read bytes from the current file (opened by unzOpenCurrentFile)
buf contain buffer where data must be copied
len the size of buf.
return the number of byte copied if somes bytes are copied
return 0 if the end of file was reached
return <0 with error code if there is an error
(UNZ_ERRNO for IO error, or zLib error for uncompress error)
*/
extern z_off_t ZEXPORT unztell OF((unzFile file));
extern ZPOS64_T ZEXPORT unztell64 OF((unzFile file));
/*
Give the current position in uncompressed data
*/
extern int ZEXPORT unzeof OF((unzFile file));
/*
return 1 if the end of file was reached, 0 elsewhere
*/
extern int ZEXPORT unzGetLocalExtrafield OF((unzFile file,
voidp buf,
unsigned len));
/*
Read extra field from the current file (opened by unzOpenCurrentFile)
This is the local-header version of the extra field (sometimes, there is
more info in the local-header version than in the central-header)
if buf==NULL, it return the size of the local extra field
if buf!=NULL, len is the size of the buffer, the extra header is copied in
buf.
the return value is the number of bytes copied in buf, or (if <0)
the error code
*/
/***************************************************************************/
/* Get the current file offset */
extern ZPOS64_T ZEXPORT unzGetOffset64 (unzFile file);
extern uLong ZEXPORT unzGetOffset (unzFile file);
/* Set the current file offset */
extern int ZEXPORT unzSetOffset64 (unzFile file, ZPOS64_T pos);
extern int ZEXPORT unzSetOffset (unzFile file, uLong pos);
#ifdef __cplusplus
}
#endif
#endif /* _unz64_H */
File diff suppressed because it is too large Load Diff
+356
View File
@@ -0,0 +1,356 @@
/* zip.h -- IO on .zip files using zlib
Version 1.1, February 14h, 2010
part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
Modifications for Zip64 support
Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
For more info read MiniZip_info.txt
---------------------------------------------------------------------------
Condition of use and distribution are the same than zlib :
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
---------------------------------------------------------------------------
Changes
See header of zip.h
*/
#ifndef _zip12_H
#define _zip12_H
#ifdef __cplusplus
extern "C" {
#endif
//#define HAVE_BZIP2
#ifndef _ZLIB_H
#include "zlib.h"
#endif
#ifndef _ZLIBIOAPI_H
#include "ioapi.h"
#endif
#ifdef HAVE_BZIP2
#include "bzlib.h"
#endif
#define Z_BZIP2ED 12
#if defined(STRICTZIP) || defined(STRICTZIPUNZIP)
/* like the STRICT of WIN32, we define a pointer that cannot be converted
from (void*) without cast */
typedef struct TagzipFile__ { int unused; } zipFile__;
typedef zipFile__ *zipFile;
#else
typedef voidp zipFile;
#endif
#define ZIP_OK (0)
#define ZIP_EOF (0)
#define ZIP_ERRNO (Z_ERRNO)
#define ZIP_PARAMERROR (-102)
#define ZIP_BADZIPFILE (-103)
#define ZIP_INTERNALERROR (-104)
#ifndef DEF_MEM_LEVEL
# if MAX_MEM_LEVEL >= 8
# define DEF_MEM_LEVEL 8
# else
# define DEF_MEM_LEVEL MAX_MEM_LEVEL
# endif
#endif
/* default memLevel */
/* tm_zip contain date/time info */
typedef struct tm_zip_s
{
uInt tm_sec; /* seconds after the minute - [0,59] */
uInt tm_min; /* minutes after the hour - [0,59] */
uInt tm_hour; /* hours since midnight - [0,23] */
uInt tm_mday; /* day of the month - [1,31] */
uInt tm_mon; /* months since January - [0,11] */
uInt tm_year; /* years - [1980..2044] */
} tm_zip;
typedef struct
{
tm_zip tmz_date; /* date in understandable format */
uLong dosDate; /* if dos_date == 0, tmu_date is used */
/* uLong flag; */ /* general purpose bit flag 2 bytes */
uLong internal_fa; /* internal file attributes 2 bytes */
uLong external_fa; /* external file attributes 4 bytes */
} zip_fileinfo;
typedef const char* zipcharpc;
#define APPEND_STATUS_CREATE (0)
#define APPEND_STATUS_CREATEAFTER (1)
#define APPEND_STATUS_ADDINZIP (2)
extern zipFile ZEXPORT zipOpen OF((const char *pathname, int append));
extern zipFile ZEXPORT zipOpen64 OF((const void *pathname, int append));
/*
Create a zipfile.
pathname contain on Windows XP a filename like "c:\\zlib\\zlib113.zip" or on
an Unix computer "zlib/zlib113.zip".
if the file pathname exist and append==APPEND_STATUS_CREATEAFTER, the zip
will be created at the end of the file.
(useful if the file contain a self extractor code)
if the file pathname exist and append==APPEND_STATUS_ADDINZIP, we will
add files in existing zip (be sure you don't add file that doesn't exist)
If the zipfile cannot be opened, the return value is NULL.
Else, the return value is a zipFile Handle, usable with other function
of this zip package.
*/
/* Note : there is no delete function into a zipfile.
If you want delete file into a zipfile, you must open a zipfile, and create another
Of couse, you can use RAW reading and writing to copy the file you did not want delte
*/
extern zipFile ZEXPORT zipOpen2 OF((const char *pathname,
int append,
zipcharpc* globalcomment,
zlib_filefunc_def* pzlib_filefunc_def));
extern zipFile ZEXPORT zipOpen2_64 OF((const void *pathname,
int append,
zipcharpc* globalcomment,
zlib_filefunc64_def* pzlib_filefunc_def));
extern int ZEXPORT zipOpenNewFileInZip OF((zipFile file,
const char* filename,
const zip_fileinfo* zipfi,
const void* extrafield_local,
uInt size_extrafield_local,
const void* extrafield_global,
uInt size_extrafield_global,
const char* comment,
int method,
int level));
extern int ZEXPORT zipOpenNewFileInZip64 OF((zipFile file,
const char* filename,
const zip_fileinfo* zipfi,
const void* extrafield_local,
uInt size_extrafield_local,
const void* extrafield_global,
uInt size_extrafield_global,
const char* comment,
int method,
int level,
int zip64));
/*
Open a file in the ZIP for writing.
filename : the filename in zip (if NULL, '-' without quote will be used
*zipfi contain supplemental information
if extrafield_local!=NULL and size_extrafield_local>0, extrafield_local
contains the extrafield data the the local header
if extrafield_global!=NULL and size_extrafield_global>0, extrafield_global
contains the extrafield data the the local header
if comment != NULL, comment contain the comment string
method contain the compression method (0 for store, Z_DEFLATED for deflate)
level contain the level of compression (can be Z_DEFAULT_COMPRESSION)
zip64 is set to 1 if a zip64 extended information block should be added to the local file header.
this MUST be '1' if the uncompressed size is >= 0xffffffff.
*/
extern int ZEXPORT zipOpenNewFileInZip2 OF((zipFile file,
const char* filename,
const zip_fileinfo* zipfi,
const void* extrafield_local,
uInt size_extrafield_local,
const void* extrafield_global,
uInt size_extrafield_global,
const char* comment,
int method,
int level,
int raw));
extern int ZEXPORT zipOpenNewFileInZip2_64 OF((zipFile file,
const char* filename,
const zip_fileinfo* zipfi,
const void* extrafield_local,
uInt size_extrafield_local,
const void* extrafield_global,
uInt size_extrafield_global,
const char* comment,
int method,
int level,
int raw,
int zip64));
/*
Same than zipOpenNewFileInZip, except if raw=1, we write raw file
*/
extern int ZEXPORT zipOpenNewFileInZip3 OF((zipFile file,
const char* filename,
const zip_fileinfo* zipfi,
const void* extrafield_local,
uInt size_extrafield_local,
const void* extrafield_global,
uInt size_extrafield_global,
const char* comment,
int method,
int level,
int raw,
int windowBits,
int memLevel,
int strategy,
const char* password,
uLong crcForCrypting));
extern int ZEXPORT zipOpenNewFileInZip3_64 OF((zipFile file,
const char* filename,
const zip_fileinfo* zipfi,
const void* extrafield_local,
uInt size_extrafield_local,
const void* extrafield_global,
uInt size_extrafield_global,
const char* comment,
int method,
int level,
int raw,
int windowBits,
int memLevel,
int strategy,
const char* password,
uLong crcForCrypting,
int zip64
));
/*
Same than zipOpenNewFileInZip2, except
windowBits,memLevel,,strategy : see parameter strategy in deflateInit2
password : crypting password (NULL for no crypting)
crcForCrypting : crc of file to compress (needed for crypting)
*/
extern int ZEXPORT zipOpenNewFileInZip4 OF((zipFile file,
const char* filename,
const zip_fileinfo* zipfi,
const void* extrafield_local,
uInt size_extrafield_local,
const void* extrafield_global,
uInt size_extrafield_global,
const char* comment,
int method,
int level,
int raw,
int windowBits,
int memLevel,
int strategy,
const char* password,
uLong crcForCrypting,
uLong versionMadeBy,
uLong flagBase
));
extern int ZEXPORT zipOpenNewFileInZip4_64 OF((zipFile file,
const char* filename,
const zip_fileinfo* zipfi,
const void* extrafield_local,
uInt size_extrafield_local,
const void* extrafield_global,
uInt size_extrafield_global,
const char* comment,
int method,
int level,
int raw,
int windowBits,
int memLevel,
int strategy,
const char* password,
uLong crcForCrypting,
uLong versionMadeBy,
uLong flagBase,
int zip64
));
/*
Same than zipOpenNewFileInZip4, except
versionMadeBy : value for Version made by field
flag : value for flag field (compression level info will be added)
*/
extern int ZEXPORT zipWriteInFileInZip OF((zipFile file,
const void* buf,
unsigned len));
/*
Write data in the zipfile
*/
extern int ZEXPORT zipCloseFileInZip OF((zipFile file));
/*
Close the current file in the zipfile
*/
extern int ZEXPORT zipCloseFileInZipRaw OF((zipFile file,
uLong uncompressed_size,
uLong crc32));
extern int ZEXPORT zipCloseFileInZipRaw64 OF((zipFile file,
ZPOS64_T uncompressed_size,
uLong crc32));
/*
Close the current file in the zipfile, for file opened with
parameter raw=1 in zipOpenNewFileInZip2
uncompressed_size and crc32 are value for the uncompressed size
*/
extern int ZEXPORT zipClose OF((zipFile file,
const char* global_comment));
/*
Close the zipfile
*/
extern int ZEXPORT zipRemoveExtraInfoBlock OF((char* pData, int* dataLen, short sHeader));
/*
zipRemoveExtraInfoBlock - Added by Mathias Svensson
Remove extra information block from a extra information data for the local file header or central directory header
It is needed to remove ZIP64 extra information blocks when before data is written if using RAW mode.
0x0001 is the signature header for the ZIP64 extra information blocks
usage.
Remove ZIP64 Extra information from a central director extra field data
zipRemoveExtraInfoBlock(pCenDirExtraFieldData, &nCenDirExtraFieldDataLen, 0x0001);
Remove ZIP64 Extra information from a Local File Header extra field data
zipRemoveExtraInfoBlock(pLocalHeaderExtraFieldData, &nLocalHeaderExtraFieldDataLen, 0x0001);
*/
#ifdef __cplusplus
}
#endif
#endif /* _zip64_H */
+50
View File
@@ -0,0 +1,50 @@
#ifndef CompilerDetect_h__
#define CompilerDetect_h__
namespace LifeCore{
/*enum CompilerType{
CT_GCC,
CT_Intel,
CT_MwCodewarrior,
CT_MinGw,
CT_BorlandCpp,
CT_Clang,
CT_DigitalMars,
CT_IbmXl,
CT_KeilCArm,
CT_AltiumMbC,
CT_AltiumCthw
}*/
#if defined(__GNUC__)
#define COMPILER_GCC
#elif defined(__INTEL_COMPILER) | (__ICC) | (__ECC) | (__ICL)
#define COMPILER_INTEL
#elif defined(__MWERKS__) | defined(__CWCC__)
#define COMPILER_MW_CODEWARRIOR
#elif defined(_MSC_VER)
#define COMPILER_MSVC
#elif defined(__MINGW32__)
#define COMPILER_MINGW
#define COMPILER_MINGW32
#elif defined(__MINGW64__)
#define COMPILER_MINGW
#define COMPILER_MINGW64
#elif defined(__BORLANDC__) | defined(__CODEGEARC__)
#define COMPILER_BORLAND_CPP
#elif defined(__clang__)
#define COMPILER_CLANG
#elif defined(__DMC__)
#define COMPILER_DIGITALMARS
#elif defined(__xlc__) | defined(__xlC__) | defined(__xlC_ver__) | defined(__IBMC__) | defined(__IBMCPP__)
#define COMPILER_IBM_XL
#elif defined(__CA__) | defined(__KEIL__)
#define COMPILER_KEIL_CARM
#elif defined(__CMB__)
#define COMPILER_ALTIUM_MB_C
#elif defined(__CHC__)
#define COMPILER_ALTIUM_CTHW
#endif
}
#endif // CompilerDetect_h__
+18
View File
@@ -0,0 +1,18 @@
#ifndef Inline_h__
#define Inline_h__
#include "CompilerDetect.h"
namespace LifeCore{
#if defined(COMPILER_MSVC)
#define FORCEINLINE __forceinline
#elif defined(COMPILER_GCC)
#define FORCEINLINE __attribute__((always_inline))
#else
#define FORCEINLINE inline
#endif
#define INLINE inline
}
#endif // Inline_h__

Some files were not shown because too many files have changed in this diff Show More