init repo - middle of crane assignment

This commit is contained in:
Hugo Willaume 2018-11-14 10:46:35 +09:00
commit f020c3dd81
36 changed files with 35239 additions and 0 deletions

334
.gitignore vendored Normal file
View File

@ -0,0 +1,334 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/

56
BaseGLProject/ADrawable.h Normal file
View File

@ -0,0 +1,56 @@
#pragma once
#include <queue>
#include "IDrawable.h"
enum Transformation
{
Rotation,
Translation,
Scaling
};
class ADrawable : IDrawable {
protected:
std::vector<std::pair<glm::vec4, Transformation>> _transformations;
Model _model;
void effectTransformations()
{
for (auto pair : _transformations)
{
switch (pair.second)
{
case(Rotation):
_model.glRotate(pair.first.w, pair.first.x, pair.first.y, pair.first.z);
break;
case(Translation):
_model.glTranslate(pair.first.x, pair.first.y, pair.first.z);
break;
case(Scaling):
_model.glScale(pair.first.x, pair.first.y, pair.first.z);
break;
}
}
}
public:
virtual void draw(ShaderProgram *shader, glm::mat4x4 pv) = 0;
virtual DrawableType getType() = 0;
void addRotation(glm::vec4 vec) override
{
_transformations.emplace_back(vec, Rotation);
}
void addTranslation(glm::vec4 vec) override
{
_transformations.emplace_back(vec, Translation);
}
void addScaling(glm::vec4 vec) override
{
_transformations.emplace_back(vec, Scaling);
}
};

View File

@ -0,0 +1,200 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.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="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>15.0</VCProjectVersion>
<ProjectGuid>{53EA9451-7504-4B40-9986-47ECD7AA35D8}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>BaseGLProject</RootNamespace>
<WindowsTargetPlatformVersion>10.0.17134.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</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 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 Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<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|x64'">
<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>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>C:\Graphics\Tools\glew\include;C:\Graphics\Tools\glm;C:\Graphics\Tools\glfw\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<AdditionalLibraryDirectories>C:\Graphics\Tools\glfw\lib\x86;C:\Graphics\Tools\glew\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalDependencies>glfw3.lib;glew32.lib;opengl32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="CheckeredFloor.cpp" />
<ClCompile Include="ColorCube.cpp" />
<ClCompile Include="imgui\imgui.cpp" />
<ClCompile Include="imgui\imgui_demo.cpp" />
<ClCompile Include="imgui\imgui_draw.cpp" />
<ClCompile Include="imgui\imgui_impl_glfw.cpp" />
<ClCompile Include="imgui\imgui_impl_opengl3.cpp" />
<ClCompile Include="imgui\imgui_widgets.cpp" />
<ClCompile Include="MyGLWindow.cpp" />
<ClCompile Include="Source.cpp" />
<ClCompile Include="Viewer.cpp" />
<ClCompile Include="WireCube.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="ADrawable.h" />
<ClInclude Include="CheckeredFloor.h" />
<ClInclude Include="ColorCube.h" />
<ClInclude Include="IDrawable.h" />
<ClInclude Include="imgui\imconfig.h" />
<ClInclude Include="imgui\imgui.h" />
<ClInclude Include="imgui\imgui_impl_glfw.h" />
<ClInclude Include="imgui\imgui_impl_opengl3.h" />
<ClInclude Include="imgui\imgui_internal.h" />
<ClInclude Include="imgui\imstb_rectpack.h" />
<ClInclude Include="imgui\imstb_textedit.h" />
<ClInclude Include="imgui\imstb_truetype.h" />
<ClInclude Include="Loader.h" />
<ClInclude Include="ModelView.h" />
<ClInclude Include="MyGLWindow.h" />
<ClInclude Include="Viewer.h" />
<ClInclude Include="WireCube.h" />
</ItemGroup>
<ItemGroup>
<None Include="simple.vert">
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Geometry</ShaderType>
<ShaderModel Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">4.0</ShaderModel>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Geometry</ShaderType>
<ShaderModel Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">4.0</ShaderModel>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Geometry</ShaderType>
<ShaderModel Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">4.0</ShaderModel>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Geometry</ShaderType>
<ShaderModel Condition="'$(Configuration)|$(Platform)'=='Release|x64'">4.0</ShaderModel>
<FileType>Document</FileType>
</None>
</ItemGroup>
<ItemGroup>
<None Include="simple.frag" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,122 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
<Filter Include="Shaders">
<UniqueIdentifier>{9f40fac6-e9ab-42de-a9e9-3cb8ce88833c}</UniqueIdentifier>
</Filter>
<Filter Include="imgui">
<UniqueIdentifier>{4ea3f893-d13b-4d3c-a496-f05d5b3aeeb4}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="Source.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="MyGLWindow.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="ColorCube.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Viewer.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="CheckeredFloor.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="imgui\imgui.cpp">
<Filter>imgui</Filter>
</ClCompile>
<ClCompile Include="imgui\imgui_demo.cpp">
<Filter>imgui</Filter>
</ClCompile>
<ClCompile Include="imgui\imgui_draw.cpp">
<Filter>imgui</Filter>
</ClCompile>
<ClCompile Include="imgui\imgui_impl_glfw.cpp">
<Filter>imgui</Filter>
</ClCompile>
<ClCompile Include="imgui\imgui_impl_opengl3.cpp">
<Filter>imgui</Filter>
</ClCompile>
<ClCompile Include="imgui\imgui_widgets.cpp">
<Filter>imgui</Filter>
</ClCompile>
<ClCompile Include="WireCube.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="ColorCube.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="ModelView.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="IDrawable.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Loader.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="MyGLWindow.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Viewer.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="CheckeredFloor.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="imgui\imconfig.h">
<Filter>imgui</Filter>
</ClInclude>
<ClInclude Include="imgui\imgui.h">
<Filter>imgui</Filter>
</ClInclude>
<ClInclude Include="imgui\imgui_impl_glfw.h">
<Filter>imgui</Filter>
</ClInclude>
<ClInclude Include="imgui\imgui_impl_opengl3.h">
<Filter>imgui</Filter>
</ClInclude>
<ClInclude Include="imgui\imgui_internal.h">
<Filter>imgui</Filter>
</ClInclude>
<ClInclude Include="imgui\imstb_rectpack.h">
<Filter>imgui</Filter>
</ClInclude>
<ClInclude Include="imgui\imstb_textedit.h">
<Filter>imgui</Filter>
</ClInclude>
<ClInclude Include="imgui\imstb_truetype.h">
<Filter>imgui</Filter>
</ClInclude>
<ClInclude Include="WireCube.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="ADrawable.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<None Include="simple.frag">
<Filter>Shaders</Filter>
</None>
<None Include="simple.vert">
<Filter>Shaders</Filter>
</None>
</ItemGroup>
</Project>

View File

@ -0,0 +1,97 @@
#include "CheckeredFloor.h"
void CheckeredFloor::genVertices(std::vector<glm::vec4> &vertices,
std::vector<glm::vec3> &colors)
{
float maxX = _size / 2.f, maxY = _size / 2.f;
float minX = -_size / 2.f, minY = -_size / 2.f;
float side_size = _size / (float)_squares;
int color = 1;
for (float x = minX; x < maxX; x += side_size)
{
for (float y = minY; y < maxY; y += side_size)
{
color *= -1;
glm::vec3 tile_color = (color > 0) ? _light_color : _dark_color;
//gen 1 carré
vertices.emplace_back(x, 0, y, 1); //upleft
vertices.emplace_back(x + side_size, 0, y, 1); //upright
vertices.emplace_back(x, 0, y + side_size, 1); //downleft
vertices.emplace_back(x + side_size, 0, y, 1); //upright
vertices.emplace_back(x, 0, y + side_size, 1); //downleft
vertices.emplace_back(x + side_size, 0, y + side_size, 1); //downright
for (int z = 0; z < 6; z++)
colors.push_back(tile_color);
}
color *= -1;
}
}
void CheckeredFloor::setup()
{
std::vector<glm::vec4> floor_vertices;
std::vector<glm::vec3> floor_colors;
glGenVertexArrays(1, &_vaoHandle);
glBindVertexArray(_vaoHandle);
genVertices(floor_vertices, floor_colors);
glGenBuffers(1, &_vbo_vertices);
glBindBuffer(GL_ARRAY_BUFFER, _vbo_vertices);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * floor_vertices.size() * 4, floor_vertices.data(), GL_STATIC_DRAW);
glVertexAttribPointer(
0, //attr number = 0
4,
GL_FLOAT,
GL_FALSE,
0,
(void*)0);
glEnableVertexAttribArray(0); //attr number = 0
glGenBuffers(1, &_vbo_colors);
glBindBuffer(GL_ARRAY_BUFFER, _vbo_colors);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * floor_colors.size() * 3, floor_colors.data(), GL_STATIC_DRAW);
glVertexAttribPointer(
1,
3,
GL_FLOAT,
GL_FALSE,
0,
(void *)0);
glEnableVertexAttribArray(1);
glBindVertexArray(0);
}
CheckeredFloor::CheckeredFloor(int size, int squares) :
_size(size), _squares(squares)
{
setup();
}
CheckeredFloor::~CheckeredFloor()
{
}
void CheckeredFloor::draw(ShaderProgram * shader, glm::mat4x4 pv)
{
_model.glPushMatrix();
effectTransformations();
glBindVertexArray(_vaoHandle);
glm::mat4 mvpMatrix = pv * _model.getMatrix();
glUniformMatrix4fv(shader->uniform("mvp"), 1, GL_FALSE, glm::value_ptr(mvpMatrix));
glDrawArrays(GL_TRIANGLES, 0, _squares * _squares * 6);
_model.glPopMatrix();
}
DrawableType CheckeredFloor::getType()
{
return DrawableType::CHECKERED_FLOOR;
}

View File

@ -0,0 +1,31 @@
#pragma once
#define GLM_SWIZZLE
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/glm.hpp>
#include <glm/gtx/string_cast.hpp>
#include <vector>
#include "ADrawable.h"
class CheckeredFloor : public ADrawable
{
private :
GLuint _vaoHandle;
GLuint _vbo_vertices, _vbo_colors;
void genVertices(std::vector<glm::vec4> &vertices,
std::vector<glm::vec3> &colors);
void setup();
glm::vec3 _light_color = {.7f, .7f, .7f};
glm::vec3 _dark_color = {.3f, .3f, .3f};
int _size;
int _squares;
public :
CheckeredFloor(int size, int squares);
~CheckeredFloor();
void draw(ShaderProgram *shader, glm::mat4x4 pv) override;
DrawableType getType() override;
};

101
BaseGLProject/ColorCube.cpp Normal file
View File

@ -0,0 +1,101 @@
#include "ColorCube.h"
void ColorCube::setup()
{
std::vector<glm::vec3> cube_vertices =
{ { -1.0, -1.0, 1.0},
{ 1.0, -1.0, 1.0},
{ 1.0, 1.0, 1.0},
{ -1.0, 1.0, 1.0},
{ -1.0, -1.0, -1.0},
{ 1.0, -1.0, -1.0},
{ 1.0, 1.0, -1.0},
{ -1.0, 1.0, -1.0} };
GLfloat cube_colors[] = {
// front colors
1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0,
1.0, 1.0, 1.0,
// back colors
1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0,
1.0, 1.0, 1.0,
};
GLushort cube_elements[] = {
0, 1, 2, 2, 3, 0, 1, 5, 6,
6, 2, 1, 7, 6, 5, 5, 4, 7,
4, 0, 3, 3, 7, 4, 4, 5, 1,
1, 0, 4, 3, 2, 6, 6, 7, 3,
};
glGenVertexArrays(1, &_vaoHandle);
glBindVertexArray(_vaoHandle);
glGenBuffers(1, &_vbo_vertices);
glBindBuffer(GL_ARRAY_BUFFER, _vbo_vertices);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * cube_vertices.size() * 3, cube_vertices.data(), GL_STATIC_DRAW);
glVertexAttribPointer(
0, //attr number = 0
3,
GL_FLOAT,
GL_FALSE,
0,
(void*)0);
glEnableVertexAttribArray(0); //attr number = 0
glGenBuffers(1, &_vbo_colors);
glBindBuffer(GL_ARRAY_BUFFER, _vbo_colors);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 24, cube_colors, GL_STATIC_DRAW);
glVertexAttribPointer(
1,
3,
GL_FLOAT,
GL_FALSE,
0,
(void*)0);
glEnableVertexAttribArray(1);
glGenBuffers(1, &_iboHandle);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _iboHandle);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(cube_elements), cube_elements, GL_STATIC_DRAW);
glBindVertexArray(0);
}
ColorCube::ColorCube()
{
setup();
}
void ColorCube::draw(ShaderProgram *shader, glm::mat4x4 pv)
{
_model.glPushMatrix();
effectTransformations();
glBindVertexArray(_vaoHandle);
int size;
glGetBufferParameteriv(GL_ELEMENT_ARRAY_BUFFER, GL_BUFFER_SIZE, &size);
glm::mat4 mvpMatrix = pv * _model.getMatrix();
glUniformMatrix4fv(shader->uniform("mvp"), 1, GL_FALSE, glm::value_ptr(mvpMatrix));
glDrawElements(GL_TRIANGLES, size / sizeof(GLushort), GL_UNSIGNED_SHORT, 0);
_model.glPopMatrix();
}
DrawableType ColorCube::getType()
{
return DrawableType::COLOR_CUBE;
}
ColorCube::~ColorCube()
{
}

24
BaseGLProject/ColorCube.h Normal file
View File

@ -0,0 +1,24 @@
#include <iostream>
#include <string>
#include <vector>
#include <glm/vec4.hpp>
#include "ADrawable.h"
#pragma once
class ColorCube : public ADrawable
{
private:
GLuint _vaoHandle;
GLuint _iboHandle;
GLuint _vbo_vertices, _vbo_colors;
void setup();
public:
ColorCube();
void draw(ShaderProgram *shader, glm::mat4x4 pv) override;
DrawableType getType() override;
~ColorCube();
};

23
BaseGLProject/IDrawable.h Normal file
View File

@ -0,0 +1,23 @@
#pragma once
#include "GL/glew.h"
#include "glm/gtc/type_ptr.hpp"
#include "Loader.h"
#include "ModelView.h"
enum DrawableType
{
COLOR_CUBE,
CHECKERED_FLOOR,
WIRE_CUBE
};
class IDrawable {
public:
virtual void addRotation(glm::vec4 vec) = 0;
virtual void addTranslation(glm::vec4 vec) = 0;
virtual void addScaling(glm::vec4 vec) = 0;
virtual void draw(ShaderProgram *shader, glm::mat4x4 pv) = 0;
virtual DrawableType getType() = 0;
};

395
BaseGLProject/Loader.h Normal file
View File

@ -0,0 +1,395 @@
/***
author : r3dux
version : 0.3 - 15/01/2014
description: Gets GLSL source code either provided as strings or can load from filenames,
compiles the shaders, creates a shader program which the shaders are linked
to, then the program is validated and is ready for use via myProgram.use(),
<draw-stuff-here> then calling myProgram.disable();
Attributes and uniforms are stored in <string, int> maps and can be added
via calls to addAttribute(<name-of-attribute>) and then the attribute
index can be obtained via myProgram.attribute(<name-of-attribute>) - Uniforms
work in the exact same way.
***/
#ifndef SHADER_PROGRAM_HPP
#define SHADER_PROGRAM_HPP
#include <iostream>
#include <fstream>
#include <sstream>
#include <map>
class ShaderProgram
{
private:
// static DEBUG flag - if set to false then, errors aside, we'll run completely silent
static const bool DEBUG = true;
// We'll use an enum to differentiate between shaders and shader programs when querying the info log
enum class ObjectType
{
SHADER, PROGRAM
};
// Shader program and individual shader Ids
GLuint programId;
GLuint vertexShaderId;
GLuint fragmentShaderId;
// How many shaders are attached to the shader program
GLuint shaderCount;
// Map of attributes and their binding locations
std::map<std::string, int> attributeMap;
// Map of uniforms and their binding locations
std::map<std::string, int> uniformMap;
// Has this shader program been initialised?
bool initialised;
// ---------- PRIVATE METHODS ----------
// Private method to compile a shader of a given type
GLuint compileShader(std::string shaderSource, GLenum shaderType)
{
std::string shaderTypeString;
switch (shaderType)
{
case GL_VERTEX_SHADER:
shaderTypeString = "GL_VERTEX_SHADER";
break;
case GL_FRAGMENT_SHADER:
shaderTypeString = "GL_FRAGMENT_SHADER";
break;
case GL_GEOMETRY_SHADER:
throw std::runtime_error("Geometry shaders are unsupported at this time.");
break;
default:
throw std::runtime_error("Bad shader type enum in compileShader.");
break;
}
// Generate a shader id
// Note: Shader id will be non-zero if successfully created.
GLuint shaderId = glCreateShader(shaderType);
if (shaderId == 0)
{
// Display the shader log via a runtime_error
throw std::runtime_error("Could not create shader of type " + shaderTypeString + ": " + getInfoLog(ObjectType::SHADER, shaderId));
}
// Get the source string as a pointer to an array of characters
const char *shaderSourceChars = shaderSource.c_str();
// Attach the GLSL source code to the shader
// Params: GLuint shader, GLsizei count, const GLchar **string, const GLint *length
// Note: The pointer to an array of source chars will be null terminated, so we don't need to specify the length and can instead use NULL.
glShaderSource(shaderId, 1, &shaderSourceChars, NULL);
// Compile the shader
glCompileShader(shaderId);
// Check the compilation status and throw a runtime_error if shader compilation failed
GLint shaderStatus;
glGetShaderiv(shaderId, GL_COMPILE_STATUS, &shaderStatus);
if (shaderStatus == GL_FALSE)
{
throw std::runtime_error(shaderTypeString + " compilation failed: " + getInfoLog(ObjectType::SHADER, shaderId));
}
else
{
if (DEBUG)
{
std::cout << shaderTypeString << " shader compilation successful." << std::endl;
}
}
// If everything went well, return the shader id
return shaderId;
}
// Private method to compile/attach/link/verify the shaders.
// Note: Rather than returning a boolean as a success/fail status we'll just consider
// a failure here to be an unrecoverable error and throw a runtime_error.
void initialise(std::string vertexShaderSource, std::string fragmentShaderSource)
{
// Compile the shaders and return their id values
vertexShaderId = compileShader(vertexShaderSource, GL_VERTEX_SHADER);
fragmentShaderId = compileShader(fragmentShaderSource, GL_FRAGMENT_SHADER);
// Attach the compiled shaders to the shader program
glAttachShader(programId, vertexShaderId);
glAttachShader(programId, fragmentShaderId);
// Link the shader program - details are placed in the program info log
glLinkProgram(programId);
// Once the shader program has the shaders attached and linked, the shaders are no longer required.
// If the linking failed, then we're going to abort anyway so we still detach the shaders.
glDetachShader(programId, vertexShaderId);
glDetachShader(programId, fragmentShaderId);
// Check the program link status and throw a runtime_error if program linkage failed.
GLint programLinkSuccess = GL_FALSE;
glGetProgramiv(programId, GL_LINK_STATUS, &programLinkSuccess);
if (programLinkSuccess == GL_TRUE)
{
if (DEBUG)
{
std::cout << "Shader program link successful." << std::endl;
}
}
else
{
throw std::runtime_error("Shader program link failed: " + getInfoLog(ObjectType::PROGRAM, programId));
}
// Validate the shader program
glValidateProgram(programId);
// Check the validation status and throw a runtime_error if program validation failed
GLint programValidatationStatus;
glGetProgramiv(programId, GL_VALIDATE_STATUS, &programValidatationStatus);
if (programValidatationStatus == GL_TRUE)
{
if (DEBUG)
{
std::cout << "Shader program validation successful." << std::endl;
}
}
else
{
throw std::runtime_error("Shader program validation failed: " + getInfoLog(ObjectType::PROGRAM, programId));
}
// Finally, the shader program is initialised
initialised = true;
}
// Private method to load the shader source code from a file
std::string loadShaderFromFile(const std::string filename)
{
// Create an input filestream and attempt to open the specified file
std::ifstream file(filename.c_str());
// If we couldn't open the file we'll bail out
if (!file.good())
{
throw std::runtime_error("Failed to open file: " + filename);
}
// Otherwise, create a string stream...
std::stringstream stream;
// ...and dump the contents of the file into it.
stream << file.rdbuf();
// Now that we've read the file we can close it
file.close();
// Finally, convert the stringstream into a string and return it
return stream.str();
}
// Private method to return the current shader program info log as a string
std::string getInfoLog(ObjectType type, int id)
{
GLint infoLogLength;
if (type == ObjectType::SHADER)
{
glGetShaderiv(id, GL_INFO_LOG_LENGTH, &infoLogLength);
}
else // type must be ObjectType::PROGRAM
{
glGetProgramiv(id, GL_INFO_LOG_LENGTH, &infoLogLength);
}
GLchar *infoLog = new GLchar[infoLogLength + 1];
if (type == ObjectType::SHADER)
{
glGetShaderInfoLog(id, infoLogLength, NULL, infoLog);
}
else // type must be ObjectType::PROGRAM
{
glGetProgramInfoLog(id, infoLogLength, NULL, infoLog);
}
// Convert the info log to a string
std::string infoLogString(infoLog);
// Delete the char array version of the log
delete[] infoLog;
// Finally, return the string version of the info log
return infoLogString;
}
public:
// Constructor
ShaderProgram()
{
// We start in a non-initialised state - calling initFromFiles() or initFromStrings() will
// initialise us.
initialised = false;
// Generate a unique Id / handle for the shader program
// Note: We MUST have a valid rendering context before generating the programId or we'll segfault!
programId = glCreateProgram();
glUseProgram(programId);
// Initially, we have zero shaders attached to the program
shaderCount = 0;
}
// Destructor
~ShaderProgram()
{
// Delete the shader program from the graphics card memory to
// free all the resources it's been using
glDeleteProgram(programId);
}
// Method to initialise a shader program from shaders provided as files
void initFromFiles(std::string vertexShaderFilename, std::string fragmentShaderFilename)
{
// Get the shader file contents as strings
std::string vertexShaderSource = loadShaderFromFile(vertexShaderFilename);
std::string fragmentShaderSource = loadShaderFromFile(fragmentShaderFilename);
initialise(vertexShaderSource, fragmentShaderSource);
}
// Method to initialise a shader program from shaders provided as strings
void initFromStrings(std::string vertexShaderSource, std::string fragmentShaderSource)
{
initialise(vertexShaderSource, fragmentShaderSource);
}
// Method to enable the shader program - we'll suggest this for inlining
inline void use()
{
// Santity check that we're initialised and ready to go...
if (initialised)
{
glUseProgram(programId);
}
else
{
std::string msg = "Shader program " + programId;
msg += " not initialised - aborting.";
throw std::runtime_error(msg);
}
}
// Method to disable the shader - we'll also suggest this for inlining
inline void disable()
{
glUseProgram(0);
}
// Method to return the bound location of a named attribute, or -1 if the attribute was not found
GLuint attribute(const std::string attributeName)
{
// You could do this method with the single line:
//
// return attributeMap[attribute];
//
// BUT, if you did, and you asked it for a named attribute which didn't exist
// like: attributeMap["FakeAttrib"] then the method would return an invalid
// value which will likely cause the program to segfault. So we're making sure
// the attribute asked for exists, and if it doesn't then we alert the user & bail.
// Create an iterator to look through our attribute map (only create iterator on first run -
// reuse it for all further calls).
static std::map<std::string, int>::const_iterator attributeIter;
// Try to find the named attribute
attributeIter = attributeMap.find(attributeName);
// Not found? Bail.
if (attributeIter == attributeMap.end())
{
throw std::runtime_error("Could not find attribute in shader program: " + attributeName);
}
// Otherwise return the attribute location from the attribute map
return attributeMap[attributeName];
}
// Method to returns the bound location of a named uniform
GLuint uniform(const std::string uniformName)
{
// Note: You could do this method with the single line:
//
// return uniformLocList[uniform];
//
// But we're not doing that. Explanation in the attribute() method above.
// Create an iterator to look through our uniform map (only create iterator on first run -
// reuse it for all further calls).
static std::map<std::string, int>::const_iterator uniformIter;
// Try to find the named uniform
uniformIter = uniformMap.find(uniformName);
// Found it? Great - pass it back! Didn't find it? Alert user and halt.
if (uniformIter == uniformMap.end())
{
throw std::runtime_error("Could not find uniform in shader program: " + uniformName);
}
// Otherwise return the attribute location from the uniform map
return uniformMap[uniformName];
}
// Method to add an attribute to the shader and return the bound location
int addAttribute(const std::string attributeName)
{
// Add the attribute location value for the attributeName key
attributeMap[attributeName] = glGetAttribLocation(programId, attributeName.c_str());
// Check to ensure that the shader contains an attribute with this name
if (attributeMap[attributeName] == -1)
{
throw std::runtime_error("Could not add attribute: " + attributeName + " - location returned -1.");
}
else // Valid attribute location? Inform user if we're in debug mode.
{
if (DEBUG)
{
std::cout << "Attribute " << attributeName << " bound to location: " << attributeMap[attributeName] << std::endl;
}
}
// Return the attribute location
return attributeMap[attributeName];
}
// Method to add a uniform to the shader and return the bound location
int addUniform(const std::string uniformName)
{
// Add the uniform location value for the uniformName key
uniformMap[uniformName] = glGetUniformLocation(programId, uniformName.c_str());
// Check to ensure that the shader contains a uniform with this name
if (uniformMap[uniformName] == -1)
{
throw std::runtime_error("Could not add uniform: " + uniformName + " - location returned -1.");
}
else // Valid uniform location? Inform user if we're in debug mode.
{
if (DEBUG)
{
//std::cout << "Uniform " << uniformName << " bound to location: " << uniformMap[uniformName] << std::endl;
}
}
// Return the uniform location
return uniformMap[uniformName];
}
}; // End of class
#endif // SHADER_PROGRAM_HPP

66
BaseGLProject/ModelView.h Normal file
View File

@ -0,0 +1,66 @@
#ifndef _MODELVIEW
#define _MODELVIEW
#include <stack>
#include <glm/glm.hpp>
#include "glm/mat4x4.hpp"
#include <glm/gtc/matrix_transform.hpp>
class Model
{
public:
std::stack<glm::mat4> modelstack;
Model() {
glm::mat4 id(1.0);
modelstack.push(id);
}
void glTranslate(float x, float y, float z)
{
glm::mat4 Trans = glm::translate(glm::mat4(1.0f), glm::vec3(x, y, z));
modelstack.top() = modelstack.top() * Trans;
}
void glRotate(float degree, float x, float y, float z)
{
glm::mat4 rot = glm::rotate(glm::mat4(1.0f), glm::radians(degree), glm::vec3(x, y, z));
modelstack.top() = modelstack.top() * rot;
}
void glScale(float x, float y, float z)
{
glm::mat4 scale = glm::scale(glm::mat4(1.0f), glm::vec3(x, y, z));
modelstack.top() = modelstack.top() * scale;
}
void glPushMatrix()
{
glm::mat4 t = getMatrix();
modelstack.push(t);
}
glm::mat4 getMatrix()
{
if (modelstack.size() > 0)
return modelstack.top();
return glm::mat4(1.0);
}
void glPopMatrix()
{
modelstack.pop();
}
};
#endif

View File

@ -0,0 +1,160 @@
#include <algorithm>
#include "MyGlWindow.h"
glm::mat4x4 perspective(float fovy, float aspect, float near, float far)
{
float fovy2 = glm::tan(fovy / 2);
glm::mat4x4 pmat{ { 1 / (aspect * fovy2), 0, 0, 0},
{ 0, 1 / fovy2, 0, 0},
{ 0, 0, -((far + near) / (far - near)), -1},
{ 0, 0, -((2 * far * near) / (far - near)), 0} };
return pmat;
}
// Getting the view matrix
glm::mat4x4 lookAt(glm::vec3 campos, glm::vec3 look, glm::vec3 up)
{
glm::vec3 ZCam(glm::normalize(campos - look));
glm::vec3 XCam(glm::normalize(glm::cross(up, ZCam)));
glm::vec3 YCam(glm::normalize(glm::cross(ZCam, XCam)));
glm::mat4x4 cam_mat{ {XCam.x, YCam.x, ZCam.x, 0},
{XCam.y, YCam.y, ZCam.y, 0},
{XCam.z, YCam.z, ZCam.z, 0},
{0, 0, 0 ,1} };
glm::mat4x4 norm_mat{ {1, 0, 0, 0},
{0, 1, 0, 0},
{0, 0, 1, 0},
{-campos.x, -campos.y, -campos.z, 1} };
return cam_mat * norm_mat;
}
MyGlWindow::MyGlWindow(int w, int h) :
viewer(glm::vec3(5, 5, 5), glm::vec3(0, 0, 0), glm::vec3(0, 1, 0), 45.0f, (w / (float)h)),
_floor(50, 16)
{
m_width = w;
m_height = h;
setup();
setupCubeBuffer();
}
MyGlWindow::~MyGlWindow()
{
}
void MyGlWindow::setBgColor(float bgColor[3])
{
_bgColor[0] = bgColor[0];
_bgColor[1] = bgColor[1];
_bgColor[2] = bgColor[2];
}
void MyGlWindow::setup()
{
_shaderProgram = new ShaderProgram();
_shaderProgram->initFromFiles("simple.vert", "simple.frag");
_drawables.emplace_back(new CheckeredFloor(50, 16));
_drawables.emplace_back(new WireCube());
_drawables.back()->addTranslation(glm::vec4(0, 1, 0, 0));
}
void MyGlWindow::setupCubeBuffer()
{
}
void MyGlWindow::setupRectBuffer()
{
GLuint vbo_cube_vertices;
glGenVertexArrays(1, &_vaoHandle);
glBindVertexArray(_vaoHandle);
vertexAttr* verts = new vertexAttr[6];
verts[0].posX = -0.3f; verts[0].posY = 0.4f; verts[0].posZ = 0;
verts[0].r = 1; verts[0].g = 0; verts[0].b = 0;
verts[1].posX = -0.3f; verts[1].posY = -0.4f; verts[1].posZ = 0;
verts[1].r = 0; verts[1].g = 1; verts[1].b = 0;
verts[2].posX = 0.3f; verts[2].posY = -0.4f; verts[2].posZ = 0;
verts[2].r = 0; verts[2].g = 0; verts[2].b = 1;
verts[3].posX = 0.3f; verts[3].posY = -0.4f; verts[3].posZ = 0;
verts[3].r = 0; verts[3].g = 0; verts[3].b = 1;
verts[4].posX = 0.3f; verts[4].posY = 0.4f; verts[4].posZ = 0;
verts[4].r = 0; verts[4].g = 1; verts[4].b = 0;
verts[5].posX = -0.3f; verts[5].posY = 0.4f; verts[5].posZ = 0;
verts[5].r = 1; verts[5].g = 0; verts[5].b = 0;
glGenBuffers(1, &vbo_cube_vertices);
glBindBuffer(GL_ARRAY_BUFFER, vbo_cube_vertices);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertexAttr) * 6, verts, GL_STATIC_DRAW);
glVertexAttribPointer(
0, //attr number = 0
3,
GL_FLOAT,
GL_FALSE,
sizeof(vertexAttr),
(void*)0);
glEnableVertexAttribArray(0); //attr number = 0
glVertexAttribPointer(
1,
3,
GL_FLOAT,
GL_FALSE,
sizeof(vertexAttr),
(void*)(sizeof(GLfloat) * 3));
glEnableVertexAttribArray(1);
glBindVertexArray(0);
}
void MyGlWindow::draw()
{
glClearColor(_bgColor[0], _bgColor[1], _bgColor[2], 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glViewport(0, 0, m_width, m_height);
glEnable(GL_DEPTH_TEST);
_shaderProgram->use();
glm::vec3 eye(viewer.getViewPoint().x, viewer.getViewPoint().y, viewer.getViewPoint().z);
glm::vec3 look(viewer.getViewCenter().x, viewer.getViewCenter().y, viewer.getViewCenter().z);
glm::vec3 up(viewer.getUpVector().x, viewer.getUpVector().y, viewer.getUpVector().z);
glm::mat4 view = lookAt(eye, look, up); //Calculate view matrix from paramters of m_viewer
glm::mat4 projection = perspective(45.0f, m_width / m_height, 0.1f, 500.0f);
_shaderProgram->addUniform("mvp");
for (ADrawable *drawable : _drawables)
{
drawable->draw(_shaderProgram, projection * view);
}
_shaderProgram->disable();
}
void MyGlWindow::AddDrawable(ADrawable *d)
{
_drawables.push_back(d);
}
void MyGlWindow::resize(int w, int h)
{
m_width = w;
m_height = h;
viewer.setAspectRatio(w / float(h));
}

View File

@ -0,0 +1,52 @@
#pragma once
#include <iostream>
#include "GL/glew.h"
#include <string>
#include <vector>
#include "IDrawable.h"
#include "ColorCube.h"
#include "Loader.h"
#include "ModelView.h"
#include "Viewer.h"
#include "CheckeredFloor.h"
#include "WireCube.h"
struct vertexAttr {
GLfloat posX, posY, posZ;
GLfloat r, g, b;
};
class MyGlWindow {
public:
MyGlWindow(int w, int h);
MyGlWindow();
~MyGlWindow();
void draw();
void setBgColor(float bgColor[3]);
float cubeRotation = .0f;
void AddDrawable(ADrawable *);
void resize(int w, int h);
Viewer viewer;
private:
ShaderProgram *_shaderProgram;
int m_width;
int m_height;
ColorCube _cube;
CheckeredFloor _floor;
float _bgColor[3];
GLuint _vaoHandle;
GLuint _iboHandle;
std::vector<ADrawable *> _drawables;
void setup();
void setupRectBuffer();
void setupCubeBuffer();
};

232
BaseGLProject/Source.cpp Normal file
View File

@ -0,0 +1,232 @@
#include <cstdio>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include "imgui/imgui.h"
#include "imgui/imgui_impl_glfw.h"
#include "imgui/imgui_impl_opengl3.h"
#include "MyGLWindow.h"
bool lbutton_down;
bool rbutton_down;
bool mbutton_down;
double m_lastMouseX;
double m_lastMouseY;
double cx, cy;
int g_width;
int g_height;
void window_size_callback(GLFWwindow* window, int width, int height)
{
g_width = width;
g_height = height;
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GLFW_TRUE);
}
static void cursor_pos_callback(GLFWwindow* window, double xpos, double ypos)
{
cx = xpos;
cy = ypos;
}
void mouse_button_callback(GLFWwindow* window, int button, int action, int mods)
{
if (action == GLFW_PRESS) {
double xpos, ypos;
glfwGetCursorPos(window, &xpos, &ypos);
m_lastMouseX = xpos;
m_lastMouseY = ypos;
}
if (button == GLFW_MOUSE_BUTTON_LEFT) {
if (GLFW_PRESS == action)
lbutton_down = true;
else if (GLFW_RELEASE == action)
lbutton_down = false;
}
else if (button == GLFW_MOUSE_BUTTON_RIGHT) {
if (GLFW_PRESS == action)
rbutton_down = true;
else if (GLFW_RELEASE == action)
rbutton_down = false;
}
else if (button == GLFW_MOUSE_BUTTON_MIDDLE) {
if (GLFW_PRESS == action)
mbutton_down = true;
else if (GLFW_RELEASE == action)
mbutton_down = false;
}
}
void mouseDragging(double width, double height, MyGlWindow &win)
{
ImGuiIO& io = ImGui::GetIO();
if (!io.WantCaptureMouse)
{
if (lbutton_down) {
float fractionChangeX = static_cast<float>(cx - m_lastMouseX) / static_cast<float>(width);
float fractionChangeY = static_cast<float>(m_lastMouseY - cy) / static_cast<float>(height);
win.viewer.rotate(fractionChangeX, fractionChangeY);
}
else if (mbutton_down) {
float fractionChangeX = static_cast<float>(cx - m_lastMouseX) / static_cast<float>(width);
float fractionChangeY = static_cast<float>(m_lastMouseY - cy) / static_cast<float>(height);
win.viewer.zoom(fractionChangeY);
}
else if (rbutton_down) {
float fractionChangeX = static_cast<float>(cx - m_lastMouseX) / static_cast<float>(width);
float fractionChangeY = static_cast<float>(m_lastMouseY - cy) / static_cast<float>(height);
win.viewer.translate(-fractionChangeX, -fractionChangeY, 1);
}
m_lastMouseX = cx;
m_lastMouseY = cy;
}
}
bool initGLFW()
{
if (!glfwInit())
{
// Windows error box
return false;
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
return true;
}
void initImgui(GLFWwindow **window)
{
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
const char* glsl_version = "#version 430";
ImGui_ImplGlfw_InitForOpenGL(*window, true);
ImGui_ImplOpenGL3_Init(glsl_version);
ImGui::StyleColorsDark();
//ImGui::StyleColorsClassic();
//ImGui::StyleColorsLight();
}
bool createWindow(GLFWwindow **window)
{
int width = 1080;
int height = 1080;
g_width = 1080;
g_height = 1080;
/* Create a windowed mode window and its OpenGL context */
(*window) = glfwCreateWindow(width, height, "OpenGL FrameWork", NULL, NULL);
if (!(*window))
{
// Windows error box
glfwTerminate();
return false;
}
initImgui(window);
glfwMakeContextCurrent((*window));
/* Make the window's context current */
glewExperimental = GL_TRUE;
GLenum err = glewInit();
if (err != GLEW_OK)
{
// Windows error box
//Problem: glewInit failed, something is seriously wrong.
return false;
}
glfwSetKeyCallback((*window), key_callback);
return true;
}
int loop(GLFWwindow *window)
{
std::printf("OpenGL %s, GLSL %s\n", glGetString(GL_VERSION), glGetString(GL_SHADING_LANGUAGE_VERSION));
int width;
int heigth;
glfwGetWindowSize(window, &width, &heigth);
MyGlWindow glWin(width, heigth);
while (!glfwWindowShouldClose(window))
{
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
if (ImGui::Begin("First Window"))
{
ImGui::SetWindowSize(ImVec2(350, 150));
ImGui::SetWindowPos(ImVec2(20, 20));
ImGui::Text("WannaQuit ?");
if (ImGui::Button("Yes"))
glfwSetWindowShouldClose(window, GLFW_TRUE);
static float rotation = .0f;
ImGui::SliderFloat("Volume", &rotation, 0.0f, 360.0f);
glWin.cubeRotation = rotation;
static float bgColor[3] = { .0f, .0f, .0f };
ImGui::ColorEdit3("Background", bgColor, 0);
glWin.setBgColor(bgColor);
ImGui::End();
}
glfwSwapBuffers(window);
glWin.draw();
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
glfwPollEvents();
mouseDragging(g_width, g_height, glWin);
glWin.resize(g_width, g_height);
}
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
glfwDestroyWindow(window);
glfwTerminate();
return 0;
}
// upload to padlet.com/mksung89/cameraControl2
int main()
{
GLFWwindow *win;
if (!initGLFW() || !createWindow(&win))
return 1;
glfwSetWindowSizeCallback(win, window_size_callback);
glfwSetMouseButtonCallback(win, mouse_button_callback);
glfwSetCursorPosCallback(win, cursor_pos_callback);
glfwSetKeyCallback(win, key_callback);
glfwSetWindowTitle(win, "Variables d'environnement pour le DLL :,(");
return loop(win);
}

205
BaseGLProject/Viewer.cpp Normal file
View File

@ -0,0 +1,205 @@
// File: Viewer.cpp
// Author: mankyu sung
#include <iostream>
#include "Viewer.h"
#include <glm/gtc/quaternion.hpp>
static float DEFAULT_TRANSLATE_SPEED = 0.5;
static float DEFAULT_ZOOM_FRACTION = 2.5;
static float DEFAULT_ROTATE_SPEED = 2.0;
using namespace std;
Viewer::Viewer(
const glm::vec3 &viewPoint, const glm::vec3 &viewCenter, const glm::vec3 &upVector,
float fieldOfView, float aspectRatio
) :
m_viewPoint(viewPoint),
m_viewCenter(viewCenter),
m_upVector(upVector),
m_fieldOfView(fieldOfView),
m_aspectRatio(aspectRatio),
m_translateSpeed(DEFAULT_TRANSLATE_SPEED),
m_zoomFraction(DEFAULT_ZOOM_FRACTION),
m_rotateSpeed(DEFAULT_ROTATE_SPEED)
{
m_upVector = glm::normalize(m_upVector);
getFrustrumInfo();
}
void Viewer::translate(float changeHoriz, float changeVert, bool inImagePlane) {
glm::vec3 translateVec;
if (inImagePlane) {
translateVec = (m_imagePlaneHorizDir * (m_displayWidth * changeHoriz)) + (m_imagePlaneVertDir * (changeVert * m_displayHeight));
}
else {
translateVec = (m_viewCenter - m_viewPoint) * changeVert;
}
translateVec *= m_translateSpeed;
m_viewPoint += translateVec;
m_viewCenter += translateVec;
}
void Viewer::zoom(float changeVert) {
float scaleFactor = powf(2.0, -changeVert * m_zoomFraction);
m_viewPoint = m_viewCenter + (m_viewPoint - m_viewCenter) * scaleFactor;
getFrustrumInfo();
}
const float pi = glm::pi<float>();
glm::quat setFromAxisAngle(glm::vec3 & axis, float angle) {
float cosAng = cosf(angle / 2.0f);
float sinAng = sinf(angle / 2.0f);
float norm = sqrt(axis.x * axis.x + axis.y * axis.y + axis.z * axis.z);
glm::quat res;
res.x = axis.x / norm;
res.y = axis.y / norm;
res.z = axis.z / norm;
res.w = cosAng; //w
res.x *= sinAng; //x
res.y *= sinAng; //y
res.z *= sinAng; //z
return res;
}
void makeOrthogonalTo(glm::vec3 & vec1, glm::vec3 & vec2) {
float length = glm::length(vec2);
if (length == 0) {
std::cout << "Warning: called MathVec3D::makeOrthogonalTo with zero vector as the argument. Doing nothing." << std::endl;
}
else {
float scale = (vec1.x * vec2.x + vec1.y * vec2.y + vec1.z * vec2.z) / (length * length);
vec1.x -= scale * vec2.x;
vec1.y -= scale * vec2.y;
vec1.z -= scale * vec2.z;
}
}
void Viewer::rotate(float changeHoriz, float changeVert) {
float horizRotAngle = m_rotateSpeed * changeVert;
float vertRotAngle = -m_rotateSpeed * changeHoriz;
glm::quat horizRot;
horizRot = setFromAxisAngle(m_imagePlaneHorizDir, horizRotAngle);
glm::quat vertRot;
vertRot = setFromAxisAngle(m_imagePlaneVertDir, vertRotAngle);
glm::quat totalRot = horizRot * vertRot;
glm::vec3 viewVec = m_viewPoint - m_viewCenter;
viewVec = totalRot * viewVec;
m_viewPoint = m_viewCenter + viewVec;
getFrustrumInfo();
}
void Viewer::centerAt(const glm::vec3 &pos) {
m_viewPoint += (pos - m_viewCenter);
m_viewCenter = pos;
getFrustrumInfo();
}
void Viewer::lookFrom(const glm::vec3 &pos) {
m_viewPoint = pos;
getFrustrumInfo();
}
glm::vec3 Viewer::getViewPoint() const {
return( m_viewPoint );
}
glm::vec3 Viewer::getViewCenter() const {
return( m_viewCenter );
}
glm::vec3 Viewer::getUpVector() const {
return( m_upVector );
}
float Viewer::getFieldOfView() const {
return( m_fieldOfView );
}
float Viewer::getAspectRatio() const {
return( m_aspectRatio );
}
glm::vec3 Viewer::getViewDir() const {
return( m_viewDir );
}
glm::vec3 Viewer::getImagePlaneHorizDir() const {
return( m_imagePlaneHorizDir );
}
glm::vec3 Viewer::getImagePlaneVertDir() const {
return( m_imagePlaneVertDir );
}
void Viewer::setAspectRatio(float aspectRatio) {
if( m_aspectRatio != aspectRatio ) {
m_aspectRatio = aspectRatio;
getFrustrumInfo();
}
}
void Viewer::setFieldOfView(float fieldOfView) {
if( m_fieldOfView != fieldOfView ) {
m_fieldOfView = fieldOfView;
getFrustrumInfo();
}
}
void Viewer::setTranslateSpeed(float translateSpeed) {
m_translateSpeed = translateSpeed;
}
void Viewer::setZoomFraction(float zoomFraction) {
m_zoomFraction = zoomFraction;
}
void Viewer::setRotateSpeed(float rotateSpeed) {
m_rotateSpeed = rotateSpeed;
}
void Viewer::getFrustrumInfo() {
// Get the viewing direction
m_viewDir = m_viewCenter - m_viewPoint;
m_viewDir = glm::normalize(m_viewDir);
// Get the vertical image-plane direction (the projection of the up vector into the view plane)
m_imagePlaneVertDir = m_upVector;
makeOrthogonalTo(m_imagePlaneVertDir, m_viewDir);
m_imagePlaneVertDir = glm::normalize(m_imagePlaneVertDir);
// Get the horizontal image-plane direction
m_imagePlaneHorizDir = glm::cross(m_viewDir, m_imagePlaneVertDir);
m_imagePlaneHorizDir = glm::normalize(m_imagePlaneHorizDir);
// Get the view plane width and height at the view center.
m_displayHeight = 2.0 * glm::length(m_viewCenter-m_viewPoint) * tan(0.5*m_fieldOfView);
m_displayWidth = m_displayHeight * m_aspectRatio;
}

170
BaseGLProject/Viewer.h Normal file
View File

@ -0,0 +1,170 @@
// File: Viewer.h
#pragma once
class Viewer;
/**
* \brief A class to control the viewing parameters.
*
* This class maintains and provides access to parameters of a simple viewing model,
* and it supports basic viewing operations like translation, rotation, and zooming.
* The view parameters are:
* - The view point (where the camera is located)
* - The view center (a point that is being looked at; the closer it is to the
* view point, the greater the degree of zooming)
* - The up vector (defines the global vertical axis; typically this is the y axis)
* - The field of view (defined as the vertical angular span of the viewing
* frustrum in radians
* - The aspect ratio (the ratio width/height for the resultant image)
*/
#include <glm/glm.hpp>
class Viewer {
public:
/** Constructor */
Viewer(
const glm::vec3 &viewPoint, const glm::vec3 &viewCenter, const glm::vec3 &upVector,
float fieldOfView, float aspectRatio
);
/** The worldspace location of the center of focus */
glm::vec3 getViewPoint() const;
/** This corresponds to the worldspace location of OpenGL's "look at" point */
glm::vec3 getViewCenter() const;
/** The up vector in worldspace coordinates */
glm::vec3 getUpVector() const;
float getFieldOfView() const;
float getAspectRatio() const;
/** The (normalized) worldspace vector from the viewpoint to the view center */
glm::vec3 getViewDir() const;
/** The worldspace direction (i.e., normalized vector) of the horizontal image axis */
glm::vec3 getImagePlaneHorizDir() const;
/** The worldspace direction (i.e., normalized vector) of the vertical image axis */
glm::vec3 getImagePlaneVertDir() const;
/**
* Translate
*
* These methods alter the view based on mouse movement. The arguments
* changeHoriz and changeVert specify, respectively, the amount
* the mouse has moved horizontally/vertically as a fraction of the
* total screen width/height.
*
* translate: The final argument determines whether the translation is
* parallel to the view plane; if not, then only the vertical mouse
* movement (second argument) is used. The actual amount of
* translation is determined by the distance between the view center
* and the view point.
*
*/
void translate(float changeHoriz, float changeVert, bool parallelToViewPlane);
/**
* Zoom
*
* These methods alter the view based on mouse movement. The arguments
* changeHoriz and changeVert specify, respectively, the amount
* the mouse has moved horizontally/vertically as a fraction of the
* total screen width/height.
*
* zoom: Zoom in or out by changing the distance between the view
* center and the viewpoint; the view center is held fixed. The
* distance is changed by a fraction 2.0 ^ (m_zoomFraction*changeVert)
* of the current distance; m_zoomFraction can be altered to adjust
* zoom speed.
*
*/
void zoom(float changeVert);
/**
* Rotate
*
* These methods alter the view based on mouse movement. The arguments
* changeHoriz and changeVert specify, respectively, the amount
* the mouse has moved horizontally/vertically as a fraction of the
* total screen width/height.
*
*
* rotate: Rotate about the view plane axes; the first argument is for
* rotation about the vertical view axis and the second is for
* rotation about the horizontal view axis. The amount of rotation
* is controlled by m_rotateSpeed.
*/
void rotate(float changeHoriz, float changeVert);
/**
* Center at
*
* These methods alter the view based on mouse movement. The arguments
* changeHoriz and changeVert specify, respectively, the amount
* the mouse has moved horizontally/vertically as a fraction of the
* total screen width/height.
*
* centerAt: Centers the view at the given location without changing the
* global orientation or scaling.
*/
void centerAt(const glm::vec3 &pos);
/**
* Look From
*
*/
void lookFrom(const glm::vec3 &pos);
/** Set the field of view*/
void setFieldOfView(float fieldOfView);
/** Set up the aspect ratio*/
void setAspectRatio(float aspectRatio);
/** Set up the translate speed */
void setTranslateSpeed(float translateSpeed);
/** Set up the zoom factor*/
void setZoomFraction(float zoomFraction);
/** Set up the roation speed */
void setRotateSpeed(float rotateSpeed);
private:
glm::vec3 m_viewPoint;
glm::vec3 m_viewCenter;
glm::vec3 m_upVector;
float m_fieldOfView;
float m_aspectRatio;
float m_translateSpeed;
float m_zoomFraction;
float m_rotateSpeed;
glm::vec3 m_viewDir;
glm::vec3 m_imagePlaneHorizDir;
glm::vec3 m_imagePlaneVertDir;
/**
* These member variables hold the width and height of the plane that
* a) is parallel to the clipping planes, b) passes through the
* the view center, and c) is clipped by the frustrum boundaries.
* This is useful for converting mouse input into view transformations
* of an appropriate magnitude.
*/
float m_displayWidth;
float m_displayHeight;
/** These are used for tracking */
float m_lastDesired[3];
/**
* The following values contain the geometry of our viewing volume: the
* field of view, the aspect ratio, the height and width of view plane
* containing the center of projection, the world-coordinate directions
* of the image x and y axes, and the dimensions of the viewport.
*/
void getFrustrumInfo();
};

View File

@ -0,0 +1,67 @@
#include "WireCube.h"
void WireCube::setup()
{
_cube_vertices =
{ { -1.0, -1.0, 1.0}, { 1.0, -1.0, 1.0}, { 1.0, 1.0, 1.0},
{ -1.0, 1.0, 1.0}, { 1.0, 1.0, 1.0}, { -1.0, -1.0, 1.0},
{ -1.0, -1.0, -1.0}, { 1.0, -1.0, -1.0}, { 1.0, 1.0, -1.0},
{ -1.0, 1.0, -1.0}, { 1.0, 1.0, -1.0}, { -1.0, -1.0, -1.0},
{ -1.0, 1.0, -1.0}, { 1.0, 1.0, -1.0}, { 1.0, 1.0, 1.0},
{ -1.0, 1.0, 1.0}, { -1.0, 1.0, -1.0}, { 1.0, 1.0, -1.0},
{ -1.0, -1.0, -1.0}, { 1.0, -1.0, -1.0}, { 1.0, -1.0, 1.0},
{ -1.0, -1.0, 1.0}, { -1.0, -1.0, -1.0}, { 1.0, -1.0, -1.0},
{ -1.0, -1.0, -1.0}, { -1.0, -1.0, 1.0}, { -1.0, 1.0, 1.0},
{ -1.0, 1.0, -1.0}, { -1.0, -1.0, -1.0}, { -1.0, -1.0, 1.0},
{ 1.0, -1.0, -1.0}, { 1.0, -1.0, 1.0}, { 1.0, 1.0, 1.0},
{ 1.0, 1.0, -1.0}, { 1.0, -1.0, -1.0}, { 1.0, -1.0, 1.0}};
glGenVertexArrays(1, &_vaoHandle);
glBindVertexArray(_vaoHandle);
glGenBuffers(1, &_vbo_vertices);
glBindBuffer(GL_ARRAY_BUFFER, _vbo_vertices);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * _cube_vertices.size() * 3, _cube_vertices.data(), GL_STATIC_DRAW);
glVertexAttribPointer(
0, //attr number = 0
3,
GL_FLOAT,
GL_FALSE,
0,
(void*)0);
glEnableVertexAttribArray(0); //attr number = 0
}
WireCube::WireCube()
{
setup();
}
void WireCube::draw(ShaderProgram * shader, glm::mat4x4 pv)
{
_model.glPushMatrix();
effectTransformations();
glm::mat4 mvpMatrix = pv * _model.getMatrix();
glUniformMatrix4fv(shader->uniform("mvp"), 1, GL_FALSE, glm::value_ptr(mvpMatrix));
glLineWidth(2);
glBindVertexArray(_vaoHandle);
for (int i = 0; i < _cube_vertices.size() * 3; i += 3)
glDrawArrays(GL_LINE_LOOP, i, 3);
_model.glPopMatrix();
}
DrawableType WireCube::getType()
{
return DrawableType::WIRE_CUBE;
}
WireCube::~WireCube()
{
}

27
BaseGLProject/WireCube.h Normal file
View File

@ -0,0 +1,27 @@
#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <glm/vec4.hpp>
#include "ADrawable.h"
#pragma once
class WireCube : public ADrawable
{
private:
GLuint _vaoHandle;
GLuint _vbo_vertices, _vbo_colors;
std::vector<glm::vec3> _cube_vertices;
void setup();
public:
WireCube();
void draw(ShaderProgram *shader, glm::mat4x4 pv) override;
DrawableType getType() override;
~WireCube();
};

50
BaseGLProject/imgui.ini Normal file
View File

@ -0,0 +1,50 @@
[Window][Debug##Default]
Pos=60,60
Size=400,400
Collapsed=0
[Window][ImGui Demo]
Pos=1347,13
Size=550,680
Collapsed=0
[Window][Example: Console]
Pos=60,60
Size=520,600
Collapsed=0
[Window][Example: Long text display]
Pos=60,60
Size=520,600
Collapsed=0
[Window][Same title as another window##1]
Pos=97,118
Size=449,61
Collapsed=0
[Window][Same title as another window##2]
Pos=100,200
Size=449,61
Collapsed=0
[Window][###AnimatedTitle]
Pos=100,300
Size=246,48
Collapsed=0
[Window][Example: Custom rendering]
Pos=227,95
Size=350,560
Collapsed=0
[Window][Example: Property editor]
Pos=60,60
Size=430,450
Collapsed=0
[Window][First Window]
Pos=20,20
Size=350,150
Collapsed=0

View File

@ -0,0 +1,74 @@
//-----------------------------------------------------------------------------
// COMPILE-TIME OPTIONS FOR DEAR IMGUI
// Runtime options (clipboard callbacks, enabling various features, etc.) can generally be set via the ImGuiIO structure.
// You can use ImGui::SetAllocatorFunctions() before calling ImGui::CreateContext() to rewire memory allocation functions.
//-----------------------------------------------------------------------------
// A) You may edit imconfig.h (and not overwrite it when updating imgui, or maintain a patch/branch with your modifications to imconfig.h)
// B) or add configuration directives in your own file and compile with #define IMGUI_USER_CONFIG "myfilename.h"
// If you do so you need to make sure that configuration settings are defined consistently _everywhere_ dear imgui is used, which include
// the imgui*.cpp files but also _any_ of your code that uses imgui. This is because some compile-time options have an affect on data structures.
// Defining those options in imconfig.h will ensure every compilation unit gets to see the same data structure layouts.
// Call IMGUI_CHECKVERSION() from your .cpp files to verify that the data structures your files are using are matching the ones imgui.cpp is using.
//-----------------------------------------------------------------------------
#pragma once
//---- Define assertion handler. Defaults to calling assert().
//#define IM_ASSERT(_EXPR) MyAssert(_EXPR)
//#define IM_ASSERT(_EXPR) ((void)(_EXPR)) // Disable asserts
//---- Define attributes of all API symbols declarations, e.g. for DLL under Windows.
//#define IMGUI_API __declspec( dllexport )
//#define IMGUI_API __declspec( dllimport )
//---- Don't define obsolete functions/enums names. Consider enabling from time to time after updating to avoid using soon-to-be obsolete function/names.
//#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS
//---- Don't implement demo windows functionality (ShowDemoWindow()/ShowStyleEditor()/ShowUserGuide() methods will be empty)
//---- It is very strongly recommended to NOT disable the demo windows during development. Please read the comments in imgui_demo.cpp.
//#define IMGUI_DISABLE_DEMO_WINDOWS
//---- Don't implement some functions to reduce linkage requirements.
//#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // [Win32] Don't implement default clipboard handler. Won't use and link with OpenClipboard/GetClipboardData/CloseClipboard etc.
//#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] Don't implement default IME handler. Won't use and link with ImmGetContext/ImmSetCompositionWindow.
//#define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use and link with any Win32 function.
//#define IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS // Don't implement ImFormatString/ImFormatStringV so you can implement them yourself if you don't want to link with vsnprintf.
//#define IMGUI_DISABLE_MATH_FUNCTIONS // Don't implement ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 wrapper so you can implement them yourself. Declare your prototypes in imconfig.h.
//#define IMGUI_DISABLE_DEFAULT_ALLOCATORS // Don't implement default allocators calling malloc()/free() to avoid linking with them. You will need to call ImGui::SetAllocatorFunctions().
//---- Include imgui_user.h at the end of imgui.h as a convenience
//#define IMGUI_INCLUDE_IMGUI_USER_H
//---- Pack colors to BGRA8 instead of RGBA8 (to avoid converting from one to another)
//#define IMGUI_USE_BGRA_PACKED_COLOR
//---- Avoid multiple STB libraries implementations, or redefine path/filenames to prioritize another version
// By default the embedded implementations are declared static and not available outside of imgui cpp files.
//#define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h"
//#define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h"
//#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION
//#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION
//---- Define constructor and implicit cast operators to convert back<>forth between your math types and ImVec2/ImVec4.
// This will be inlined as part of ImVec2 and ImVec4 class declarations.
/*
#define IM_VEC2_CLASS_EXTRA \
ImVec2(const MyVec2& f) { x = f.x; y = f.y; } \
operator MyVec2() const { return MyVec2(x,y); }
#define IM_VEC4_CLASS_EXTRA \
ImVec4(const MyVec4& f) { x = f.x; y = f.y; z = f.z; w = f.w; } \
operator MyVec4() const { return MyVec4(x,y,z,w); }
*/
//---- Use 32-bit vertex indices (default is 16-bit) to allow meshes with more than 64K vertices. Render function needs to support it.
//#define ImDrawIdx unsigned int
//---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files.
/*
namespace ImGui
{
void MyFunction(const char* name, const MyMatrix44& v);
}
*/
#define IMGUI_IMPL_OPENGL_LOADER_GLEW

File diff suppressed because it is too large Load Diff

1993
BaseGLProject/imgui/imgui.h Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,298 @@
// dear imgui: Platform Binding for GLFW
// This needs to be used along with a Renderer (e.g. OpenGL3, Vulkan..)
// (Info: GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.)
// Implemented features:
// [X] Platform: Clipboard support.
// [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
// [x] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. FIXME: 3 cursors types are missing from GLFW.
// [X] Platform: Keyboard arrays indexed using GLFW_KEY_* codes, e.g. ImGui::IsKeyPressed(GLFW_KEY_SPACE).
// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp.
// https://github.com/ocornut/imgui
// CHANGELOG
// (minor and older changes stripped away, please see git history for details)
// 2018-08-01: Inputs: Workaround for Emscripten which doesn't seem to handle focus related calls.
// 2018-06-29: Inputs: Added support for the ImGuiMouseCursor_Hand cursor.
// 2018-06-08: Misc: Extracted imgui_impl_glfw.cpp/.h away from the old combined GLFW+OpenGL/Vulkan examples.
// 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors flag + honor ImGuiConfigFlags_NoMouseCursorChange flag.
// 2018-02-20: Inputs: Added support for mouse cursors (ImGui::GetMouseCursor() value, passed to glfwSetCursor()).
// 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
// 2018-02-06: Inputs: Added mapping for ImGuiKey_Space.
// 2018-01-25: Inputs: Added gamepad support if ImGuiConfigFlags_NavEnableGamepad is set.
// 2018-01-25: Inputs: Honoring the io.WantSetMousePos by repositioning the mouse (when using navigation and ImGuiConfigFlags_NavMoveMouse is set).
// 2018-01-20: Inputs: Added Horizontal Mouse Wheel support.
// 2018-01-18: Inputs: Added mapping for ImGuiKey_Insert.
// 2017-08-25: Inputs: MousePos set to -FLT_MAX,-FLT_MAX when mouse is unavailable/missing (instead of -1,-1).
// 2016-10-15: Misc: Added a void* user_data parameter to Clipboard function handlers.
#include "imgui.h"
#include "imgui_impl_glfw.h"
// GLFW
#include <GLFW/glfw3.h>
#ifdef _WIN32
#undef APIENTRY
#define GLFW_EXPOSE_NATIVE_WIN32
#include <GLFW/glfw3native.h> // for glfwGetWin32Window
#endif
#define GLFW_HAS_WINDOW_TOPMOST (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3200) // 3.2+ GLFW_FLOATING
#define GLFW_HAS_WINDOW_HOVERED (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3300) // 3.3+ GLFW_HOVERED
#define GLFW_HAS_WINDOW_ALPHA (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3300) // 3.3+ glfwSetWindowOpacity
#define GLFW_HAS_PER_MONITOR_DPI (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3300) // 3.3+ glfwGetMonitorContentScale
#define GLFW_HAS_VULKAN (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3200) // 3.2+ glfwCreateWindowSurface
// Data
enum GlfwClientApi
{
GlfwClientApi_Unknown,
GlfwClientApi_OpenGL,
GlfwClientApi_Vulkan
};
static GLFWwindow* g_Window = NULL;
static GlfwClientApi g_ClientApi = GlfwClientApi_Unknown;
static double g_Time = 0.0;
static bool g_MouseJustPressed[5] = { false, false, false, false, false };
static GLFWcursor* g_MouseCursors[ImGuiMouseCursor_COUNT] = { 0 };
static const char* ImGui_ImplGlfw_GetClipboardText(void* user_data)
{
return glfwGetClipboardString((GLFWwindow*)user_data);
}
static void ImGui_ImplGlfw_SetClipboardText(void* user_data, const char* text)
{
glfwSetClipboardString((GLFWwindow*)user_data, text);
}
void ImGui_ImplGlfw_MouseButtonCallback(GLFWwindow*, int button, int action, int /*mods*/)
{
if (action == GLFW_PRESS && button >= 0 && button < IM_ARRAYSIZE(g_MouseJustPressed))
g_MouseJustPressed[button] = true;
}
void ImGui_ImplGlfw_ScrollCallback(GLFWwindow*, double xoffset, double yoffset)
{
ImGuiIO& io = ImGui::GetIO();
io.MouseWheelH += (float)xoffset;
io.MouseWheel += (float)yoffset;
}
void ImGui_ImplGlfw_KeyCallback(GLFWwindow*, int key, int, int action, int mods)
{
ImGuiIO& io = ImGui::GetIO();
if (action == GLFW_PRESS)
io.KeysDown[key] = true;
if (action == GLFW_RELEASE)
io.KeysDown[key] = false;
(void)mods; // Modifiers are not reliable across systems
io.KeyCtrl = io.KeysDown[GLFW_KEY_LEFT_CONTROL] || io.KeysDown[GLFW_KEY_RIGHT_CONTROL];
io.KeyShift = io.KeysDown[GLFW_KEY_LEFT_SHIFT] || io.KeysDown[GLFW_KEY_RIGHT_SHIFT];
io.KeyAlt = io.KeysDown[GLFW_KEY_LEFT_ALT] || io.KeysDown[GLFW_KEY_RIGHT_ALT];
io.KeySuper = io.KeysDown[GLFW_KEY_LEFT_SUPER] || io.KeysDown[GLFW_KEY_RIGHT_SUPER];
}
void ImGui_ImplGlfw_CharCallback(GLFWwindow*, unsigned int c)
{
ImGuiIO& io = ImGui::GetIO();
if (c > 0 && c < 0x10000)
io.AddInputCharacter((unsigned short)c);
}
void ImGui_ImplGlfw_InstallCallbacks(GLFWwindow* window)
{
glfwSetMouseButtonCallback(window, ImGui_ImplGlfw_MouseButtonCallback);
glfwSetScrollCallback(window, ImGui_ImplGlfw_ScrollCallback);
glfwSetKeyCallback(window, ImGui_ImplGlfw_KeyCallback);
glfwSetCharCallback(window, ImGui_ImplGlfw_CharCallback);
}
static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, GlfwClientApi client_api)
{
g_Window = window;
g_Time = 0.0;
// Setup back-end capabilities flags
ImGuiIO& io = ImGui::GetIO();
io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional)
io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used)
// Keyboard mapping. ImGui will use those indices to peek into the io.KeysDown[] array.
io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB;
io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT;
io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT;
io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP;
io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN;
io.KeyMap[ImGuiKey_PageUp] = GLFW_KEY_PAGE_UP;
io.KeyMap[ImGuiKey_PageDown] = GLFW_KEY_PAGE_DOWN;
io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;
io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;
io.KeyMap[ImGuiKey_Insert] = GLFW_KEY_INSERT;
io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;
io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;
io.KeyMap[ImGuiKey_Space] = GLFW_KEY_SPACE;
io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;
io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE;
io.KeyMap[ImGuiKey_A] = GLFW_KEY_A;
io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;
io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;
io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;
io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;
io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;
io.SetClipboardTextFn = ImGui_ImplGlfw_SetClipboardText;
io.GetClipboardTextFn = ImGui_ImplGlfw_GetClipboardText;
io.ClipboardUserData = g_Window;
#if defined(_WIN32)
io.ImeWindowHandle = (void*)glfwGetWin32Window(g_Window);
#endif
g_MouseCursors[ImGuiMouseCursor_Arrow] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
g_MouseCursors[ImGuiMouseCursor_TextInput] = glfwCreateStandardCursor(GLFW_IBEAM_CURSOR);
g_MouseCursors[ImGuiMouseCursor_ResizeAll] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR); // FIXME: GLFW doesn't have this.
g_MouseCursors[ImGuiMouseCursor_ResizeNS] = glfwCreateStandardCursor(GLFW_VRESIZE_CURSOR);
g_MouseCursors[ImGuiMouseCursor_ResizeEW] = glfwCreateStandardCursor(GLFW_HRESIZE_CURSOR);
g_MouseCursors[ImGuiMouseCursor_ResizeNESW] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR); // FIXME: GLFW doesn't have this.
g_MouseCursors[ImGuiMouseCursor_ResizeNWSE] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR); // FIXME: GLFW doesn't have this.
g_MouseCursors[ImGuiMouseCursor_Hand] = glfwCreateStandardCursor(GLFW_HAND_CURSOR);
if (install_callbacks)
ImGui_ImplGlfw_InstallCallbacks(window);
g_ClientApi = client_api;
return true;
}
bool ImGui_ImplGlfw_InitForOpenGL(GLFWwindow* window, bool install_callbacks)
{
return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_OpenGL);
}
bool ImGui_ImplGlfw_InitForVulkan(GLFWwindow* window, bool install_callbacks)
{
return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_Vulkan);
}
void ImGui_ImplGlfw_Shutdown()
{
for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++)
{
glfwDestroyCursor(g_MouseCursors[cursor_n]);
g_MouseCursors[cursor_n] = NULL;
}
g_ClientApi = GlfwClientApi_Unknown;
}
static void ImGui_ImplGlfw_UpdateMousePosAndButtons()
{
// Update buttons
ImGuiIO& io = ImGui::GetIO();
for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
{
// If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame.
io.MouseDown[i] = g_MouseJustPressed[i] || glfwGetMouseButton(g_Window, i) != 0;
g_MouseJustPressed[i] = false;
}
// Update mouse position
const ImVec2 mouse_pos_backup = io.MousePos;
io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
#ifdef __EMSCRIPTEN__
const bool focused = true; // Emscripten
#else
const bool focused = glfwGetWindowAttrib(g_Window, GLFW_FOCUSED) != 0;
#endif
if (focused)
{
if (io.WantSetMousePos)
{
glfwSetCursorPos(g_Window, (double)mouse_pos_backup.x, (double)mouse_pos_backup.y);
}
else
{
double mouse_x, mouse_y;
glfwGetCursorPos(g_Window, &mouse_x, &mouse_y);
io.MousePos = ImVec2((float)mouse_x, (float)mouse_y);
}
}
}
static void ImGui_ImplGlfw_UpdateMouseCursor()
{
ImGuiIO& io = ImGui::GetIO();
if ((io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) || glfwGetInputMode(g_Window, GLFW_CURSOR) == GLFW_CURSOR_DISABLED)
return;
ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
if (imgui_cursor == ImGuiMouseCursor_None || io.MouseDrawCursor)
{
// Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
glfwSetInputMode(g_Window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
}
else
{
// Show OS mouse cursor
// FIXME-PLATFORM: Unfocused windows seems to fail changing the mouse cursor with GLFW 3.2, but 3.3 works here.
glfwSetCursor(g_Window, g_MouseCursors[imgui_cursor] ? g_MouseCursors[imgui_cursor] : g_MouseCursors[ImGuiMouseCursor_Arrow]);
glfwSetInputMode(g_Window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
}
}
void ImGui_ImplGlfw_NewFrame()
{
ImGuiIO& io = ImGui::GetIO();
IM_ASSERT(io.Fonts->IsBuilt()); // Font atlas needs to be built, call renderer _NewFrame() function e.g. ImGui_ImplOpenGL3_NewFrame()
// Setup display size
int w, h;
int display_w, display_h;
glfwGetWindowSize(g_Window, &w, &h);
glfwGetFramebufferSize(g_Window, &display_w, &display_h);
io.DisplaySize = ImVec2((float)w, (float)h);
io.DisplayFramebufferScale = ImVec2(w > 0 ? ((float)display_w / w) : 0, h > 0 ? ((float)display_h / h) : 0);
// Setup time step
double current_time = glfwGetTime();
io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f/60.0f);
g_Time = current_time;
ImGui_ImplGlfw_UpdateMousePosAndButtons();
ImGui_ImplGlfw_UpdateMouseCursor();
// Gamepad navigation mapping [BETA]
memset(io.NavInputs, 0, sizeof(io.NavInputs));
if (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad)
{
// Update gamepad inputs
#define MAP_BUTTON(NAV_NO, BUTTON_NO) { if (buttons_count > BUTTON_NO && buttons[BUTTON_NO] == GLFW_PRESS) io.NavInputs[NAV_NO] = 1.0f; }
#define MAP_ANALOG(NAV_NO, AXIS_NO, V0, V1) { float v = (axes_count > AXIS_NO) ? axes[AXIS_NO] : V0; v = (v - V0) / (V1 - V0); if (v > 1.0f) v = 1.0f; if (io.NavInputs[NAV_NO] < v) io.NavInputs[NAV_NO] = v; }
int axes_count = 0, buttons_count = 0;
const float* axes = glfwGetJoystickAxes(GLFW_JOYSTICK_1, &axes_count);
const unsigned char* buttons = glfwGetJoystickButtons(GLFW_JOYSTICK_1, &buttons_count);
MAP_BUTTON(ImGuiNavInput_Activate, 0); // Cross / A
MAP_BUTTON(ImGuiNavInput_Cancel, 1); // Circle / B
MAP_BUTTON(ImGuiNavInput_Menu, 2); // Square / X
MAP_BUTTON(ImGuiNavInput_Input, 3); // Triangle / Y
MAP_BUTTON(ImGuiNavInput_DpadLeft, 13); // D-Pad Left
MAP_BUTTON(ImGuiNavInput_DpadRight, 11); // D-Pad Right
MAP_BUTTON(ImGuiNavInput_DpadUp, 10); // D-Pad Up
MAP_BUTTON(ImGuiNavInput_DpadDown, 12); // D-Pad Down
MAP_BUTTON(ImGuiNavInput_FocusPrev, 4); // L1 / LB
MAP_BUTTON(ImGuiNavInput_FocusNext, 5); // R1 / RB
MAP_BUTTON(ImGuiNavInput_TweakSlow, 4); // L1 / LB
MAP_BUTTON(ImGuiNavInput_TweakFast, 5); // R1 / RB
MAP_ANALOG(ImGuiNavInput_LStickLeft, 0, -0.3f, -0.9f);
MAP_ANALOG(ImGuiNavInput_LStickRight,0, +0.3f, +0.9f);
MAP_ANALOG(ImGuiNavInput_LStickUp, 1, +0.3f, +0.9f);
MAP_ANALOG(ImGuiNavInput_LStickDown, 1, -0.3f, -0.9f);
#undef MAP_BUTTON
#undef MAP_ANALOG
if (axes_count > 0 && buttons_count > 0)
io.BackendFlags |= ImGuiBackendFlags_HasGamepad;
else
io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad;
}
}

View File

@ -0,0 +1,34 @@
// dear imgui: Platform Binding for GLFW
// This needs to be used along with a Renderer (e.g. OpenGL3, Vulkan..)
// (Info: GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.)
// Implemented features:
// [X] Platform: Clipboard support.
// [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
// [x] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. FIXME: 3 cursors types are missing from GLFW.
// [X] Platform: Keyboard arrays indexed using GLFW_KEY_* codes, e.g. ImGui::IsKeyPressed(GLFW_KEY_SPACE).
// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp.
// https://github.com/ocornut/imgui
// About GLSL version:
// The 'glsl_version' initialization parameter defaults to "#version 150" if NULL.
// Only override if your GL version doesn't handle this GLSL version. Keep NULL if unsure!
#pragma once
struct GLFWwindow;
IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForOpenGL(GLFWwindow* window, bool install_callbacks);
IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForVulkan(GLFWwindow* window, bool install_callbacks);
IMGUI_IMPL_API void ImGui_ImplGlfw_Shutdown();
IMGUI_IMPL_API void ImGui_ImplGlfw_NewFrame();
// GLFW callbacks (installed by default if you enable 'install_callbacks' during initialization)
// Provided here if you want to chain callbacks.
// You can also handle inputs yourself and use those as a reference.
IMGUI_IMPL_API void ImGui_ImplGlfw_MouseButtonCallback(GLFWwindow* window, int button, int action, int mods);
IMGUI_IMPL_API void ImGui_ImplGlfw_ScrollCallback(GLFWwindow* window, double xoffset, double yoffset);
IMGUI_IMPL_API void ImGui_ImplGlfw_KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods);
IMGUI_IMPL_API void ImGui_ImplGlfw_CharCallback(GLFWwindow* window, unsigned int c);

View File

@ -0,0 +1,541 @@
// dear imgui: Renderer for OpenGL3 / OpenGL ES2 / OpenGL ES3 (modern OpenGL with shaders / programmatic pipeline)
// This needs to be used along with a Platform Binding (e.g. GLFW, SDL, Win32, custom..)
// (Note: We are using GL3W as a helper library to access OpenGL functions since there is no standard header to access modern OpenGL functions easily. Alternatives are GLEW, Glad, etc..)
// Implemented features:
// [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID in imgui.cpp.
// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp.
// https://github.com/ocornut/imgui
// CHANGELOG
// (minor and older changes stripped away, please see git history for details)
// 2018-08-29: OpenGL: Added support for more OpenGL loaders: glew and glad, with comments indicative that any loader can be used.
// 2018-08-09: OpenGL: Default to OpenGL ES 3 on iOS and Android. GLSL version default to "#version 300 ES".
// 2018-07-30: OpenGL: Support for GLSL 300 ES and 410 core. Fixes for Emscripten compilation.
// 2018-07-10: OpenGL: Support for more GLSL versions (based on the GLSL version string). Added error output when shaders fail to compile/link.
// 2018-06-08: Misc: Extracted imgui_impl_opengl3.cpp/.h away from the old combined GLFW/SDL+OpenGL3 examples.
// 2018-06-08: OpenGL: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
// 2018-05-25: OpenGL: Removed unnecessary backup/restore of GL_ELEMENT_ARRAY_BUFFER_BINDING since this is part of the VAO state.
// 2018-05-14: OpenGL: Making the call to glBindSampler() optional so 3.2 context won't fail if the function is a NULL pointer.
// 2018-03-06: OpenGL: Added const char* glsl_version parameter to ImGui_ImplOpenGL3_Init() so user can override the GLSL version e.g. "#version 150".
// 2018-02-23: OpenGL: Create the VAO in the render function so the setup can more easily be used with multiple shared GL context.
// 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplSdlGL3_RenderDrawData() in the .h file so you can call it yourself.
// 2018-01-07: OpenGL: Changed GLSL shader version from 330 to 150.
// 2017-09-01: OpenGL: Save and restore current bound sampler. Save and restore current polygon mode.
// 2017-05-01: OpenGL: Fixed save and restore of current blend func state.
// 2017-05-01: OpenGL: Fixed save and restore of current GL_ACTIVE_TEXTURE.
// 2016-09-05: OpenGL: Fixed save and restore of current scissor rectangle.
// 2016-07-29: OpenGL: Explicitly setting GL_UNPACK_ROW_LENGTH to reduce issues because SDL changes it. (#752)
//----------------------------------------
// OpenGL GLSL GLSL
// version version string
//----------------------------------------
// 2.0 110 "#version 110"
// 2.1 120
// 3.0 130
// 3.1 140
// 3.2 150 "#version 150"
// 3.3 330
// 4.0 400
// 4.1 410 "#version 410 core"
// 4.2 420
// 4.3 430
// ES 2.0 100 "#version 100"
// ES 3.0 300 "#version 300 es"
//----------------------------------------
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "imgui.h"
#include "imgui_impl_opengl3.h"
#include <stdio.h>
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
#include <stddef.h> // intptr_t
#else
#include <stdint.h> // intptr_t
#endif
#if defined(__APPLE__)
#include "TargetConditionals.h"
#endif
// iOS, Android and Emscripten can use GL ES 3
// Call ImGui_ImplOpenGL3_Init() with "#version 300 es"
#if (defined(__APPLE__) && TARGET_OS_IOS) || (defined(__ANDROID__)) || (defined(__EMSCRIPTEN__))
#define USE_GL_ES3
#endif
#ifdef USE_GL_ES3
// OpenGL ES 3
#include <GLES3/gl3.h> // Use GL ES 3
#else
// Regular OpenGL
// About OpenGL function loaders: modern OpenGL doesn't have a standard header file and requires individual function pointers to be loaded manually.
// Helper libraries are often used for this purpose! Here we are supporting a few common ones: gl3w, glew, glad.
// You may use another loader/header of your choice (glext, glLoadGen, etc.), or chose to manually implement your own.
#if defined(IMGUI_IMPL_OPENGL_LOADER_GL3W)
#include <GL/gl3w.h>
#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLEW)
#include <GL/glew.h>
#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD)
#include <glad/glad.h>
#else
#include IMGUI_IMPL_OPENGL_LOADER_CUSTOM
#endif
#endif
// OpenGL Data
static char g_GlslVersionString[32] = "";
static GLuint g_FontTexture = 0;
static GLuint g_ShaderHandle = 0, g_VertHandle = 0, g_FragHandle = 0;
static int g_AttribLocationTex = 0, g_AttribLocationProjMtx = 0;
static int g_AttribLocationPosition = 0, g_AttribLocationUV = 0, g_AttribLocationColor = 0;
static unsigned int g_VboHandle = 0, g_ElementsHandle = 0;
// Functions
bool ImGui_ImplOpenGL3_Init(const char* glsl_version)
{
// Store GLSL version string so we can refer to it later in case we recreate shaders. Note: GLSL version is NOT the same as GL version. Leave this to NULL if unsure.
#ifdef USE_GL_ES3
if (glsl_version == NULL)
glsl_version = "#version 300 es";
#else
if (glsl_version == NULL)
glsl_version = "#version 130";
#endif
IM_ASSERT((int)strlen(glsl_version) + 2 < IM_ARRAYSIZE(g_GlslVersionString));
strcpy(g_GlslVersionString, glsl_version);
strcat(g_GlslVersionString, "\n");
return true;
}
void ImGui_ImplOpenGL3_Shutdown()
{
ImGui_ImplOpenGL3_DestroyDeviceObjects();
}
void ImGui_ImplOpenGL3_NewFrame()
{
if (!g_FontTexture)
ImGui_ImplOpenGL3_CreateDeviceObjects();
}
// OpenGL3 Render function.
// (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
// Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly, in order to be able to run within any OpenGL engine that doesn't do so.
void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data)
{
// Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
ImGuiIO& io = ImGui::GetIO();
int fb_width = (int)(draw_data->DisplaySize.x * io.DisplayFramebufferScale.x);
int fb_height = (int)(draw_data->DisplaySize.y * io.DisplayFramebufferScale.y);
if (fb_width <= 0 || fb_height <= 0)
return;
draw_data->ScaleClipRects(io.DisplayFramebufferScale);
// Backup GL state
GLenum last_active_texture; glGetIntegerv(GL_ACTIVE_TEXTURE, (GLint*)&last_active_texture);
glActiveTexture(GL_TEXTURE0);
GLint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, &last_program);
GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
#ifdef GL_SAMPLER_BINDING
GLint last_sampler; glGetIntegerv(GL_SAMPLER_BINDING, &last_sampler);
#endif
GLint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
GLint last_vertex_array; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
#ifdef GL_POLYGON_MODE
GLint last_polygon_mode[2]; glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode);
#endif
GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box);
GLenum last_blend_src_rgb; glGetIntegerv(GL_BLEND_SRC_RGB, (GLint*)&last_blend_src_rgb);
GLenum last_blend_dst_rgb; glGetIntegerv(GL_BLEND_DST_RGB, (GLint*)&last_blend_dst_rgb);
GLenum last_blend_src_alpha; glGetIntegerv(GL_BLEND_SRC_ALPHA, (GLint*)&last_blend_src_alpha);
GLenum last_blend_dst_alpha; glGetIntegerv(GL_BLEND_DST_ALPHA, (GLint*)&last_blend_dst_alpha);
GLenum last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, (GLint*)&last_blend_equation_rgb);
GLenum last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, (GLint*)&last_blend_equation_alpha);
GLboolean last_enable_blend = glIsEnabled(GL_BLEND);
GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE);
GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST);
GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST);
// Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, polygon fill
glEnable(GL_BLEND);
glBlendEquation(GL_FUNC_ADD);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glEnable(GL_SCISSOR_TEST);
#ifdef GL_POLYGON_MODE
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
#endif
// Setup viewport, orthographic projection matrix
// Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayMin is typically (0,0) for single viewport apps.
glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
float L = draw_data->DisplayPos.x;
float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
float T = draw_data->DisplayPos.y;
float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
const float ortho_projection[4][4] =
{
{ 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
{ 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
{ 0.0f, 0.0f, -1.0f, 0.0f },
{ (R+L)/(L-R), (T+B)/(B-T), 0.0f, 1.0f },
};
glUseProgram(g_ShaderHandle);
glUniform1i(g_AttribLocationTex, 0);
glUniformMatrix4fv(g_AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]);
#ifdef GL_SAMPLER_BINDING
glBindSampler(0, 0); // We use combined texture/sampler state. Applications using GL 3.3 may set that otherwise.
#endif
// Recreate the VAO every time
// (This is to easily allow multiple GL contexts. VAO are not shared among GL contexts, and we don't track creation/deletion of windows so we don't have an obvious key to use to cache them.)
GLuint vao_handle = 0;
glGenVertexArrays(1, &vao_handle);
glBindVertexArray(vao_handle);
glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
glEnableVertexAttribArray(g_AttribLocationPosition);
glEnableVertexAttribArray(g_AttribLocationUV);
glEnableVertexAttribArray(g_AttribLocationColor);
glVertexAttribPointer(g_AttribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, pos));
glVertexAttribPointer(g_AttribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, uv));
glVertexAttribPointer(g_AttribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, col));
// Draw
ImVec2 pos = draw_data->DisplayPos;
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
const ImDrawList* cmd_list = draw_data->CmdLists[n];
const ImDrawIdx* idx_buffer_offset = 0;
glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.Size * sizeof(ImDrawVert), (const GLvoid*)cmd_list->VtxBuffer.Data, GL_STREAM_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx), (const GLvoid*)cmd_list->IdxBuffer.Data, GL_STREAM_DRAW);
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
{
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
if (pcmd->UserCallback)
{
// User callback (registered via ImDrawList::AddCallback)
pcmd->UserCallback(cmd_list, pcmd);
}
else
{
ImVec4 clip_rect = ImVec4(pcmd->ClipRect.x - pos.x, pcmd->ClipRect.y - pos.y, pcmd->ClipRect.z - pos.x, pcmd->ClipRect.w - pos.y);
if (clip_rect.x < fb_width && clip_rect.y < fb_height && clip_rect.z >= 0.0f && clip_rect.w >= 0.0f)
{
// Apply scissor/clipping rectangle
glScissor((int)clip_rect.x, (int)(fb_height - clip_rect.w), (int)(clip_rect.z - clip_rect.x), (int)(clip_rect.w - clip_rect.y));
// Bind texture, Draw
glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId);
glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
}
}
idx_buffer_offset += pcmd->ElemCount;
}
}
glDeleteVertexArrays(1, &vao_handle);
// Restore modified GL state
glUseProgram(last_program);
glBindTexture(GL_TEXTURE_2D, last_texture);
#ifdef GL_SAMPLER_BINDING
glBindSampler(0, last_sampler);
#endif
glActiveTexture(last_active_texture);
glBindVertexArray(last_vertex_array);
glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha);
glBlendFuncSeparate(last_blend_src_rgb, last_blend_dst_rgb, last_blend_src_alpha, last_blend_dst_alpha);
if (last_enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND);
if (last_enable_cull_face) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE);
if (last_enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST);
if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST);
#ifdef GL_POLYGON_MODE
glPolygonMode(GL_FRONT_AND_BACK, (GLenum)last_polygon_mode[0]);
#endif
glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]);
}
bool ImGui_ImplOpenGL3_CreateFontsTexture()
{
// Build texture atlas
ImGuiIO& io = ImGui::GetIO();
unsigned char* pixels;
int width, height;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bits (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory.
// Upload texture to graphics system
GLint last_texture;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
glGenTextures(1, &g_FontTexture);
glBindTexture(GL_TEXTURE_2D, g_FontTexture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
// Store our identifier
io.Fonts->TexID = (ImTextureID)(intptr_t)g_FontTexture;
// Restore state
glBindTexture(GL_TEXTURE_2D, last_texture);
return true;
}
void ImGui_ImplOpenGL3_DestroyFontsTexture()
{
if (g_FontTexture)
{
ImGuiIO& io = ImGui::GetIO();
glDeleteTextures(1, &g_FontTexture);
io.Fonts->TexID = 0;
g_FontTexture = 0;
}
}
// If you get an error please report on github. You may try different GL context version or GLSL version. See GL<>GLSL version table at the top of this file.
static bool CheckShader(GLuint handle, const char* desc)
{
GLint status = 0, log_length = 0;
glGetShaderiv(handle, GL_COMPILE_STATUS, &status);
glGetShaderiv(handle, GL_INFO_LOG_LENGTH, &log_length);
if ((GLboolean)status == GL_FALSE)
fprintf(stderr, "ERROR: ImGui_ImplOpenGL3_CreateDeviceObjects: failed to compile %s!\n", desc);
if (log_length > 0)
{
ImVector<char> buf;
buf.resize((int)(log_length + 1));
glGetShaderInfoLog(handle, log_length, NULL, (GLchar*)buf.begin());
fprintf(stderr, "%s\n", buf.begin());
}
return (GLboolean)status == GL_TRUE;
}
// If you get an error please report on GitHub. You may try different GL context version or GLSL version.
static bool CheckProgram(GLuint handle, const char* desc)
{
GLint status = 0, log_length = 0;
glGetProgramiv(handle, GL_LINK_STATUS, &status);
glGetProgramiv(handle, GL_INFO_LOG_LENGTH, &log_length);
if ((GLboolean)status == GL_FALSE)
fprintf(stderr, "ERROR: ImGui_ImplOpenGL3_CreateDeviceObjects: failed to link %s! (with GLSL '%s')\n", desc, g_GlslVersionString);
if (log_length > 0)
{
ImVector<char> buf;
buf.resize((int)(log_length + 1));
glGetProgramInfoLog(handle, log_length, NULL, (GLchar*)buf.begin());
fprintf(stderr, "%s\n", buf.begin());
}
return (GLboolean)status == GL_TRUE;
}
bool ImGui_ImplOpenGL3_CreateDeviceObjects()
{
// Backup GL state
GLint last_texture, last_array_buffer, last_vertex_array;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
// Parse GLSL version string
int glsl_version = 130;
sscanf(g_GlslVersionString, "#version %d", &glsl_version);
const GLchar* vertex_shader_glsl_120 =
"uniform mat4 ProjMtx;\n"
"attribute vec2 Position;\n"
"attribute vec2 UV;\n"
"attribute vec4 Color;\n"
"varying vec2 Frag_UV;\n"
"varying vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" Frag_UV = UV;\n"
" Frag_Color = Color;\n"
" gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
"}\n";
const GLchar* vertex_shader_glsl_130 =
"uniform mat4 ProjMtx;\n"
"in vec2 Position;\n"
"in vec2 UV;\n"
"in vec4 Color;\n"
"out vec2 Frag_UV;\n"
"out vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" Frag_UV = UV;\n"
" Frag_Color = Color;\n"
" gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
"}\n";
const GLchar* vertex_shader_glsl_300_es =
"precision mediump float;\n"
"layout (location = 0) in vec2 Position;\n"
"layout (location = 1) in vec2 UV;\n"
"layout (location = 2) in vec4 Color;\n"
"uniform mat4 ProjMtx;\n"
"out vec2 Frag_UV;\n"
"out vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" Frag_UV = UV;\n"
" Frag_Color = Color;\n"
" gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
"}\n";
const GLchar* vertex_shader_glsl_410_core =
"layout (location = 0) in vec2 Position;\n"
"layout (location = 1) in vec2 UV;\n"
"layout (location = 2) in vec4 Color;\n"
"uniform mat4 ProjMtx;\n"
"out vec2 Frag_UV;\n"
"out vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" Frag_UV = UV;\n"
" Frag_Color = Color;\n"
" gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
"}\n";
const GLchar* fragment_shader_glsl_120 =
"#ifdef GL_ES\n"
" precision mediump float;\n"
"#endif\n"
"uniform sampler2D Texture;\n"
"varying vec2 Frag_UV;\n"
"varying vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" gl_FragColor = Frag_Color * texture2D(Texture, Frag_UV.st);\n"
"}\n";
const GLchar* fragment_shader_glsl_130 =
"uniform sampler2D Texture;\n"
"in vec2 Frag_UV;\n"
"in vec4 Frag_Color;\n"
"out vec4 Out_Color;\n"
"void main()\n"
"{\n"
" Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
"}\n";
const GLchar* fragment_shader_glsl_300_es =
"precision mediump float;\n"
"uniform sampler2D Texture;\n"
"in vec2 Frag_UV;\n"
"in vec4 Frag_Color;\n"
"layout (location = 0) out vec4 Out_Color;\n"
"void main()\n"
"{\n"
" Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
"}\n";
const GLchar* fragment_shader_glsl_410_core =
"in vec2 Frag_UV;\n"
"in vec4 Frag_Color;\n"
"uniform sampler2D Texture;\n"
"layout (location = 0) out vec4 Out_Color;\n"
"void main()\n"
"{\n"
" Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
"}\n";
// Select shaders matching our GLSL versions
const GLchar* vertex_shader = NULL;
const GLchar* fragment_shader = NULL;
if (glsl_version < 130)
{
vertex_shader = vertex_shader_glsl_120;
fragment_shader = fragment_shader_glsl_120;
}
else if (glsl_version == 410)
{
vertex_shader = vertex_shader_glsl_410_core;
fragment_shader = fragment_shader_glsl_410_core;
}
else if (glsl_version == 300)
{
vertex_shader = vertex_shader_glsl_300_es;
fragment_shader = fragment_shader_glsl_300_es;
}
else
{
vertex_shader = vertex_shader_glsl_130;
fragment_shader = fragment_shader_glsl_130;
}
// Create shaders
const GLchar* vertex_shader_with_version[2] = { g_GlslVersionString, vertex_shader };
g_VertHandle = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(g_VertHandle, 2, vertex_shader_with_version, NULL);
glCompileShader(g_VertHandle);
CheckShader(g_VertHandle, "vertex shader");
const GLchar* fragment_shader_with_version[2] = { g_GlslVersionString, fragment_shader };
g_FragHandle = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(g_FragHandle, 2, fragment_shader_with_version, NULL);
glCompileShader(g_FragHandle);
CheckShader(g_FragHandle, "fragment shader");
g_ShaderHandle = glCreateProgram();
glAttachShader(g_ShaderHandle, g_VertHandle);
glAttachShader(g_ShaderHandle, g_FragHandle);
glLinkProgram(g_ShaderHandle);
CheckProgram(g_ShaderHandle, "shader program");
g_AttribLocationTex = glGetUniformLocation(g_ShaderHandle, "Texture");
g_AttribLocationProjMtx = glGetUniformLocation(g_ShaderHandle, "ProjMtx");
g_AttribLocationPosition = glGetAttribLocation(g_ShaderHandle, "Position");
g_AttribLocationUV = glGetAttribLocation(g_ShaderHandle, "UV");
g_AttribLocationColor = glGetAttribLocation(g_ShaderHandle, "Color");
// Create buffers
glGenBuffers(1, &g_VboHandle);
glGenBuffers(1, &g_ElementsHandle);
ImGui_ImplOpenGL3_CreateFontsTexture();
// Restore modified GL state
glBindTexture(GL_TEXTURE_2D, last_texture);
glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
glBindVertexArray(last_vertex_array);
return true;
}
void ImGui_ImplOpenGL3_DestroyDeviceObjects()
{
if (g_VboHandle) glDeleteBuffers(1, &g_VboHandle);
if (g_ElementsHandle) glDeleteBuffers(1, &g_ElementsHandle);
g_VboHandle = g_ElementsHandle = 0;
if (g_ShaderHandle && g_VertHandle) glDetachShader(g_ShaderHandle, g_VertHandle);
if (g_VertHandle) glDeleteShader(g_VertHandle);
g_VertHandle = 0;
if (g_ShaderHandle && g_FragHandle) glDetachShader(g_ShaderHandle, g_FragHandle);
if (g_FragHandle) glDeleteShader(g_FragHandle);
g_FragHandle = 0;
if (g_ShaderHandle) glDeleteProgram(g_ShaderHandle);
g_ShaderHandle = 0;
ImGui_ImplOpenGL3_DestroyFontsTexture();
}

View File

@ -0,0 +1,41 @@
// dear imgui: Renderer for OpenGL3 / OpenGL ES2 / OpenGL ES3 (modern OpenGL with shaders / programmatic pipeline)
// This needs to be used along with a Platform Binding (e.g. GLFW, SDL, Win32, custom..)
// (Note: We are using GL3W as a helper library to access OpenGL functions since there is no standard header to access modern OpenGL functions easily. Alternatives are GLEW, Glad, etc..)
// Implemented features:
// [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID in imgui.cpp.
// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp.
// https://github.com/ocornut/imgui
// About OpenGL function loaders:
// About OpenGL function loaders: modern OpenGL doesn't have a standard header file and requires individual function pointers to be loaded manually.
// Helper libraries are often used for this purpose! Here we are supporting a few common ones: gl3w, glew, glad.
// You may use another loader/header of your choice (glext, glLoadGen, etc.), or chose to manually implement your own.
// About GLSL version:
// The 'glsl_version' initialization parameter should be NULL (default) or a "#version XXX" string.
// On computer platform the GLSL version default to "#version 130". On OpenGL ES 3 platform it defaults to "#version 300 es"
// Only override if your GL version doesn't handle this GLSL version. See GLSL version table at the top of imgui_impl_opengl3.cpp.
#pragma once
// Set default OpenGL loader to be gl3w
#if !defined(IMGUI_IMPL_OPENGL_LOADER_GL3W) \
&& !defined(IMGUI_IMPL_OPENGL_LOADER_GLEW) \
&& !defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) \
&& !defined(IMGUI_IMPL_OPENGL_LOADER_CUSTOM)
#define IMGUI_IMPL_OPENGL_LOADER_GL3W
#endif
IMGUI_IMPL_API bool ImGui_ImplOpenGL3_Init(const char* glsl_version = NULL);
IMGUI_IMPL_API void ImGui_ImplOpenGL3_Shutdown();
IMGUI_IMPL_API void ImGui_ImplOpenGL3_NewFrame();
IMGUI_IMPL_API void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data);
// Called by Init/NewFrame/Shutdown
IMGUI_IMPL_API bool ImGui_ImplOpenGL3_CreateFontsTexture();
IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyFontsTexture();
IMGUI_IMPL_API bool ImGui_ImplOpenGL3_CreateDeviceObjects();
IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyDeviceObjects();

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,623 @@
// stb_rect_pack.h - v0.11 - public domain - rectangle packing
// Sean Barrett 2014
//
// Useful for e.g. packing rectangular textures into an atlas.
// Does not do rotation.
//
// Not necessarily the awesomest packing method, but better than
// the totally naive one in stb_truetype (which is primarily what
// this is meant to replace).
//
// Has only had a few tests run, may have issues.
//
// More docs to come.
//
// No memory allocations; uses qsort() and assert() from stdlib.
// Can override those by defining STBRP_SORT and STBRP_ASSERT.
//
// This library currently uses the Skyline Bottom-Left algorithm.
//
// Please note: better rectangle packers are welcome! Please
// implement them to the same API, but with a different init
// function.
//
// Credits
//
// Library
// Sean Barrett
// Minor features
// Martins Mozeiko
// github:IntellectualKitty
//
// Bugfixes / warning fixes
// Jeremy Jaussaud
//
// Version history:
//
// 0.11 (2017-03-03) return packing success/fail result
// 0.10 (2016-10-25) remove cast-away-const to avoid warnings
// 0.09 (2016-08-27) fix compiler warnings
// 0.08 (2015-09-13) really fix bug with empty rects (w=0 or h=0)
// 0.07 (2015-09-13) fix bug with empty rects (w=0 or h=0)
// 0.06 (2015-04-15) added STBRP_SORT to allow replacing qsort
// 0.05: added STBRP_ASSERT to allow replacing assert
// 0.04: fixed minor bug in STBRP_LARGE_RECTS support
// 0.01: initial release
//
// LICENSE
//
// See end of file for license information.
//////////////////////////////////////////////////////////////////////////////
//
// INCLUDE SECTION
//
#ifndef STB_INCLUDE_STB_RECT_PACK_H
#define STB_INCLUDE_STB_RECT_PACK_H
#define STB_RECT_PACK_VERSION 1
#ifdef STBRP_STATIC
#define STBRP_DEF static
#else
#define STBRP_DEF extern
#endif
#ifdef __cplusplus
extern "C" {
#endif
typedef struct stbrp_context stbrp_context;
typedef struct stbrp_node stbrp_node;
typedef struct stbrp_rect stbrp_rect;
#ifdef STBRP_LARGE_RECTS
typedef int stbrp_coord;
#else
typedef unsigned short stbrp_coord;
#endif
STBRP_DEF int stbrp_pack_rects (stbrp_context *context, stbrp_rect *rects, int num_rects);
// Assign packed locations to rectangles. The rectangles are of type
// 'stbrp_rect' defined below, stored in the array 'rects', and there
// are 'num_rects' many of them.
//
// Rectangles which are successfully packed have the 'was_packed' flag
// set to a non-zero value and 'x' and 'y' store the minimum location
// on each axis (i.e. bottom-left in cartesian coordinates, top-left
// if you imagine y increasing downwards). Rectangles which do not fit
// have the 'was_packed' flag set to 0.
//
// You should not try to access the 'rects' array from another thread
// while this function is running, as the function temporarily reorders
// the array while it executes.
//
// To pack into another rectangle, you need to call stbrp_init_target
// again. To continue packing into the same rectangle, you can call
// this function again. Calling this multiple times with multiple rect
// arrays will probably produce worse packing results than calling it
// a single time with the full rectangle array, but the option is
// available.
//
// The function returns 1 if all of the rectangles were successfully
// packed and 0 otherwise.
struct stbrp_rect
{
// reserved for your use:
int id;
// input:
stbrp_coord w, h;
// output:
stbrp_coord x, y;
int was_packed; // non-zero if valid packing
}; // 16 bytes, nominally
STBRP_DEF void stbrp_init_target (stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes);
// Initialize a rectangle packer to:
// pack a rectangle that is 'width' by 'height' in dimensions
// using temporary storage provided by the array 'nodes', which is 'num_nodes' long
//
// You must call this function every time you start packing into a new target.
//
// There is no "shutdown" function. The 'nodes' memory must stay valid for
// the following stbrp_pack_rects() call (or calls), but can be freed after
// the call (or calls) finish.
//
// Note: to guarantee best results, either:
// 1. make sure 'num_nodes' >= 'width'
// or 2. call stbrp_allow_out_of_mem() defined below with 'allow_out_of_mem = 1'
//
// If you don't do either of the above things, widths will be quantized to multiples
// of small integers to guarantee the algorithm doesn't run out of temporary storage.
//
// If you do #2, then the non-quantized algorithm will be used, but the algorithm
// may run out of temporary storage and be unable to pack some rectangles.
STBRP_DEF void stbrp_setup_allow_out_of_mem (stbrp_context *context, int allow_out_of_mem);
// Optionally call this function after init but before doing any packing to
// change the handling of the out-of-temp-memory scenario, described above.
// If you call init again, this will be reset to the default (false).
STBRP_DEF void stbrp_setup_heuristic (stbrp_context *context, int heuristic);
// Optionally select which packing heuristic the library should use. Different
// heuristics will produce better/worse results for different data sets.
// If you call init again, this will be reset to the default.
enum
{
STBRP_HEURISTIC_Skyline_default=0,
STBRP_HEURISTIC_Skyline_BL_sortHeight = STBRP_HEURISTIC_Skyline_default,
STBRP_HEURISTIC_Skyline_BF_sortHeight
};
//////////////////////////////////////////////////////////////////////////////
//
// the details of the following structures don't matter to you, but they must
// be visible so you can handle the memory allocations for them
struct stbrp_node
{
stbrp_coord x,y;
stbrp_node *next;
};
struct stbrp_context
{
int width;
int height;
int align;
int init_mode;
int heuristic;
int num_nodes;
stbrp_node *active_head;
stbrp_node *free_head;
stbrp_node extra[2]; // we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2'
};
#ifdef __cplusplus
}
#endif
#endif
//////////////////////////////////////////////////////////////////////////////
//
// IMPLEMENTATION SECTION
//
#ifdef STB_RECT_PACK_IMPLEMENTATION
#ifndef STBRP_SORT
#include <stdlib.h>
#define STBRP_SORT qsort
#endif
#ifndef STBRP_ASSERT
#include <assert.h>
#define STBRP_ASSERT assert
#endif
#ifdef _MSC_VER
#define STBRP__NOTUSED(v) (void)(v)
#define STBRP__CDECL __cdecl
#else
#define STBRP__NOTUSED(v) (void)sizeof(v)
#define STBRP__CDECL
#endif
enum
{
STBRP__INIT_skyline = 1
};
STBRP_DEF void stbrp_setup_heuristic(stbrp_context *context, int heuristic)
{
switch (context->init_mode) {
case STBRP__INIT_skyline:
STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight || heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight);
context->heuristic = heuristic;
break;
default:
STBRP_ASSERT(0);
}
}
STBRP_DEF void stbrp_setup_allow_out_of_mem(stbrp_context *context, int allow_out_of_mem)
{
if (allow_out_of_mem)
// if it's ok to run out of memory, then don't bother aligning them;
// this gives better packing, but may fail due to OOM (even though
// the rectangles easily fit). @TODO a smarter approach would be to only
// quantize once we've hit OOM, then we could get rid of this parameter.
context->align = 1;
else {
// if it's not ok to run out of memory, then quantize the widths
// so that num_nodes is always enough nodes.
//
// I.e. num_nodes * align >= width
// align >= width / num_nodes
// align = ceil(width/num_nodes)
context->align = (context->width + context->num_nodes-1) / context->num_nodes;
}
}
STBRP_DEF void stbrp_init_target(stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes)
{
int i;
#ifndef STBRP_LARGE_RECTS
STBRP_ASSERT(width <= 0xffff && height <= 0xffff);
#endif
for (i=0; i < num_nodes-1; ++i)
nodes[i].next = &nodes[i+1];
nodes[i].next = NULL;
context->init_mode = STBRP__INIT_skyline;
context->heuristic = STBRP_HEURISTIC_Skyline_default;
context->free_head = &nodes[0];
context->active_head = &context->extra[0];
context->width = width;
context->height = height;
context->num_nodes = num_nodes;
stbrp_setup_allow_out_of_mem(context, 0);
// node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly)
context->extra[0].x = 0;
context->extra[0].y = 0;
context->extra[0].next = &context->extra[1];
context->extra[1].x = (stbrp_coord) width;
#ifdef STBRP_LARGE_RECTS
context->extra[1].y = (1<<30);
#else
context->extra[1].y = 65535;
#endif
context->extra[1].next = NULL;
}
// find minimum y position if it starts at x1
static int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0, int width, int *pwaste)
{
stbrp_node *node = first;
int x1 = x0 + width;
int min_y, visited_width, waste_area;
STBRP__NOTUSED(c);
STBRP_ASSERT(first->x <= x0);
#if 0
// skip in case we're past the node
while (node->next->x <= x0)
++node;
#else
STBRP_ASSERT(node->next->x > x0); // we ended up handling this in the caller for efficiency
#endif
STBRP_ASSERT(node->x <= x0);
min_y = 0;
waste_area = 0;
visited_width = 0;
while (node->x < x1) {
if (node->y > min_y) {
// raise min_y higher.
// we've accounted for all waste up to min_y,
// but we'll now add more waste for everything we've visted
waste_area += visited_width * (node->y - min_y);
min_y = node->y;
// the first time through, visited_width might be reduced
if (node->x < x0)
visited_width += node->next->x - x0;
else
visited_width += node->next->x - node->x;
} else {
// add waste area
int under_width = node->next->x - node->x;
if (under_width + visited_width > width)
under_width = width - visited_width;
waste_area += under_width * (min_y - node->y);
visited_width += under_width;
}
node = node->next;
}
*pwaste = waste_area;
return min_y;
}
typedef struct
{
int x,y;
stbrp_node **prev_link;
} stbrp__findresult;
static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int width, int height)
{
int best_waste = (1<<30), best_x, best_y = (1 << 30);
stbrp__findresult fr;
stbrp_node **prev, *node, *tail, **best = NULL;
// align to multiple of c->align
width = (width + c->align - 1);
width -= width % c->align;
STBRP_ASSERT(width % c->align == 0);
node = c->active_head;
prev = &c->active_head;
while (node->x + width <= c->width) {
int y,waste;
y = stbrp__skyline_find_min_y(c, node, node->x, width, &waste);
if (c->heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight) { // actually just want to test BL
// bottom left
if (y < best_y) {
best_y = y;
best = prev;
}
} else {
// best-fit
if (y + height <= c->height) {
// can only use it if it first vertically
if (y < best_y || (y == best_y && waste < best_waste)) {
best_y = y;
best_waste = waste;
best = prev;
}
}
}
prev = &node->next;
node = node->next;
}
best_x = (best == NULL) ? 0 : (*best)->x;
// if doing best-fit (BF), we also have to try aligning right edge to each node position
//
// e.g, if fitting
//
// ____________________
// |____________________|
//
// into
//
// | |
// | ____________|
// |____________|
//
// then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned
//
// This makes BF take about 2x the time
if (c->heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight) {
tail = c->active_head;
node = c->active_head;
prev = &c->active_head;
// find first node that's admissible
while (tail->x < width)
tail = tail->next;
while (tail) {
int xpos = tail->x - width;
int y,waste;
STBRP_ASSERT(xpos >= 0);
// find the left position that matches this
while (node->next->x <= xpos) {
prev = &node->next;
node = node->next;
}
STBRP_ASSERT(node->next->x > xpos && node->x <= xpos);
y = stbrp__skyline_find_min_y(c, node, xpos, width, &waste);
if (y + height < c->height) {
if (y <= best_y) {
if (y < best_y || waste < best_waste || (waste==best_waste && xpos < best_x)) {
best_x = xpos;
STBRP_ASSERT(y <= best_y);
best_y = y;
best_waste = waste;
best = prev;
}
}
}
tail = tail->next;
}
}
fr.prev_link = best;
fr.x = best_x;
fr.y = best_y;
return fr;
}
static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, int width, int height)
{
// find best position according to heuristic
stbrp__findresult res = stbrp__skyline_find_best_pos(context, width, height);
stbrp_node *node, *cur;
// bail if:
// 1. it failed
// 2. the best node doesn't fit (we don't always check this)
// 3. we're out of memory
if (res.prev_link == NULL || res.y + height > context->height || context->free_head == NULL) {
res.prev_link = NULL;
return res;
}
// on success, create new node
node = context->free_head;
node->x = (stbrp_coord) res.x;
node->y = (stbrp_coord) (res.y + height);
context->free_head = node->next;
// insert the new node into the right starting point, and
// let 'cur' point to the remaining nodes needing to be
// stiched back in
cur = *res.prev_link;
if (cur->x < res.x) {
// preserve the existing one, so start testing with the next one
stbrp_node *next = cur->next;
cur->next = node;
cur = next;
} else {
*res.prev_link = node;
}
// from here, traverse cur and free the nodes, until we get to one
// that shouldn't be freed
while (cur->next && cur->next->x <= res.x + width) {
stbrp_node *next = cur->next;
// move the current node to the free list
cur->next = context->free_head;
context->free_head = cur;
cur = next;
}
// stitch the list back in
node->next = cur;
if (cur->x < res.x + width)
cur->x = (stbrp_coord) (res.x + width);
#ifdef _DEBUG
cur = context->active_head;
while (cur->x < context->width) {
STBRP_ASSERT(cur->x < cur->next->x);
cur = cur->next;
}
STBRP_ASSERT(cur->next == NULL);
{
int count=0;
cur = context->active_head;
while (cur) {
cur = cur->next;
++count;
}
cur = context->free_head;
while (cur) {
cur = cur->next;
++count;
}
STBRP_ASSERT(count == context->num_nodes+2);
}
#endif
return res;
}
static int STBRP__CDECL rect_height_compare(const void *a, const void *b)
{
const stbrp_rect *p = (const stbrp_rect *) a;
const stbrp_rect *q = (const stbrp_rect *) b;
if (p->h > q->h)
return -1;
if (p->h < q->h)
return 1;
return (p->w > q->w) ? -1 : (p->w < q->w);
}
static int STBRP__CDECL rect_original_order(const void *a, const void *b)
{
const stbrp_rect *p = (const stbrp_rect *) a;
const stbrp_rect *q = (const stbrp_rect *) b;
return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed);
}
#ifdef STBRP_LARGE_RECTS
#define STBRP__MAXVAL 0xffffffff
#else
#define STBRP__MAXVAL 0xffff
#endif
STBRP_DEF int stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects)
{
int i, all_rects_packed = 1;
// we use the 'was_packed' field internally to allow sorting/unsorting
for (i=0; i < num_rects; ++i) {
rects[i].was_packed = i;
#ifndef STBRP_LARGE_RECTS
STBRP_ASSERT(rects[i].w <= 0xffff && rects[i].h <= 0xffff);
#endif
}
// sort according to heuristic
STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_height_compare);
for (i=0; i < num_rects; ++i) {
if (rects[i].w == 0 || rects[i].h == 0) {
rects[i].x = rects[i].y = 0; // empty rect needs no space
} else {
stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h);
if (fr.prev_link) {
rects[i].x = (stbrp_coord) fr.x;
rects[i].y = (stbrp_coord) fr.y;
} else {
rects[i].x = rects[i].y = STBRP__MAXVAL;
}
}
}
// unsort
STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_original_order);
// set was_packed flags and all_rects_packed status
for (i=0; i < num_rects; ++i) {
rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL);
if (!rects[i].was_packed)
all_rects_packed = 0;
}
// return the all_rects_packed status
return all_rects_packed;
}
#endif
/*
------------------------------------------------------------------------------
This software is available under 2 licenses -- choose whichever you prefer.
------------------------------------------------------------------------------
ALTERNATIVE A - MIT License
Copyright (c) 2017 Sean Barrett
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
ALTERNATIVE B - Public Domain (www.unlicense.org)
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
*/

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,9 @@
#version 430
in vec3 f_color;
out vec4 FragColors;
void main()
{
FragColors = vec4(f_color, 1.f);
}

14
BaseGLProject/simple.vert Normal file
View File

@ -0,0 +1,14 @@
#version 430
layout(location=0) in vec3 coord3d;
layout(location=1) in vec3 v_color;
out vec3 f_color;
uniform mat4 mvp;
void main(void)
{
f_color = v_color;
gl_Position = mvp * vec4(coord3d, 1.0f);
}

31
BaseOpenGLProject.sln Normal file
View File

@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.28010.2041
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "BaseGLProject", "BaseGLProject\BaseGLProject.vcxproj", "{53EA9451-7504-4B40-9986-47ECD7AA35D8}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{53EA9451-7504-4B40-9986-47ECD7AA35D8}.Debug|x64.ActiveCfg = Debug|x64
{53EA9451-7504-4B40-9986-47ECD7AA35D8}.Debug|x64.Build.0 = Debug|x64
{53EA9451-7504-4B40-9986-47ECD7AA35D8}.Debug|x86.ActiveCfg = Debug|Win32
{53EA9451-7504-4B40-9986-47ECD7AA35D8}.Debug|x86.Build.0 = Debug|Win32
{53EA9451-7504-4B40-9986-47ECD7AA35D8}.Release|x64.ActiveCfg = Release|x64
{53EA9451-7504-4B40-9986-47ECD7AA35D8}.Release|x64.Build.0 = Release|x64
{53EA9451-7504-4B40-9986-47ECD7AA35D8}.Release|x86.ActiveCfg = Release|Win32
{53EA9451-7504-4B40-9986-47ECD7AA35D8}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {5406B6D7-8DCC-4463-B26A-3511D92BE420}
EndGlobalSection
EndGlobal