This commit is contained in:
Jakub Łangowski 2022-02-11 15:37:18 +01:00
commit 0a9fc2523b
2183 changed files with 589642 additions and 0 deletions

422
.gitignore vendored Normal file
View File

@ -0,0 +1,422 @@
## 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/main/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
/[Dd]ebug/
/[Dd]ebugPublic/
/[Rr]elease/
/[Rr]eleases/
x64/
x86/
/[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
/[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# 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
nunit-*.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/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# 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
*.tlog
*.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
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# 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
# NuGet Symbol Packages
*.snupkg
# 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
*.appxbundle
*.appxupload
# 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
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# 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 6 auto-generated project file (contains which files were open etc.)
*.vbp
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp
# Visual Studio 6 technical files
*.ncb
*.aps
# 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/
# 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/
# Visual Studio History (VSHistory) files
.vshistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp
# JetBrains Rider
*.sln.iml
# gitignore for C++
# Compiled Object files
*.slo
*.lo
*.o
# Compiled Dynamic libraries
*.so
*.dylib
# Compiled Static libraries
*.lai
*.la
*.a
# Visual Studio Files
/Debug
/Release
*.suo
*.csproj.user
*.vbproj.user
ipch
*sdf

31
Grk-Projekt.sln Normal file
View File

@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.32014.148
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Grk-Projekt", "Grk-Projekt\Grk-Projekt.vcxproj", "{3FD0ADB5-BA44-494A-A874-9C7D84AA93A6}"
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
{3FD0ADB5-BA44-494A-A874-9C7D84AA93A6}.Debug|x64.ActiveCfg = Debug|x64
{3FD0ADB5-BA44-494A-A874-9C7D84AA93A6}.Debug|x64.Build.0 = Debug|x64
{3FD0ADB5-BA44-494A-A874-9C7D84AA93A6}.Debug|x86.ActiveCfg = Debug|Win32
{3FD0ADB5-BA44-494A-A874-9C7D84AA93A6}.Debug|x86.Build.0 = Debug|Win32
{3FD0ADB5-BA44-494A-A874-9C7D84AA93A6}.Release|x64.ActiveCfg = Release|x64
{3FD0ADB5-BA44-494A-A874-9C7D84AA93A6}.Release|x64.Build.0 = Release|x64
{3FD0ADB5-BA44-494A-A874-9C7D84AA93A6}.Release|x86.ActiveCfg = Release|Win32
{3FD0ADB5-BA44-494A-A874-9C7D84AA93A6}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {4F1FE9D7-18E4-4DA2-A295-92187E9FD0F4}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<Project>
<ProjectOutputs>
<ProjectOutput>
<FullPath>C:\Users\kubik\source\repos\Grk-Projekt\Debug\Grk-Projekt.exe</FullPath>
</ProjectOutput>
</ProjectOutputs>
<ContentFiles />
<SatelliteDlls />
<NonRecipeFileRefs />
</Project>

BIN
Grk-Projekt/Debug/vc142.idb Normal file

Binary file not shown.

BIN
Grk-Projekt/Debug/vc143.idb Normal file

Binary file not shown.

View File

@ -0,0 +1,212 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" 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>16.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{3fd0adb5-ba44-494a-a874-9c7d84aa93a6}</ProjectGuid>
<RootNamespace>GrkProjekt</RootNamespace>
<WindowsTargetPlatformVersion>10.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>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</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)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>$(SolutionDir)dependencies\PHYSX\include;$(SolutionDir)dependencies\PHYSX\source\common\include;$(SolutionDir)dependencies\PHYSX\source\common\src;$(SolutionDir)dependencies\PHYSX\source\physx\src;$(SolutionDir)dependencies\PHYSX\source\physx\src\device;$(SolutionDir)dependencies\PHYSX\source\physx\src\buffering;$(SolutionDir)dependencies\PHYSX\source\physxgpu\include;$(SolutionDir)dependencies\PHYSX\source\geomutils\include;$(SolutionDir)dependencies\PHYSX\source\geomutils\src;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\contact;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\common;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\convex;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\distance;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\sweep;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\gjk;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\intersection;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\mesh;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\hf;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\pcm;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\ccd;$(SolutionDir)dependencies\PHYSX\source\lowlevel\api\include;$(SolutionDir)dependencies\PHYSX\source\lowlevel\software\include;$(SolutionDir)dependencies\PHYSX\source\lowlevel\common\include\pipeline;$(SolutionDir)dependencies\PHYSX\source\lowlevelaabb\include;$(SolutionDir)dependencies\PHYSX\source\lowleveldynamics\include;$(SolutionDir)dependencies\PHYSX\source\simulationcontroller\include;$(SolutionDir)dependencies\PHYSX\source\simulationcontroller\src;$(SolutionDir)dependencies\PHYSX\source\physxcooking\src;$(SolutionDir)dependencies\PHYSX\source\physxcooking\src\mesh;$(SolutionDir)dependencies\PHYSX\source\physxcooking\src\convex;$(SolutionDir)dependencies\PHYSX\source\scenequery\include;$(SolutionDir)dependencies\PHYSX\source\physxmetadata\core\include;$(SolutionDir)dependencies\PHYSX\source\immediatemode\include;$(SolutionDir)dependencies\PHYSX\source\pvd\include;$(SolutionDir)dependencies\PHYSX\source\foundation\include;$(SolutionDir)dependencies\GLFW\include;$(SolutionDir)dependencies\GLEW\include;$(SolutionDir)dependencies\GLM\include;$(SolutionDir)dependencies\ASSIMP\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\PhysXExtensions_static_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\PhysX_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\PhysXPvdSDK_static_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\PhysXVehicle_static_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\PhysXCharacterKinematic_static_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\PhysXCooking_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\PhysXCommon_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\SnippetUtils_static_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\SnippetRender_static_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\PhysXFoundation_32.lib;opengl32.lib;$(SolutionDir)dependencies\GLEW\lib\Release\Win32\glew32.lib;$(SolutionDir)dependencies\GLFW\lib-vc2022\glfw3.lib;$(SolutionDir)dependencies\ASSIMP\zlibd.lib;$(SolutionDir)dependencies\ASSIMP\assimp-vc141-mtd.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>
</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>$(SolutionDir)dependencies\PHYSX\include;$(SolutionDir)dependencies\PHYSX\source\common\include;$(SolutionDir)dependencies\PHYSX\source\common\src;$(SolutionDir)dependencies\PHYSX\source\physx\src;$(SolutionDir)dependencies\PHYSX\source\physx\src\device;$(SolutionDir)dependencies\PHYSX\source\physx\src\buffering;$(SolutionDir)dependencies\PHYSX\source\physxgpu\include;$(SolutionDir)dependencies\PHYSX\source\geomutils\include;$(SolutionDir)dependencies\PHYSX\source\geomutils\src;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\contact;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\common;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\convex;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\distance;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\sweep;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\gjk;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\intersection;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\mesh;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\hf;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\pcm;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\ccd;$(SolutionDir)dependencies\PHYSX\source\lowlevel\api\include;$(SolutionDir)dependencies\PHYSX\source\lowlevel\software\include;$(SolutionDir)dependencies\PHYSX\source\lowlevel\common\include\pipeline;$(SolutionDir)dependencies\PHYSX\source\lowlevelaabb\include;$(SolutionDir)dependencies\PHYSX\source\lowleveldynamics\include;$(SolutionDir)dependencies\PHYSX\source\simulationcontroller\include;$(SolutionDir)dependencies\PHYSX\source\simulationcontroller\src;$(SolutionDir)dependencies\PHYSX\source\physxcooking\src;$(SolutionDir)dependencies\PHYSX\source\physxcooking\src\mesh;$(SolutionDir)dependencies\PHYSX\source\physxcooking\src\convex;$(SolutionDir)dependencies\PHYSX\source\scenequery\include;$(SolutionDir)dependencies\PHYSX\source\physxmetadata\core\include;$(SolutionDir)dependencies\PHYSX\source\immediatemode\include;$(SolutionDir)dependencies\PHYSX\source\pvd\include;$(SolutionDir)dependencies\PHYSX\source\foundation\include;$(SolutionDir)dependencies\GLFW\include;$(SolutionDir)dependencies\GLEW\include;$(SolutionDir)dependencies\GLM\include;$(SolutionDir)dependencies\ASSIMP\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<Optimization>MaxSpeed</Optimization>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\PhysXExtensions_static_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\PhysX_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\PhysXPvdSDK_static_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\PhysXVehicle_static_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\PhysXCharacterKinematic_static_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\PhysXCooking_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\PhysXCommon_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\SnippetUtils_static_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\SnippetRender_static_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\PhysXFoundation_32.lib;opengl32.lib;$(SolutionDir)dependencies\GLEW\lib\Release\Win32\glew32.lib;$(SolutionDir)dependencies\GLFW\lib-vc2022\glfw3.lib;$(SolutionDir)dependencies\ASSIMP\zlibd.lib;$(SolutionDir)dependencies\ASSIMP\assimp-vc141-mtd.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>
</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>$(SolutionDir)dependencies\PHYSX\include;$(SolutionDir)dependencies\PHYSX\source\common\include;$(SolutionDir)dependencies\PHYSX\source\common\src;$(SolutionDir)dependencies\PHYSX\source\physx\src;$(SolutionDir)dependencies\PHYSX\source\physx\src\device;$(SolutionDir)dependencies\PHYSX\source\physx\src\buffering;$(SolutionDir)dependencies\PHYSX\source\physxgpu\include;$(SolutionDir)dependencies\PHYSX\source\geomutils\include;$(SolutionDir)dependencies\PHYSX\source\geomutils\src;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\contact;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\common;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\convex;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\distance;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\sweep;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\gjk;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\intersection;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\mesh;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\hf;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\pcm;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\ccd;$(SolutionDir)dependencies\PHYSX\source\lowlevel\api\include;$(SolutionDir)dependencies\PHYSX\source\lowlevel\software\include;$(SolutionDir)dependencies\PHYSX\source\lowlevel\common\include\pipeline;$(SolutionDir)dependencies\PHYSX\source\lowlevelaabb\include;$(SolutionDir)dependencies\PHYSX\source\lowleveldynamics\include;$(SolutionDir)dependencies\PHYSX\source\simulationcontroller\include;$(SolutionDir)dependencies\PHYSX\source\simulationcontroller\src;$(SolutionDir)dependencies\PHYSX\source\physxcooking\src;$(SolutionDir)dependencies\PHYSX\source\physxcooking\src\mesh;$(SolutionDir)dependencies\PHYSX\source\physxcooking\src\convex;$(SolutionDir)dependencies\PHYSX\source\scenequery\include;$(SolutionDir)dependencies\PHYSX\source\physxmetadata\core\include;$(SolutionDir)dependencies\PHYSX\source\immediatemode\include;$(SolutionDir)dependencies\PHYSX\source\pvd\include;$(SolutionDir)dependencies\PHYSX\source\foundation\include;$(SolutionDir)dependencies\GLFW\include;$(SolutionDir)dependencies\GLEW\include;$(SolutionDir)dependencies\GLM\include;$(SolutionDir)dependencies\ASSIMP\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\PhysXExtensions_static_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\PhysX_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\PhysXPvdSDK_static_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\PhysXVehicle_static_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\PhysXCharacterKinematic_static_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\PhysXCooking_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\PhysXCommon_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\SnippetUtils_static_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\SnippetRender_static_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\PhysXFoundation_32.lib;opengl32.lib;$(SolutionDir)dependencies\GLEW\lib\Release\Win32\glew32.lib;$(SolutionDir)dependencies\GLFW\lib-vc2022\glfw3.lib;$(SolutionDir)dependencies\ASSIMP\Release\zlibd.lib;$(SolutionDir)dependencies\ASSIMP\Release\assimp-vc141-mtd.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>$(SolutionDir)dependencies\PHYSX\include;$(SolutionDir)dependencies\PHYSX\source\common\include;$(SolutionDir)dependencies\PHYSX\source\common\src;$(SolutionDir)dependencies\PHYSX\source\physx\src;$(SolutionDir)dependencies\PHYSX\source\physx\src\device;$(SolutionDir)dependencies\PHYSX\source\physx\src\buffering;$(SolutionDir)dependencies\PHYSX\source\physxgpu\include;$(SolutionDir)dependencies\PHYSX\source\geomutils\include;$(SolutionDir)dependencies\PHYSX\source\geomutils\src;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\contact;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\common;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\convex;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\distance;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\sweep;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\gjk;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\intersection;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\mesh;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\hf;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\pcm;$(SolutionDir)dependencies\PHYSX\source\geomutils\src\ccd;$(SolutionDir)dependencies\PHYSX\source\lowlevel\api\include;$(SolutionDir)dependencies\PHYSX\source\lowlevel\software\include;$(SolutionDir)dependencies\PHYSX\source\lowlevel\common\include\pipeline;$(SolutionDir)dependencies\PHYSX\source\lowlevelaabb\include;$(SolutionDir)dependencies\PHYSX\source\lowleveldynamics\include;$(SolutionDir)dependencies\PHYSX\source\simulationcontroller\include;$(SolutionDir)dependencies\PHYSX\source\simulationcontroller\src;$(SolutionDir)dependencies\PHYSX\source\physxcooking\src;$(SolutionDir)dependencies\PHYSX\source\physxcooking\src\mesh;$(SolutionDir)dependencies\PHYSX\source\physxcooking\src\convex;$(SolutionDir)dependencies\PHYSX\source\scenequery\include;$(SolutionDir)dependencies\PHYSX\source\physxmetadata\core\include;$(SolutionDir)dependencies\PHYSX\source\immediatemode\include;$(SolutionDir)dependencies\PHYSX\source\pvd\include;$(SolutionDir)dependencies\PHYSX\source\foundation\include;$(SolutionDir)dependencies\GLFW\include;$(SolutionDir)dependencies\GLEW\include;$(SolutionDir)dependencies\GLM\include;$(SolutionDir)dependencies\ASSIMP\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\PhysXExtensions_static_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\PhysX_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\PhysXPvdSDK_static_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\PhysXVehicle_static_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\PhysXCharacterKinematic_static_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\PhysXCooking_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\PhysXCommon_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\SnippetUtils_static_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\SnippetRender_static_32.lib;$(SolutionDir)dependencies\PHYSX\lib\win.x86_32.vc141.mt\debug\PhysXFoundation_32.lib;opengl32.lib;$(SolutionDir)dependencies\GLEW\lib\Release\Win32\glew32.lib;$(SolutionDir)dependencies\GLFW\lib-vc2022\glfw3.lib;$(SolutionDir)dependencies\ASSIMP\Release\zlibd.lib;$(SolutionDir)dependencies\ASSIMP\Release\assimp-vc141-mtd.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="src\main.cpp" />
<ClCompile Include="src\RenderContext.cpp" />
<ClCompile Include="src\Shader.cpp" />
<ClCompile Include="src\Window.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="src\BaseParticleGenerator.h" />
<ClInclude Include="src\BasePlayer.h" />
<ClInclude Include="src\Camera.h" />
<ClInclude Include="src\CommonValues.h" />
<ClInclude Include="src\Controlls.h" />
<ClInclude Include="src\DirectionalLight.h" />
<ClInclude Include="src\FishObject.h" />
<ClInclude Include="src\FishObject2.h" />
<ClInclude Include="src\MapObject.h" />
<ClInclude Include="src\MovableObject.h" />
<ClInclude Include="src\FreeCamera.h" />
<ClInclude Include="src\FreePlayer.h" />
<ClInclude Include="src\GameObject.h" />
<ClInclude Include="src\Light.h" />
<ClInclude Include="src\Particle2dShader.h" />
<ClInclude Include="src\PointLightDebugPlayer.h" />
<ClInclude Include="src\PlayerCamera.h" />
<ClInclude Include="src\ShaderBase.h" />
<ClInclude Include="src\Particle2dGenerator.h" />
<ClInclude Include="src\MeshesData.h" />
<ClInclude Include="src\SkyboxShader.h" />
<ClInclude Include="src\SpotLightDebugPlayer.h" />
<ClInclude Include="src\SubmarinePlayer.h" />
<ClInclude Include="src\PointLight.h" />
<ClInclude Include="src\RenderContext.h" />
<ClInclude Include="src\RenderContextMaterial.h" />
<ClInclude Include="src\RenderContextMesh.h" />
<ClInclude Include="src\RenderContextTexture.h" />
<ClInclude Include="src\Renderer.h" />
<ClInclude Include="src\Scene.h" />
<ClInclude Include="src\Shader.h" />
<ClInclude Include="src\ShadowMap.h" />
<ClInclude Include="src\Skybox.h" />
<ClInclude Include="src\SpotLight.h" />
<ClInclude Include="src\StaticObject.h" />
<ClInclude Include="src\stb_image.h" />
<ClInclude Include="src\Utils.h" />
<ClInclude Include="src\Window.h" />
</ItemGroup>
<ItemGroup>
<None Include="shaders\directional_shadow_map.frag" />
<None Include="shaders\directional_shadow_map.vert" />
<None Include="shaders\particle_2D.frag" />
<None Include="shaders\particle_2D.vert" />
<None Include="shaders\shader.frag" />
<None Include="shaders\shader.vert" />
<None Include="shaders\skybox.frag" />
<None Include="shaders\skybox.vert" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,210 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Pliki źródłowe">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="GameObjects">
<UniqueIdentifier>{b1be100c-dc4d-4fc2-8c92-29f69c1652f3}</UniqueIdentifier>
</Filter>
<Filter Include="Core">
<UniqueIdentifier>{8c3373b4-d57c-41ba-adce-547249ee229a}</UniqueIdentifier>
</Filter>
<Filter Include="Core\Light">
<UniqueIdentifier>{57f371c7-eed6-432e-8e01-e688cf8e6d11}</UniqueIdentifier>
</Filter>
<Filter Include="Core\RenderContext">
<UniqueIdentifier>{6cb331ea-25fe-4963-b839-7ec38d822ceb}</UniqueIdentifier>
</Filter>
<Filter Include="Core\Camera">
<UniqueIdentifier>{7ef70e11-1086-4b3c-80dc-508448004465}</UniqueIdentifier>
</Filter>
<Filter Include="Core\Shader">
<UniqueIdentifier>{d3702387-2b85-4978-bb02-48bf17c65850}</UniqueIdentifier>
</Filter>
<Filter Include="Core\Shader\Shaders">
<UniqueIdentifier>{08c64978-4202-4609-b4c0-d7eb01288aa8}</UniqueIdentifier>
</Filter>
<Filter Include="Core\Window">
<UniqueIdentifier>{05884a19-0e66-4c2b-98b4-b9cd08906770}</UniqueIdentifier>
</Filter>
<Filter Include="Scenes">
<UniqueIdentifier>{78e9d554-af13-4a6b-9c59-d72b1a391666}</UniqueIdentifier>
</Filter>
<Filter Include="GameObjects\Players">
<UniqueIdentifier>{c2ebeaa7-dcab-423b-8be4-0096d8042add}</UniqueIdentifier>
</Filter>
<Filter Include="Core\Meshes">
<UniqueIdentifier>{e255b991-0d8b-4ef8-95ac-75c5d50a04bf}</UniqueIdentifier>
</Filter>
<Filter Include="Core\RenderContext\Renderer">
<UniqueIdentifier>{235d8cc0-f24a-46b7-aa9c-57300df98a55}</UniqueIdentifier>
</Filter>
<Filter Include="Core\Particles">
<UniqueIdentifier>{245b267e-8b90-496c-9691-6f2c4feebb5e}</UniqueIdentifier>
</Filter>
<Filter Include="GameObjects\Abstract">
<UniqueIdentifier>{2c850e04-0437-43b4-b46f-768ca0fe2db4}</UniqueIdentifier>
</Filter>
<Filter Include="Core\Utils">
<UniqueIdentifier>{275e04e4-c1ca-49f4-a291-0ef021c2c281}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="src\RenderContext.cpp">
<Filter>Core\RenderContext</Filter>
</ClCompile>
<ClCompile Include="src\Shader.cpp">
<Filter>Core\Shader</Filter>
</ClCompile>
<ClCompile Include="src\Window.cpp">
<Filter>Core\Window</Filter>
</ClCompile>
<ClCompile Include="src\main.cpp">
<Filter>Pliki źródłowe</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="src\stb_image.h">
<Filter>Pliki źródłowe</Filter>
</ClInclude>
<ClInclude Include="src\CommonValues.h">
<Filter>Core</Filter>
</ClInclude>
<ClInclude Include="src\DirectionalLight.h">
<Filter>Core\Light</Filter>
</ClInclude>
<ClInclude Include="src\Light.h">
<Filter>Core\Light</Filter>
</ClInclude>
<ClInclude Include="src\PointLight.h">
<Filter>Core\Light</Filter>
</ClInclude>
<ClInclude Include="src\SpotLight.h">
<Filter>Core\Light</Filter>
</ClInclude>
<ClInclude Include="src\RenderContext.h">
<Filter>Core\RenderContext</Filter>
</ClInclude>
<ClInclude Include="src\RenderContextMaterial.h">
<Filter>Core\RenderContext</Filter>
</ClInclude>
<ClInclude Include="src\RenderContextMesh.h">
<Filter>Core\RenderContext</Filter>
</ClInclude>
<ClInclude Include="src\RenderContextTexture.h">
<Filter>Core\RenderContext</Filter>
</ClInclude>
<ClInclude Include="src\Camera.h">
<Filter>Core\Camera</Filter>
</ClInclude>
<ClInclude Include="src\FreeCamera.h">
<Filter>Core\Camera</Filter>
</ClInclude>
<ClInclude Include="src\Shader.h">
<Filter>Core\Shader</Filter>
</ClInclude>
<ClInclude Include="src\PlayerCamera.h">
<Filter>Core\Camera</Filter>
</ClInclude>
<ClInclude Include="src\StaticObject.h">
<Filter>GameObjects</Filter>
</ClInclude>
<ClInclude Include="src\Window.h">
<Filter>Core\Window</Filter>
</ClInclude>
<ClInclude Include="src\Controlls.h">
<Filter>Core\Window</Filter>
</ClInclude>
<ClInclude Include="src\ShadowMap.h">
<Filter>Core\Light</Filter>
</ClInclude>
<ClInclude Include="src\Skybox.h">
<Filter>Core\Light</Filter>
</ClInclude>
<ClInclude Include="src\Scene.h">
<Filter>Scenes</Filter>
</ClInclude>
<ClInclude Include="src\Renderer.h">
<Filter>Core\RenderContext\Renderer</Filter>
</ClInclude>
<ClInclude Include="src\SubmarinePlayer.h">
<Filter>GameObjects\Players</Filter>
</ClInclude>
<ClInclude Include="src\FreePlayer.h">
<Filter>GameObjects\Players</Filter>
</ClInclude>
<ClInclude Include="src\PointLightDebugPlayer.h">
<Filter>GameObjects\Players</Filter>
</ClInclude>
<ClInclude Include="src\SpotLightDebugPlayer.h">
<Filter>GameObjects\Players</Filter>
</ClInclude>
<ClInclude Include="src\ShaderBase.h">
<Filter>Core\Shader</Filter>
</ClInclude>
<ClInclude Include="src\MeshesData.h">
<Filter>Core\Meshes</Filter>
</ClInclude>
<ClInclude Include="src\Particle2dShader.h">
<Filter>Core\Shader</Filter>
</ClInclude>
<ClInclude Include="src\Particle2dGenerator.h">
<Filter>Core\Particles</Filter>
</ClInclude>
<ClInclude Include="src\BasePlayer.h">
<Filter>GameObjects\Abstract</Filter>
</ClInclude>
<ClInclude Include="src\GameObject.h">
<Filter>GameObjects\Abstract</Filter>
</ClInclude>
<ClInclude Include="src\FishObject.h">
<Filter>GameObjects</Filter>
</ClInclude>
<ClInclude Include="src\MovableObject.h">
<Filter>GameObjects\Abstract</Filter>
</ClInclude>
<ClInclude Include="src\BaseParticleGenerator.h">
<Filter>Core\Particles</Filter>
</ClInclude>
<ClInclude Include="src\Utils.h">
<Filter>Core\Utils</Filter>
</ClInclude>
<ClInclude Include="src\MapObject.h">
<Filter>GameObjects</Filter>
</ClInclude>
<ClInclude Include="src\SkyboxShader.h">
<Filter>Core\Shader</Filter>
</ClInclude>
<ClInclude Include="src\FishObject2.h">
<Filter>GameObjects</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<None Include="shaders\directional_shadow_map.frag">
<Filter>Core\Shader\Shaders</Filter>
</None>
<None Include="shaders\directional_shadow_map.vert">
<Filter>Core\Shader\Shaders</Filter>
</None>
<None Include="shaders\shader.frag">
<Filter>Core\Shader\Shaders</Filter>
</None>
<None Include="shaders\shader.vert">
<Filter>Core\Shader\Shaders</Filter>
</None>
<None Include="shaders\skybox.vert">
<Filter>Core\Shader\Shaders</Filter>
</None>
<None Include="shaders\skybox.frag">
<Filter>Core\Shader\Shaders</Filter>
</None>
<None Include="shaders\particle_2D.vert">
<Filter>Core\Shader\Shaders</Filter>
</None>
<None Include="shaders\particle_2D.frag">
<Filter>Core\Shader\Shaders</Filter>
</None>
</ItemGroup>
</Project>

Binary file not shown.

Binary file not shown.

BIN
Grk-Projekt/PhysXDevice.dll Normal file

Binary file not shown.

Binary file not shown.

BIN
Grk-Projekt/PhysXGpu_32.dll Normal file

Binary file not shown.

BIN
Grk-Projekt/PhysX_32.dll Normal file

Binary file not shown.

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<Project>
<ProjectOutputs>
<ProjectOutput>
<FullPath>C:\Users\kubik\source\repos\Grk-Projekt\Release\Grk-Projekt.exe</FullPath>
</ProjectOutput>
</ProjectOutputs>
<ContentFiles />
<SatelliteDlls />
<NonRecipeFileRefs />
</Project>

Binary file not shown.

Binary file not shown.

BIN
Grk-Projekt/freeglut.dll Normal file

Binary file not shown.

BIN
Grk-Projekt/glew32.dll Normal file

Binary file not shown.

BIN
Grk-Projekt/glfw3.dll Normal file

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 MiB

Binary file not shown.

BIN
Grk-Projekt/models/cone.fbx Normal file

Binary file not shown.

BIN
Grk-Projekt/models/cube.fbx Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

View File

@ -0,0 +1,13 @@
# Blender MTL File: 'None'
# Material Count: 1
newmtl Material.001
Ns 225.000000
Ka 1.000000 1.000000 1.000000
Kd 0.800000 0.800000 0.800000
Ks 0.500000 0.500000 0.500000
Ke 0.000000 0.000000 0.000000
Ni 1.450000
d 1.000000
illum 2
map_Kd particle2.png

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 151 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 MiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 352 KiB

Binary file not shown.

View File

@ -0,0 +1,5 @@
#version 330
void main() {
}

View File

@ -0,0 +1,12 @@
#version 330
layout (location = 0) in vec3 pos;
uniform mat4 model;
uniform mat4 directionalLightTransform;
void main(){
gl_Position = directionalLightTransform * model * vec4(pos, 1.0);
}

View File

@ -0,0 +1,37 @@
#version 330 core
out vec4 FragColor;
in vec2 TexCords;
in vec4 ParticleColor;
uniform sampler2D theTexture;
uniform bool showFog;
uniform vec3 fogColor;
float linearizeDepth(float depth, float nearPlane, float farPlane)
{
return (2.0 * nearPlane * farPlane) / (farPlane + nearPlane - (depth * 2.0 - 1.0) * (farPlane - nearPlane));
}
float logisticDepth(float depth, float nearPlane, float farPlane, float steppness, float offeset)
{
float zVal = linearizeDepth(depth, nearPlane, farPlane);
return (1 / (1 + exp(-steppness * (zVal - offeset))));
}
void main()
{
if (showFog)
{
float d = logisticDepth(gl_FragCoord.z, 0.1, 100,0.05f,5.0f);
FragColor = texture(theTexture, TexCords) * (ParticleColor * (1.0 - d) + vec4(d * fogColor, 1.0));
}
else
{
FragColor = texture(theTexture, TexCords) * ParticleColor;
}
}

View File

@ -0,0 +1,23 @@
#version 330 core
layout (location = 0) in vec3 vertex_position;
layout (location = 1) in vec4 position; // x, y, z, size
layout (location = 2) in vec4 color; // x, y, z
uniform mat4 view;
uniform mat4 projection;
out vec2 TexCords;
out vec4 ParticleColor;
void main()
{
float size = position.w;
vec4 position_viewspace = view * vec4(position.xyz, 1.0);
TexCords = vertex_position.xy - vec2(0.5);
ParticleColor = color;
position_viewspace.xy += size * TexCords;
gl_Position = projection * position_viewspace;
}

View File

@ -0,0 +1,221 @@
#version 330
struct Light
{
vec3 colour;
float ambientIntensity;
float diffuseIntensity;
};
struct DirectionalLight
{
Light base;
vec3 direction;
};
struct PointLight
{
Light base;
vec3 position;
float constant;
float linear;
float exponent;
};
struct SpotLight
{
PointLight base;
vec3 direction;
float edge;
};
struct Material
{
sampler2D diffuseTexture;
bool useDiffuseTexture;
vec3 objectColor;
float specularIntensity;
float shininess;
};
const int MAX_POINT_LIGHTS = 10;
const int MAX_SPOT_LIGHTS = 10;
in vec2 TexCoord;
in vec3 Normal;
in vec3 FragPos;
in vec4 DirectionalLightSpacePos;
out vec4 FragColor;
uniform int pointLightCount;
uniform int spotLightCount;
uniform DirectionalLight directionalLight;
uniform PointLight pointLights[MAX_POINT_LIGHTS];
uniform SpotLight spotLights[MAX_SPOT_LIGHTS];
uniform sampler2D directionalShadowMap;
uniform Material material;
uniform vec3 eyePosition;
uniform bool showFog;
uniform vec3 fogColor;
float CalcDirectionalShadowFactor(DirectionalLight light)
{
vec3 projCords = DirectionalLightSpacePos.xyz / DirectionalLightSpacePos.w;
projCords = (projCords * 0.5) + 0.5;
float currentDepth = projCords.z;
vec3 normal = normalize(Normal);
vec3 lightDir = normalize(light.direction);
float bias = max(0.05 * (1 - dot(normal, lightDir)), 0.005);
float shadow = 0.0;
vec2 texelSize = 1.0 / textureSize(directionalShadowMap, 0);
for (int x = -1; x <= 1; x++)
{
for (int y = -1; y <= 1; y++)
{
float pcfDepth = texture(directionalShadowMap, projCords.xy + vec2(x, y) * texelSize).r;
shadow += currentDepth - bias > pcfDepth ? 1.0 : 0.0;
}
}
shadow /= 9.0;
if (projCords.z > 1.0) {
shadow = 0.0;
}
return shadow;
}
vec4 CalcLightByDirection(Light light, vec3 direction, float shadowFactor)
{
vec4 ambientColour = vec4(light.colour, 1.0f) * light.ambientIntensity;
float diffuseFactor = max(dot(normalize(Normal), normalize(direction)), 0.0f);
vec4 diffuseColour = vec4(light.colour * light.diffuseIntensity * diffuseFactor, 1.0f);
vec4 specularColour = vec4(0, 0, 0, 0);
if(diffuseFactor > 0.0f)
{
vec3 fragToEye = normalize(eyePosition - FragPos);
vec3 reflectedVertex = normalize(reflect(direction, normalize(Normal)));
float specularFactor = dot(fragToEye, reflectedVertex);
if(specularFactor > 0.0f)
{
specularFactor = pow(specularFactor, material.shininess);
specularColour = vec4(light.colour * material.specularIntensity * specularFactor, 1.0f);
}
}
return (ambientColour + (1.0 - shadowFactor) * (diffuseColour + specularColour));
}
vec4 CalcDirectionalLight()
{
float shadowFactor = CalcDirectionalShadowFactor(directionalLight);
return CalcLightByDirection(directionalLight.base, directionalLight.direction, shadowFactor);
}
vec4 CalcPointLight(PointLight pLight)
{
vec3 direction = FragPos - pLight.position;
float distance = length(direction);
direction = normalize(direction);
vec4 colour = CalcLightByDirection(pLight.base, direction, 0.0);
float attenuation = pLight.exponent * distance * distance +
pLight.linear * distance +
pLight.constant;
return (colour / attenuation);
}
vec4 CalcSpotLight(SpotLight sLight)
{
vec3 rayDirection = normalize(FragPos - sLight.base.position);
float slFactor = dot(rayDirection, sLight.direction);
if(slFactor > sLight.edge)
{
vec4 colour = CalcPointLight(sLight.base);
return colour * (1.0f - (1.0f - slFactor)*(1.0f/(1.0f - sLight.edge)));
} else {
return vec4(0, 0, 0, 0);
}
}
vec4 CalcPointLights()
{
vec4 totalColour = vec4(0, 0, 0, 0);
for(int i = 0; i < pointLightCount; i++)
{
totalColour += CalcPointLight(pointLights[i]);
}
return totalColour;
}
vec4 CalcSpotLights()
{
vec4 totalColour = vec4(0, 0, 0, 0);
for(int i = 0; i < spotLightCount; i++)
{
totalColour += CalcSpotLight(spotLights[i]);
}
return totalColour;
}
float linearizeDepth(float depth, float nearPlane, float farPlane)
{
return (2.0 * nearPlane * farPlane) / (farPlane + nearPlane - (depth * 2.0 - 1.0) * (farPlane - nearPlane));
}
float logisticDepth(float depth, float nearPlane, float farPlane, float steppness, float offeset)
{
float zVal = linearizeDepth(depth, nearPlane, farPlane);
return (1 / (1 + exp(-steppness * (zVal - offeset))));
}
void main()
{
vec4 lightColour = CalcDirectionalLight();
lightColour += CalcPointLights();
lightColour += CalcSpotLights();
vec4 resultColor;
if (material.useDiffuseTexture)
{
resultColor = texture(material.diffuseTexture, TexCoord) * lightColour;
}
else
{
resultColor = vec4(material.objectColor, 1.0) * lightColour;
}
if (showFog)
{
float d = logisticDepth(gl_FragCoord.z, 0.1, 100,0.05f,5.0f);
FragColor = resultColor * (1.0 - d) + vec4(d * fogColor, 1.0);
}
else
{
FragColor = resultColor;
}
}

View File

@ -0,0 +1,26 @@
#version 330
layout (location = 0) in vec3 pos;
layout (location = 1) in vec2 tex;
layout (location = 2) in vec3 norm;
out vec2 TexCoord;
out vec3 Normal;
out vec3 FragPos;
out vec4 DirectionalLightSpacePos;
uniform mat4 model;
uniform mat4 projection;
uniform mat4 view;
uniform mat4 directionalLightTransform;
void main()
{
gl_Position = projection * view * model * vec4(pos, 1.0);
DirectionalLightSpacePos = directionalLightTransform * model * vec4(pos, 1.0);
TexCoord = tex;
Normal = mat3(transpose(inverse(model))) * norm;
FragPos = (model * vec4(pos, 1.0)).xyz;
}

View File

@ -0,0 +1,14 @@
#version 410 core
uniform vec3 objectColor;
uniform vec3 lightDir;
in vec3 interpNormal;
void main()
{
vec3 normal = normalize(interpNormal);
float ambient = 0.2;
float diffuse = max(dot(normal, -lightDir), 0.0);
gl_FragColor = vec4(objectColor * (ambient + (1-ambient) * diffuse), 1.0);
}

View File

@ -0,0 +1,16 @@
#version 410 core
layout(location = 0) in vec3 vertexPosition;
layout(location = 1) in vec2 vertexTexCoord;
layout(location = 2) in vec3 vertexNormal;
uniform mat4 modelViewProjectionMatrix;
uniform mat4 modelMatrix;
out vec3 interpNormal;
void main()
{
gl_Position = modelViewProjectionMatrix * vec4(vertexPosition, 1.0);
interpNormal = (modelMatrix * vec4(vertexNormal, 0.0)).xyz;
}

View File

@ -0,0 +1,17 @@
#version 410 core
uniform sampler2D textureSampler;
uniform vec3 lightDir;
in vec3 interpNormal;
in vec2 interpTexCoord;
void main()
{
vec2 modifiedTexCoord = vec2(interpTexCoord.x, 1.0 - interpTexCoord.y); // Poprawka dla tekstur Ziemi, ktore bez tego wyswietlaja sie 'do gory nogami'
vec3 color = texture2D(textureSampler, modifiedTexCoord).rgb;
vec3 normal = normalize(interpNormal);
float ambient = 0.2;
float diffuse = max(dot(normal, -lightDir), 0.0);
gl_FragColor = vec4(color * (ambient + (1-ambient) * diffuse), 1.0);
}

View File

@ -0,0 +1,18 @@
#version 410 core
layout(location = 0) in vec3 vertexPosition;
layout(location = 1) in vec2 vertexTexCoord;
layout(location = 2) in vec3 vertexNormal;
uniform mat4 modelViewProjectionMatrix;
uniform mat4 modelMatrix;
out vec3 interpNormal;
out vec2 interpTexCoord;
void main()
{
gl_Position = modelViewProjectionMatrix * vec4(vertexPosition, 1.0);
interpNormal = (modelMatrix * vec4(vertexNormal, 0.0)).xyz;
interpTexCoord = vertexTexCoord;
}

View File

@ -0,0 +1,23 @@
#version 330
in vec3 TexCords;
out vec4 colour;
uniform samplerCube skybox;
uniform vec3 eyePosition;
uniform bool showFog;
uniform vec3 fogColor;
void main(){
if (showFog)
{
colour = mix(texture(skybox, TexCords), vec4(fogColor, 1.0), 0.93);
}
else
{
colour = texture(skybox, TexCords);
}
}

View File

@ -0,0 +1,13 @@
#version 330
layout (location = 0) in vec3 pos;
out vec3 TexCords;
uniform mat4 projection;
uniform mat4 view;
void main(){
TexCords = pos;
gl_Position = projection * view * vec4(pos, 1.0);
}

2172
Grk-Projekt/sphere.txt Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,101 @@
#pragma once
#include <algorithm>
#include <functional>
#include "GL/glew.h"
#include "GLM/glm.hpp"
struct ParticleUpdateData
{
glm::vec4 color;
glm::vec3 speed;
float size;
};
struct Particle
{
glm::vec3 position = glm::vec3(0.0f, 0.0f, 0.0f);
glm::vec4 color = glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);
glm::vec3 speed = glm::vec3(0.0f, 0.0f, 0.0f);
float lifetime = 0.0f;
float size = 0.2f;
float cameradistance = -1.0f;
bool operator<(const Particle& that) const {
return this->cameradistance > that.cameradistance;
}
};
class BaseParticleGenerator
{
public:
BaseParticleGenerator() {}
virtual void Init(GLuint _maxParticles, ParticleUpdateData(*getData)()) = 0;
virtual void Update(const float dt, glm::vec3* cameraPos) = 0;
virtual void Draw(glm::mat4* view, glm::mat4* projection, bool showFog, glm::vec3* fogColor) = 0;
void SetLifetime(float life) {
startLifetime = life;
}
void SetStartPosition(glm::vec3 _startPos) {
startPos = _startPos;
}
~BaseParticleGenerator()
{
if (PBO != 0) { glDeleteBuffers(1, &PBO); PBO = 0; }
if (VBO != 0) { glDeleteBuffers(1, &VBO); VBO = 0; }
if (VAO != 0) { glDeleteVertexArrays(1, &VAO); VAO = 0; }
delete[] particles;
delete[] particleBufferData;
}
protected:
std::function<ParticleUpdateData()> updateCallback;
GLuint maxParticles = 0;
GLuint particlesCount = 0;
GLuint lastUsedParticle = 0;
glm::vec3 startPos = glm::vec3(0.0f, 0.0f, 0.0f);
float startLifetime = 5.0f;
Particle* particles = nullptr;
float* particleBufferData = nullptr;
GLuint VAO = 0;
GLuint VBO = 0;
GLuint IBO = 0;
GLuint PBO = 0;
int FindUnusedParticle() {
for (int i = lastUsedParticle; i < maxParticles; i++) {
if (particles[i].lifetime < 0) {
lastUsedParticle = i;
return i;
}
}
for (int i = 0; i < lastUsedParticle; i++) {
if (particles[i].lifetime < 0) {
lastUsedParticle = i;
return i;
}
}
return 0;
}
float GetRandomFloat(float min, float max)
{
return min + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (max - min)));
}
void SortParticles() {
std::sort(&particles[0], &particles[maxParticles]);
}
};

View File

@ -0,0 +1,29 @@
#pragma once
#include "GameObject.h"
#include "Camera.h"
class BasePlayer : public GameObject
{
public:
BasePlayer(RenderContext* _renderContext) : GameObject(_renderContext) {}
virtual void Init() = 0;
virtual void Update(float dt) = 0;
virtual void HandleControlls(Controlls* controlls, GLfloat deltaTime) = 0;
virtual Camera* GetCamera() = 0;
protected:
glm::vec3 playerPos = glm::vec3(0, 0, 0);
float playerRotation = glm::radians(0.0f);
glm::vec3 forward;
glm::vec3 side;
glm::vec3 worldUp = glm::vec3(0, 1, 0);
void UpdateForwardDir()
{
forward = normalize(glm::vec3(modelMatrix[2]));
side = glm::normalize(glm::cross(forward, glm::vec3(0, -1, 0)));
}
};

87
Grk-Projekt/src/Camera.h Normal file
View File

@ -0,0 +1,87 @@
#pragma once
#include <GL\glew.h>
#include <GLFW\glfw3.h>
#include <GLM\glm.hpp>
#include <GLM\ext.hpp>
#include "Controlls.h"
class Camera
{
public:
Camera(glm::vec3 startPosition, GLfloat startMoveSpeed, GLfloat startTurnSpeed)
{
_position = startPosition;
_moveSpeed = startMoveSpeed;
_turnSpeed = startTurnSpeed;
_front = glm::vec3(0.0f, 0.0f, -1.0f);
Update();
}
virtual void HandleControlls(Controlls* controlls, GLfloat deltaTime) = 0;
virtual glm::mat4* CalculateViewMatrix() = 0;
glm::vec3* GetCameraPosition(){ return &_position; }
glm::vec3* GetCameraDirection()
{
_direction = glm::normalize(_front);
return &_direction;
}
glm::vec3* GetCameraSideDirection()
{
_sideDirection = glm::normalize(_right);
return &_sideDirection;
}
glm::mat4* CreatePerspectiveMatrix()
{
const float frustumScale = 1.0f;
glm::mat4 perspective(1.0f);
perspective[0][0] = frustumScale;
perspective[1][1] = frustumScale;
perspective[2][2] = (_zFar + _zNear) / (_zNear - _zFar);
perspective[3][2] = (2 * _zFar * _zNear) / (_zNear - _zFar);
perspective[2][3] = -1;
perspective[3][3] = 0;
_perspectiveMatrix = perspective;
return &_perspectiveMatrix;
}
~Camera() {};
protected:
glm::vec3 _position;
glm::vec3 _direction;
glm::vec3 _sideDirection;
glm::mat4 _viewMatrix;
glm::mat4 _perspectiveMatrix;
glm::vec3 _front{};
glm::vec3 _up{};
glm::vec3 _right{};
glm::vec3 _worldUp = glm::vec3(0, 1, 0);
GLfloat _yaw;
GLfloat _pitch;
GLfloat _moveSpeed;
GLfloat _turnSpeed;
float _zNear = 0.01f;
float _zFar = 100.0f;
void Update()
{
_front.x = cos(glm::radians(_yaw)) * cos(glm::radians(_pitch));
_front.y = sin(glm::radians(_pitch));
_front.z = sin(glm::radians(_yaw)) * cos(glm::radians(_pitch));
_front = glm::normalize(_front);
_right = glm::normalize(glm::cross(_front, _worldUp));
//_up = glm::normalize(glm::cross(_right, _front));
}
};

View File

@ -0,0 +1,6 @@
#pragma once
#include "stb_image.h"
const int MAX_POINT_LIGHTS = 10;
const int MAX_SPOT_LIGHTS = 10;

View File

@ -0,0 +1,57 @@
#pragma once
enum ScrollDirection {
UP,
DOWN,
NONE
};
class Controlls
{
public:
Controlls()
{
for (size_t i = 0; i < 1024; i++)
{
keys[i] = false;
}
}
bool keys[1024];
bool leftMouseButton = false;
bool rightMouseButton = false;
ScrollDirection GetScrollDirection() {
if (scrollHandled) {
return ScrollDirection::NONE;
}
scrollHandled = true;
return scrollDirection;
}
void SetScrollDirection(ScrollDirection _scrollDirection) {
scrollHandled = false;
scrollDirection = _scrollDirection;
}
float GetMouseXChange() {
float theChange = mouseXChange;
mouseXChange = 0.0f;
return theChange;
}
void SetMouseXChange(float change) {
mouseXChange = change;
}
float GetMouseYChange() {
float theChange = mouseYChange;
mouseYChange = 0.0f;
return theChange;
}
void SetMouseYChange(float change) {
mouseYChange = change;
}
private:
float mouseXChange = 0;
float mouseYChange = 0;
ScrollDirection scrollDirection = ScrollDirection::NONE;
bool scrollHandled = false;
};

View File

@ -0,0 +1,37 @@
#pragma once
#include "Light.h"
class DirectionalLight : public Light
{
public:
DirectionalLight() : Light()
{
direction = glm::vec3(0.0f, -1.0f, 0.0f);
}
DirectionalLight(
GLfloat red, GLfloat green, GLfloat blue,
GLfloat aIntensity, GLfloat dIntensity,
GLfloat xDir, GLfloat yDir, GLfloat zDir,
GLfloat shadowWidth, GLfloat shadowHeight
) : Light(red, green, blue, aIntensity, dIntensity, shadowWidth, shadowHeight)
{
direction = glm::vec3(xDir, yDir, zDir);
lightProj = glm::ortho(-20.0f, 20.0f, -20.0f, 20.0f, 0.1f, 100.0f);
}
glm::mat4* CalculateLightTransform()
{
lightTransform = lightProj * glm::lookAt(-direction, glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
return &lightTransform;
}
glm::vec3* GetDirection() { return &direction; }
~DirectionalLight() {}
private:
glm::vec3 direction;
glm::mat4 lightTransform;
};

View File

@ -0,0 +1,88 @@
#pragma once
#include "MovableObject.h"
#include "GLM/ext.hpp"
#include "StaticObject.h"
#include "GLM/gtx/quaternion.hpp"
class FishObject : public MovableObject
{
public:
FishObject(RenderContext* _renderContext) : MovableObject(nullptr) {
nemo = new RenderContext("models/fish_1.fbx");
dori = new RenderContext("models/fish_2.fbx");
auto path = std::vector<glm::vec3>({
glm::vec3(-16.995449f, 10.913057f, -88.997505f),
glm::vec3(15.837612f, 7.829714f, -89.331902f),
glm::vec3(13.922138f, 7.829714f, -73.000229f),
glm::vec3(12.657385f, 4.166675f, -58.502914f),
glm::vec3(13.922138f, 3.914080f, -54.333618f),
glm::vec3(11.657133f, 7.160716f, -44.336731f),
glm::vec3(10.408125f, 8.577533f, -31.086113f),
glm::vec3(6.906233f, 9.994769f, -16.086876f),
glm::vec3(3.073606f, 10.911212f, -2.419884f),
glm::vec3(6.742506f, 11.742969f, 15.580986f),
glm::vec3(12.907820f, 13.824344f, 28.914879f),
glm::vec3(22.411451f, 13.824344f, 34.249733f),
glm::vec3(33.662903f, 8.574481f, 35.918205f),
glm::vec3(45.497925f, 8.574481f, 42.669228f),
glm::vec3(58.166840f, 3.242450f, 57.918251f),
glm::vec3(74.839432f, -0.004163f, 76.917732f)
});
for (size_t i = 0; i < 60; i++)
{
if (i % 3 == 0)
{
auto child = new StaticObject(dori);
child->Translate(GetPoint());
child->Scale(glm::vec3(GetRandomFloat(0.05, 0.2)));
AddChild(child);
}
else
{
auto child = new StaticObject(nemo);
child->Translate(GetPoint());
child->Scale(glm::vec3(GetRandomFloat(0.05, 0.2)));
AddChild(child);
}
}
initKeyRoation(path);
}
void Init() override { }
void Update(float dt) override
{
auto model = animationMatrix(glfwGetTime());
model *= glm::scale(glm::vec3(0.07f));
modelMatrix = model;
}
private:
RenderContext* nemo;
RenderContext* dori;
glm::vec3 GetPoint()
{
float x, y, z, d;
do {
x = GetRandomFloat(-100, 100);
y = GetRandomFloat(-100, 100);
z = GetRandomFloat(-100, 100);
d = x * x + y * y + z * z;
} while (d > 1000.0f);
return glm::vec3(x, y, z);
}
float GetRandomFloat(float min, float max)
{
return min + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (max - min)));
}
};

View File

@ -0,0 +1,53 @@
#pragma once
#include "MovableObject.h"
#include "GLM/ext.hpp"
#include "StaticObject.h"
#include "GLM/gtx/quaternion.hpp"
class FishObject2 : public MovableObject
{
public:
FishObject2(RenderContext* _renderContext) : MovableObject(nullptr) {
shark = new RenderContext("models/shark.fbx");
auto path = std::vector<glm::vec3>({
glm::vec3(62.500820f, 1.417747f, -98.333572f),
glm::vec3(62.500820f, 4.667355f, -85.416382f),
glm::vec3(56.167622f, 6.001202f, -68.582428f),
glm::vec3(51.833858f, 8.415218f, -53.750656f),
glm::vec3(44.332905f, 15.082470f, -42.743233f),
glm::vec3(35.497723f, 21.334339f, -31.993111f),
glm::vec3(22.417126f, 26.833759f, -34.575089f),
glm::vec3(9.250202f, 28.668705f, -29.993065f),
glm::vec3(-1.828823f, 32.168156f, -28.073357f),
glm::vec3(-14.995632f, 34.001041f, -25.155647f),
glm::vec3(-29.245510f, 34.001041f, -25.322655f),
glm::vec3(-43.078671f, 25.001942f, -26.821907f),
glm::vec3(-60.244274f, 13.088566f, -21.651924f),
glm::vec3(-73.994049f, 2.755619f, -5.652016f),
glm::vec3(- 86.330399f, -4.247936f, -1.068123f)
});
auto child = new StaticObject(shark);
child->Scale(glm::vec3(0.2f));
child->Rotate(-90.0f, glm::vec3(0, 1, 0));
AddChild(child);
initKeyRoation(path);
}
void Init() override { }
void Update(float dt) override
{
auto model = animationMatrix(glfwGetTime());
model *= glm::scale(glm::vec3(0.03f));
modelMatrix = model;
}
private:
RenderContext* shark;
};

View File

@ -0,0 +1,76 @@
#pragma once
#include "Camera.h"
class FreeCamera : public Camera
{
public:
FreeCamera() : Camera(glm::vec3(0, 0, 0), 5.0f, 5.0f) {}
FreeCamera(glm::vec3 startPosition, glm::vec3 startUp, GLfloat startYaw, GLfloat startPitch,
GLfloat startMoveSpeed, GLfloat startTurnSpeed) :
Camera(startPosition, startMoveSpeed, startTurnSpeed)
{
_up = startUp;
_yaw = startYaw;
_pitch = startPitch;
}
void HandleControlls(Controlls* controlls, GLfloat deltaTime) override
{
GLfloat velocity = _moveSpeed * deltaTime;
if (controlls->keys[GLFW_KEY_LEFT_SHIFT])
{
velocity *= 2;
}
if (controlls->keys[GLFW_KEY_W])
{
_position += _front * velocity;
}
if (controlls->keys[GLFW_KEY_S])
{
_position -= _front * velocity;
}
if (controlls->keys[GLFW_KEY_A])
{
_position -= _right * velocity;
}
if (controlls->keys[GLFW_KEY_D])
{
_position += _right * velocity;
}
if (controlls->keys[GLFW_KEY_SPACE])
{
_position += _up * velocity;
}
if (controlls->keys[GLFW_KEY_LEFT_CONTROL])
{
_position -= _up * velocity;
}
float xChange = controlls->GetMouseXChange() * _turnSpeed;
float yChange = controlls->GetMouseYChange() * _turnSpeed;
_yaw += xChange;
_pitch += yChange;
if (_pitch > 89.0f)
{
_pitch = 89.0f;
}
if (_pitch < -89.0f)
{
_pitch = -89.0f;
}
Update();
}
glm::mat4* CalculateViewMatrix() override
{
_viewMatrix = glm::lookAt(_position, _position + _front, _up);
return &_viewMatrix;
}
~FreeCamera() = default;
};

View File

@ -0,0 +1,34 @@
#pragma once
#include "BasePlayer.h"
#include "FreeCamera.h"
class FreePlayer : public BasePlayer
{
public:
FreePlayer() : BasePlayer(nullptr)
{
camera = new FreeCamera(
glm::vec3(0.0f, 0.0f, 0.0f),
glm::vec3(0.0f, 1.0f, 0.0f),
-90.0f, 0.0f, 10.0f, 0.1f
);
}
void Init() override {}
void Update(float dt) override {}
Camera* GetCamera() override
{
return camera;
}
void HandleControlls(Controlls* controlls, GLfloat deltaTime) override
{
camera->HandleControlls(controlls, deltaTime);
}
private:
FreeCamera* camera = nullptr;
};

View File

@ -0,0 +1,99 @@
#pragma once
#include <vector>
#include "RenderContext.h"
#include "Shader.h"
#include "BaseParticleGenerator.h"
class GameObject
{
public:
GameObject(){};
GameObject(RenderContext* _renderContext)
{
renderContext = _renderContext;
};
virtual void Init() = 0;
virtual void Update(float dt) = 0;
// Dodaj ca³e u¿ywane oœwietlenie przez rodzica i wszystkich potomków do sceny
void SetSceneLights(std::vector<SpotLight*>& _spotLights, std::vector<PointLight*>& _pointLights)
{
for (SpotLight* spotLight : spotLights) {
_spotLights.push_back(spotLight);
}
for (PointLight* pointLight : pointLights) {
_pointLights.push_back(pointLight);
}
for (auto child: childs)
{
child->SetSceneLights(_spotLights, _pointLights);
}
}
void SetParticleGenerators(std::vector<BaseParticleGenerator*>& _particleGenerators)
{
for (BaseParticleGenerator* generator : particleGenerators) {
_particleGenerators.push_back(generator);
}
for (auto child : childs)
{
child->SetParticleGenerators(_particleGenerators);
}
}
void Render(Shader* shader, glm::mat4* parentMatrix = nullptr)
{
if (renderContext == nullptr && childs.size() == 0) return;
if (renderContext != nullptr)
{
if (parentMatrix != nullptr) {
renderContext->Render(shader, *parentMatrix * modelMatrix);
}
else {
renderContext->Render(shader, modelMatrix);
}
}
for (auto child : childs)
{
child->Render(shader, &modelMatrix);
}
}
void AddChild(GameObject* child) {
childs.push_back(child);
}
void Translate(glm::vec3 val) {
modelMatrix = glm::translate(modelMatrix, val);
}
void Scale(glm::vec3 val) {
modelMatrix = glm::scale(modelMatrix, val);
}
void Rotate(float angle, glm::vec3 orinet) {
modelMatrix = glm::rotate(modelMatrix, glm::radians(angle), orinet);
}
Node* FindNode(const char* name) {
return renderContext->FindNode(name);
}
Material* FindMaterial(const char* name) {
return renderContext->FindMaterial(name);
}
protected:
RenderContext* renderContext = nullptr;
glm::mat4 modelMatrix = glm::mat4(1.0f);
std::vector<GameObject*> childs{};
std::vector<SpotLight*> spotLights{};
std::vector<PointLight*> pointLights{};
std::vector<BaseParticleGenerator*> particleGenerators{};
};

48
Grk-Projekt/src/Light.h Normal file
View File

@ -0,0 +1,48 @@
#pragma once
#include <GL\glew.h>
#include <GLM\glm.hpp>
#include <GLM\ext.hpp>
#include "ShadowMap.h"
class Light
{
public:
Light()
{
colour = glm::vec3(1.0f, 1.0f, 1.0f);
ambientIntensity = 1.0f;
diffuseIntensity = 0.0f;
}
Light(
GLfloat red, GLfloat green, GLfloat blue,
GLfloat aIntensity, GLfloat dIntensity,
GLfloat shadowWidth, GLfloat shadowHeight
)
{
colour = glm::vec3(red, green, blue);
ambientIntensity = aIntensity;
diffuseIntensity = dIntensity;
shadowMap = new ShadowMap();
shadowMap->Init(shadowWidth, shadowHeight);
}
GLfloat GetAmbientIntenisty() { return ambientIntensity; }
GLfloat GetDiffuseIntensity() { return diffuseIntensity; }
glm::vec3* GetColour() { return &colour; };
ShadowMap* GetShadowMap() { return shadowMap; }
~Light() {}
protected:
glm::vec3 colour;
GLfloat ambientIntensity;
GLfloat diffuseIntensity;
glm::mat4 lightProj;
ShadowMap* shadowMap;
};

102
Grk-Projekt/src/MapObject.h Normal file
View File

@ -0,0 +1,102 @@
#pragma once
#include "Utils.h"
#include "GameObject.h"
#include "Particle2dGenerator.h"
class MapObject : public GameObject
{
public:
MapObject(RenderContext* _renderContext) : GameObject(_renderContext) {
generator2d = new Particle2dGenerator("Textures/particle.png");
generator2d_2 = new Particle2dGenerator("Textures/particle.png");
generator2d_3 = new Particle2dGenerator("Textures/particle.png");
particleGenerators.push_back(generator2d);
particleGenerators.push_back(generator2d_2);
particleGenerators.push_back(generator2d_3);
}
void Init() override {
generator2d->Init(1000, []() {
auto data = ParticleUpdateData();
float spread = 1.5f;
glm::vec3 maindir = glm::vec3(0.0f, 5.0f, 0.0f);
glm::vec3 randomdir = glm::vec3(
GetRandomFloat(-1.0f, 1.0f),
GetRandomFloat(-1.0f, 1.0f),
GetRandomFloat(-1.0f, 1.0f)
);
data.speed = maindir + randomdir * spread;
data.color = glm::vec4(
GetRandomFloat(0.0f, 1.0f),
GetRandomFloat(0.0f, 1.0f),
GetRandomFloat(0.0f, 1.0f),
1.0f
);
data.size = GetRandomFloat(0.1f, 0.3f);
return data;
});
generator2d->SetStartPosition(glm::vec3(19.758930f, 16.098251f, 27.347736f));
generator2d_2->Init(500, []() {
auto data = ParticleUpdateData();
float spread = 1.5f;
glm::vec3 maindir = glm::vec3(0.0f, 5.0f, 0.0f);
glm::vec3 randomdir = glm::vec3(
GetRandomFloat(-1.0f, 1.0f),
GetRandomFloat(-1.0f, 1.0f),
GetRandomFloat(-1.0f, 1.0f)
);
data.speed = maindir + randomdir * spread;
data.color = glm::vec4(
GetRandomFloat(0.0f, 1.0f),
GetRandomFloat(0.0f, 1.0f),
GetRandomFloat(0.0f, 1.0f),
1.0f
);
data.size = GetRandomFloat(0.1f, 0.3f);
return data;
});
generator2d_2->SetStartPosition(glm::vec3(14.680309f, 13.248291f, 51.235180f));
generator2d_3->Init(300, []() {
auto data = ParticleUpdateData();
float spread = 1.5f;
glm::vec3 maindir = glm::vec3(0.0f, 5.0f, 0.0f);
glm::vec3 randomdir = glm::vec3(
GetRandomFloat(-1.0f, 1.0f),
GetRandomFloat(-1.0f, 1.0f),
GetRandomFloat(-1.0f, 1.0f)
);
data.speed = maindir + randomdir * spread;
data.color = glm::vec4(
GetRandomFloat(0.0f, 1.0f),
GetRandomFloat(0.0f, 1.0f),
GetRandomFloat(0.0f, 1.0f),
1.0f
);
data.size = GetRandomFloat(0.1f, 0.3f);
return data;
});
generator2d_3->SetStartPosition(glm::vec3(29.163837f, 13.261223f, 70.086304f));
}
void Update(float dt) override { }
private:
Particle2dGenerator* generator2d;
Particle2dGenerator* generator2d_2;
Particle2dGenerator* generator2d_3;
};

6998
Grk-Projekt/src/MeshesData.h Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,100 @@
#pragma once
#include "GameObject.h"
#include "GLM/ext.hpp"
#include "GLM/gtx/quaternion.hpp"
class MovableObject : public GameObject
{
public:
MovableObject(RenderContext* _renderContext) : GameObject(_renderContext) {}
virtual void Init() = 0;
virtual void Update(float dt) = 0;
protected:
glm::mat4 animationMatrix(float time) {
float speed = 3.;
time = time * speed;
std::vector<float> distances;
float timeStep = 0;
for (int i = 0; i < keyPoints.size() - 1; i++) {
timeStep += (keyPoints[i] - keyPoints[i + 1]).length();
distances.push_back((keyPoints[i] - keyPoints[i + 1]).length());
}
time = fmod(time, timeStep);
//index of first keyPoint
int index = 0;
while (distances[index] <= time) {
time = time - distances[index];
index += 1;
}
//t coefitient between 0 and 1 for interpolation
float t = time / distances[index];
int size = keyPoints.size() - 1;
int size2 = keyRotation.size() - 1;
glm::vec3 pos = glm::catmullRom(
keyPoints[std::max(0, index - 1)],
keyPoints[std::max(0, index)],
keyPoints[std::min(index + 1, size)],
keyPoints[std::min(index + 2, size)],
t
);
auto animationRotation = glm::quat(1, 0, 0, 0);
glm::quat q0 = keyRotation[std::max(0, index - 1)];
glm::quat q1 = keyRotation[std::max(0, index)];
glm::quat q2 = keyRotation[std::min(index + 1, size2)];
glm::quat q3 = keyRotation[std::min(index + 2, size2)];
glm::quat invQ1 = glm::inverse(q1);
glm::quat invQ2 = glm::inverse(q2);
glm::quat a1 = q1 * glm::exp(
-(
glm::log(invQ1 * q0) +
glm::log(invQ1 * q2)
) / 4.0f
);
glm::quat a2 = q2 * glm::exp(
-(
glm::log(invQ2 * q1) +
glm::log(invQ2 * q3)
) / 4.0f
);
auto squad = glm::squad(q1, q2, a1, a2, t);
glm::mat4 result = glm::translate(pos) * glm::mat4_cast(squad);
return result;
}
void initKeyRoation(std::vector<glm::vec3>& _keyPoints) {
keyPoints = _keyPoints;
glm::vec3 oldDirection = glm::vec3(0, 0, 1);
glm::quat oldRotationCamera = glm::quat(1, 0, 0, 0);
for (int i = 0; i < keyPoints.size() - 1; i++)
{
glm::vec3 newDir = keyPoints[i + 1] - keyPoints[i];
auto newRot = glm::normalize(glm::rotationCamera(newDir, oldDirection) * oldRotationCamera);
keyRotation.push_back(newRot);
oldDirection = newDir;
oldRotationCamera = newRot;
}
keyRotation.push_back(glm::quat(1, 0, 0, 0));
}
private:
std::vector<glm::quat> keyRotation;
std::vector<glm::vec3> keyPoints;
};

View File

@ -0,0 +1,150 @@
#pragma once
#include "BaseParticleGenerator.h"
#include "Particle2dShader.h"
#include "RenderContextTexture.h"
class Particle2dGenerator : public BaseParticleGenerator
{
public:
Particle2dGenerator(const char* texturePath) : BaseParticleGenerator()
{
shader = new Particle2dShader();
shader->CreateFromFiles("shaders/particle_2D.vert", "shaders/particle_2D.frag");
shader->LinkUniforms();
texture = new Texture(texturePath);
texture->LoadTexture(TextureType::DIFFUSE);
}
void Init(GLuint _maxParticles, ParticleUpdateData(*getData)()) override
{
updateCallback = getData;
maxParticles = _maxParticles;
particles = new Particle[maxParticles];
particleBufferData = new float[maxParticles * vertexDataOffset];
for (int i = 0; i < maxParticles; i++) {
particles[i] = Particle();
particles[i].lifetime = -1.0f;
particles[i].cameradistance = -1.0f;
}
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, 12 * sizeof(float), vertexBufferData, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
glGenBuffers(1, &PBO);
glBindBuffer(GL_ARRAY_BUFFER, PBO);
glBufferData(GL_ARRAY_BUFFER, maxParticles * vertexDataSize, particleBufferData, GL_DYNAMIC_DRAW);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, vertexDataSize, (const void*)(sizeof(float) * 0));
glVertexAttribDivisor(1, 1);
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, vertexDataSize, (const void*)(sizeof(float) * 4));
glVertexAttribDivisor(2, 1);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
void Update(const float dt, glm::vec3* cameraPos) override
{
// Generate 10 new particule each millisecond,
// but limit this to 16 ms (60 fps), or if you have 1 long frame (1sec),
// newparticles will be huge and the next frame even longer.
int newparticles = (int)(dt * 1000.0);
if (newparticles > (int)(0.016f * 1000.0))
newparticles = (int)(0.016f * 1000.0);
for (int i = 0; i < newparticles; i++) {
int particleIndex = FindUnusedParticle();
particles[particleIndex].lifetime = startLifetime;
particles[particleIndex].position = startPos;
ParticleUpdateData updateData = updateCallback();
particles[particleIndex].speed = updateData.speed;
particles[particleIndex].color = updateData.color;
particles[particleIndex].size = updateData.size;
}
particlesCount = 0;
for (int i = 0; i < maxParticles; i++) {
Particle& p = particles[i];
if (p.lifetime > 0.0f) {
p.lifetime -= dt;
if (p.lifetime > 0.0f) {
p.position += p.speed * dt;
p.cameradistance = glm::length2(p.position - *cameraPos);
particleBufferData[0 + (vertexDataOffset * particlesCount)] = p.position.x;
particleBufferData[1 + (vertexDataOffset * particlesCount)] = p.position.y;
particleBufferData[2 + (vertexDataOffset * particlesCount)] = p.position.z;
particleBufferData[3 + (vertexDataOffset * particlesCount)] = p.size;
particleBufferData[4 + (vertexDataOffset * particlesCount)] = p.color.r;
particleBufferData[5 + (vertexDataOffset * particlesCount)] = p.color.g;
particleBufferData[6 + (vertexDataOffset * particlesCount)] = p.color.b;
particleBufferData[7 + (vertexDataOffset * particlesCount)] = p.color.a;
}
else {
p.cameradistance = -1.0f;
}
particlesCount++;
}
}
SortParticles();
}
void Draw(glm::mat4* view, glm::mat4* projection, bool showFog, glm::vec3* fogColor) override
{
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glBindVertexArray(VAO);
shader->UseShader();
shader->SetProjectionmatrix(projection);
shader->SetViewMatrix(view);
shader->SetShowFog(showFog);
shader->SetFogColor(fogColor);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture->textureId);
shader->SetTexture(0);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
glBindBuffer(GL_ARRAY_BUFFER, PBO);
glBufferSubData(GL_ARRAY_BUFFER, 0, particlesCount * vertexDataSize, particleBufferData);
glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, particlesCount);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
private:
Particle2dShader* shader;
Texture* texture;
unsigned int vertexDataOffset = 8;
unsigned int vertexDataSize = sizeof(glm::vec4) + sizeof(glm::vec4);
GLfloat vertexBufferData[12] = {
-0.5f, -0.5f, 0.0f,
0.5f, -0.5f, 0.0f,
-0.5f, 0.5f, 0.0f,
0.5f, 0.5f, 0.0f
};
};

View File

@ -0,0 +1,41 @@
#pragma once
#include "ShaderBase.h"
class Particle2dShader : public ShaderBase
{
public:
Particle2dShader() : ShaderBase()
{
}
void SetProjectionmatrix(glm::mat4* projectionMatrix)
{
glUniformMatrix4fv(uniformProjection, 1, GL_FALSE, glm::value_ptr(*projectionMatrix));
}
void SetViewMatrix(glm::mat4* viewMatrix)
{
glUniformMatrix4fv(uniformView, 1, GL_FALSE, glm::value_ptr(*viewMatrix));
}
void SetTexture(GLuint textureUnit)
{
glUniform1i(uniformTexture, textureUnit);
}
void LinkUniforms() override
{
uniformProjection = glGetUniformLocation(shaderID, "projection");
uniformView = glGetUniformLocation(shaderID, "view");
uniformTexture = glGetUniformLocation(shaderID, "theTexture");
uniformShowFog = glGetUniformLocation(shaderID, "showFog");
uniformFogColor = glGetUniformLocation(shaderID, "fogColor");
}
private:
GLuint uniformTexture = 0;
GLuint uniformProjection = 0;
GLuint uniformView = 0;
};

View File

@ -0,0 +1,48 @@
#include "Physics.h"
#define PX_RELEASE(x) if(x) { x->release(); x = NULL; }
Physics::Physics(float gravity)
{
foundation = PxCreateFoundation(PX_PHYSICS_VERSION, allocator, errorCallback);
physics = PxCreatePhysics(PX_PHYSICS_VERSION, *foundation, PxTolerancesScale(), true);
PxSceneDesc sceneDesc(physics->getTolerancesScale());
sceneDesc.gravity = PxVec3(0.0f, -gravity, 0.0f);
dispatcher = PxDefaultCpuDispatcherCreate(2);
sceneDesc.cpuDispatcher = dispatcher;
sceneDesc.filterShader = PxDefaultSimulationFilterShader;
scene = physics->createScene(sceneDesc);
}
Physics::Physics(float gravity,
PxSimulationFilterShader simulationFilterShader,
PxSimulationEventCallback* simulationEventCallback)
{
foundation = PxCreateFoundation(PX_PHYSICS_VERSION, allocator, errorCallback);
physics = PxCreatePhysics(PX_PHYSICS_VERSION, *foundation, PxTolerancesScale(), true);
PxSceneDesc sceneDesc(physics->getTolerancesScale());
sceneDesc.gravity = PxVec3(0.0f, -gravity, 0.0f);
dispatcher = PxDefaultCpuDispatcherCreate(2);
sceneDesc.cpuDispatcher = dispatcher;
sceneDesc.filterShader = simulationFilterShader;
sceneDesc.kineKineFilteringMode = PxPairFilteringMode::eKEEP; // So kin-kin contacts with be reported
sceneDesc.staticKineFilteringMode = PxPairFilteringMode::eKEEP; // So static-kin constacts will be reported
sceneDesc.simulationEventCallback = simulationEventCallback;
scene = physics->createScene(sceneDesc);
}
Physics::~Physics()
{
PX_RELEASE(scene);
PX_RELEASE(dispatcher);
PX_RELEASE(physics);
PX_RELEASE(foundation);
}
void Physics::step(float dt)
{
scene->simulate(dt);
scene->fetchResults(true);
}

24
Grk-Projekt/src/Physics.h Normal file
View File

@ -0,0 +1,24 @@
#pragma once
#include "PxPhysicsAPI.h"
using namespace physx;
class Physics
{
public:
Physics(float gravity);
Physics(float gravity,
PxSimulationFilterShader simulationFilterShader,
PxSimulationEventCallback* simulationEventCallback);
virtual ~Physics();
PxPhysics* physics = nullptr;
PxScene* scene = nullptr;
void step(float dt);
private:
PxDefaultAllocator allocator;
PxDefaultErrorCallback errorCallback;
PxFoundation* foundation = nullptr;
PxDefaultCpuDispatcher* dispatcher = nullptr;
};

View File

@ -0,0 +1,70 @@
#pragma once
#include "Camera.h"
class PlayerCamera : public Camera
{
public:
PlayerCamera() : Camera(glm::vec3(0, 0, 0), 5.0f, 5.0f) {}
PlayerCamera(glm::vec3 startPosition, glm::vec3 startUp, GLfloat startYaw, GLfloat startPitch,
GLfloat startMoveSpeed, GLfloat startTurnSpeed) :
Camera(startPosition, startMoveSpeed, startTurnSpeed)
{
_up = startUp;
_yaw = startYaw;
_pitch = startPitch;
}
void HandleControlls(Controlls* controlls, GLfloat deltaTime) override
{
float xChange = controlls->GetMouseXChange() * _turnSpeed;
float yChange = controlls->GetMouseYChange() * _turnSpeed;
_yaw += xChange;
_pitch += yChange;
if (_pitch >= 89.0f)
_pitch = 89.0f;
if (_pitch <= -40.0f)
_pitch = -40.0f;
ScrollDirection scrollDir = controlls->GetScrollDirection();
if (scrollDir == ScrollDirection::UP && cameraDistance < cameraMaxDistance) {
cameraDistance += cameraScrollSpeed;
}
else if (scrollDir == ScrollDirection::DOWN && cameraDistance > cameraMinDistance) {
cameraDistance -= cameraScrollSpeed;
}
}
glm::mat4* CalculateViewMatrix() override
{
_viewMatrix = glm::lookAt(_position, _playerPos, _up);
return &_viewMatrix;
}
void SetPlayerPosition(glm::vec3* playerPos)
{
// https://books.google.pl/books?id=IfDouSUqOUIC&pg=PA495&lpg=PA495&dq=opengl+quaternion+third+person+camera&source=bl&ots=h1eiZG2FmX&sig=ACfU3U356snNFuYRqPUug4v4Kszu6CQ_gQ&hl=en&sa=X&ved=2ahUKEwjY--2rupj1AhWul4sKHWcUBJMQ6AF6BAgYEAM#v=onepage&q=opengl%20quaternion%20third%20person%20camera&f=false
_playerPos.x = playerPos->x;
_playerPos.y = playerPos->y;
_playerPos.z = playerPos->z;
_position.x = playerPos->x - glm::cos(_yaw * 0.01f) * glm::cos(_pitch * 0.01f) * cameraDistance;
_position.y = playerPos->y + glm::sin(_pitch * 0.01f) * cameraDistance;
_position.z = playerPos->z - glm::sin(_yaw * 0.01f) * glm::cos(_pitch * 0.01f) * cameraDistance;
}
~PlayerCamera() = default;
private:
glm::vec3 _playerPos = glm::vec3(0, 0, 0);
GLfloat cameraScrollSpeed = 0.2f;
GLfloat cameraDistance = 5.0f;
GLfloat cameraDefaultDistance = 5.0f;
GLfloat cameraMinDistance = 4.0f;
GLfloat cameraMaxDistance = 8.0f;
};

View File

@ -0,0 +1,46 @@
#pragma once
#include "Light.h"
class PointLight : public Light
{
public:
PointLight() : Light()
{
position = glm::vec3(0.0f, 0.0f, 0.0f);
constant = 1.0f;
linear = 0.0f;
exponent = 0.0f;
}
PointLight(GLfloat red, GLfloat green, GLfloat blue,
GLfloat aIntensity, GLfloat dIntensity,
GLfloat xPos, GLfloat yPos, GLfloat zPos,
GLfloat con, GLfloat lin, GLfloat exp
) : Light(red, green, blue, aIntensity, dIntensity, 1024, 1024)
{
position = glm::vec3(xPos, yPos, zPos);
constant = con;
linear = lin;
exponent = exp;
}
glm::vec3* GetPosition() { return &position; }
GLfloat GetConstant() { return constant; }
GLfloat GetLinear() { return linear; }
GLfloat GetExponent() { return exponent; }
void SetPosition(glm::vec3* _pos)
{
position.x = _pos->x;
position.y = _pos->y;
position.z = _pos->z;
}
~PointLight() {}
protected:
glm::vec3 position;
GLfloat constant, linear, exponent;
};

View File

@ -0,0 +1,105 @@
#pragma once
#include "BasePlayer.h"
#include "PlayerCamera.h"
class PointLightDebugPlayer : public BasePlayer
{
public:
PointLightDebugPlayer() : BasePlayer(nullptr)
{
/*camera = new FreeCamera(
glm::vec3(0.0f, 0.0f, 0.0f),
glm::vec3(0.0f, 1.0f, 0.0f),
-90.0f, 0.0f, 5.0f, 0.1f
);*/
camera = new PlayerCamera(
glm::vec3(0.0f, 0.0f, 0.0f),
glm::vec3(0.0f, 1.0f, 0.0f),
-90.0f, 0.0f, 5.0f, 0.3f
);
pointLight = new PointLight(
0.95f, 0.7f, 0.15f,
0.1f, 3.0f,
0.0f, 0.0f, 0.0f,
1.0f, 0.007, 0.0002f
);
pointLights.push_back(pointLight);
}
void Init() override {}
void Update(float dt) override
{
camera->SetPlayerPosition(&playerPos);
UpdateLights();
DebugLight(dt);
}
Camera* GetCamera() override
{
return camera;
}
void HandleControlls(Controlls* controlls, GLfloat deltaTime) override
{
camera->HandleControlls(controlls, deltaTime);
if (controlls->keys[GLFW_KEY_W])
{
playerPos += glm::vec3(0, 0, 1) * velocity * deltaTime;
}
if (controlls->keys[GLFW_KEY_S])
{
playerPos -= glm::vec3(0, 0, 1) * velocity * deltaTime;
}
if (controlls->keys[GLFW_KEY_A])
{
playerPos += glm::vec3(1, 0, 0) * velocity * deltaTime;
}
if (controlls->keys[GLFW_KEY_D])
{
playerPos -= glm::vec3(1, 0, 0) * velocity * deltaTime;
}
if (controlls->keys[GLFW_KEY_SPACE])
{
playerPos += worldUp * velocity * deltaTime;
}
if (controlls->keys[GLFW_KEY_LEFT_CONTROL])
{
playerPos -= worldUp * velocity * deltaTime;
}
}
private:
float velocity = 5.0f;
float dtSum = 0.0f;
glm::vec3 lightPos = glm::vec3(0);
glm::vec3 spotLightDir = glm::vec3(0);
PlayerCamera* camera = nullptr;
PointLight* pointLight = nullptr;
void UpdateLights() {
if (pointLight != nullptr) {
lightPos.x = playerPos.x;
lightPos.y = playerPos.y;
lightPos.z = playerPos.z;
pointLight->SetPosition(&lightPos);
}
}
void DebugLight(float dt) {
dtSum += dt;
if (dtSum > 1.5f && pointLight != nullptr) {
printf("PointLightPlayer {\n");
printf(" Position = %ff, %ff, %ff\n", lightPos.x, lightPos.y, lightPos.z);
printf("}\n");
dtSum = 0.0f;
}
}
};

View File

@ -0,0 +1,230 @@
#include "RenderContext.h"
#include "CommonValues.h"
#include <iostream>
#include <fstream>
RenderContext::RenderContext(const char* modelPath)
{
LoadModel(modelPath);
}
void RenderContext::Render(Shader* shader, glm::mat4 modelMatrix)
{
nodes[0]->matrix = modelMatrix;
for (auto node : nodes)
{
if (node->meshList.size() == 0) {
continue;
}
int i = 0;
for (auto context : node->meshList) {
glm::mat4 transformation = node->matrix;
unsigned int materialIndex = node->meshToMaterial[i];
if (materialList[materialIndex]->useDiffuseTexture)
{
glActiveTexture(GL_TEXTURE0 + materialList[materialIndex]->diffuseTextureUnit);
glBindTexture(GL_TEXTURE_2D, materialList[materialIndex]->diffuseTextureID);
}
shader->SetMaterial(materialList[materialIndex]);
Node* tempNode = node;
while (tempNode->parent != -1) {
transformation = nodes[tempNode->parent]->matrix * transformation;
tempNode = nodes[tempNode->parent];
}
shader->SetModelMatrix(&transformation);
glBindVertexArray(context->VAO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, context->IBO);
glDrawElements(GL_TRIANGLES, context->indexCount, GL_UNSIGNED_INT, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindVertexArray(0);
i++;
}
}
}
RenderContext::~RenderContext()
{
for (auto node : nodes) {
for (auto mesh : node->meshList) {
if (mesh) {
delete mesh;
mesh = nullptr;
}
}
}
for (auto material : materialList)
{
if (material)
{
delete material;
material = nullptr;
}
}
std::map<std::string, Texture*>::iterator it;
for (it = textureMap.begin(); it != textureMap.end(); it++)
{
if (it->second) delete it->second;
}
textureMap.clear();
}
void RenderContext::LoadModel(const char* modelPath)
{
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(modelPath, aiProcess_Triangulate | aiProcess_FlipUVs | aiProcess_GenSmoothNormals | aiProcess_JoinIdenticalVertices);
if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode)
{
printf("Model (%s) failed to load: %s", modelPath, importer.GetErrorString());
return;
}
LoadMaterials(scene);
LoadNode(scene->mRootNode, scene, -1);
}
void RenderContext::LoadNode(aiNode* node, const aiScene* scene, int parentId)
{
int index = nodes.size();
nodes.push_back(new Node());
nodes[index]->name = node->mName.C_Str();
nodes[index]->parent = parentId;
nodes[index]->matrix = glm::transpose(glm::make_mat4(&node->mTransformation.a1));
for (size_t i = 0; i < node->mNumMeshes; i++)
{
LoadMesh(scene->mMeshes[node->mMeshes[i]], scene, nodes[index]->meshList, nodes[index]->meshToMaterial);
}
for (size_t i = 0; i < node->mNumChildren; i++)
{
LoadNode(node->mChildren[i], scene, index);
}
}
void RenderContext::LoadMesh(aiMesh* mesh, const aiScene* scene, std::vector<Mesh*>& meshes, std::vector<unsigned int>& meshToMaterial)
{
std::vector<GLfloat> vertices;
std::vector<unsigned int> indices;
for (size_t i = 0; i < mesh->mNumVertices; i++)
{
vertices.insert(vertices.end(), { mesh->mVertices[i].x, mesh->mVertices[i].y, mesh->mVertices[i].z });
if (mesh->mTextureCoords[0])
{
vertices.insert(vertices.end(), { mesh->mTextureCoords[0][i].x, mesh->mTextureCoords[0][i].y });
}
else {
vertices.insert(vertices.end(), { 0.0f, 0.0f });
}
vertices.insert(vertices.end(), { -mesh->mNormals[i].x, -mesh->mNormals[i].y, -mesh->mNormals[i].z });
}
for (size_t i = 0; i < mesh->mNumFaces; i++)
{
aiFace face = mesh->mFaces[i];
for (size_t j = 0; j < face.mNumIndices; j++)
{
indices.push_back(face.mIndices[j]);
}
}
Mesh* newMesh = new Mesh(&vertices[0], &indices[0], vertices.size(), indices.size());
meshes.push_back(newMesh);
meshToMaterial.push_back(mesh->mMaterialIndex);
}
void color4_to_float4(const aiColor4D* c, float f[4])
{
f[0] = c->r;
f[1] = c->g;
f[2] = c->b;
f[3] = c->a;
}
void set_float4(float f[4], float a, float b, float c, float d)
{
f[0] = a;
f[1] = b;
f[2] = c;
f[3] = d;
}
void RenderContext::LoadMaterials(const aiScene* scene)
{
materialList.resize(scene->mNumMaterials);
for (size_t i = 0; i < scene->mNumMaterials; i++)
{
aiMaterial* material = scene->mMaterials[i];
float c[4];
aiColor4D diffuse;
float shininess, specularIntensity;
unsigned int max;
materialList[i] = new Material();
set_float4(c, 0.0f, 0.0f, 0.0f, 1.0f);
if (AI_SUCCESS == aiGetMaterialColor(material, AI_MATKEY_COLOR_DIFFUSE, &diffuse)) {
color4_to_float4(&diffuse, c);
materialList[i]->objectColor = glm::vec3(diffuse.r, diffuse.g, diffuse.b);
}
int ret1 = aiGetMaterialFloatArray(material, AI_MATKEY_SHININESS, &shininess, &max);
int ret2 = aiGetMaterialFloatArray(material, AI_MATKEY_SHININESS_STRENGTH, &specularIntensity, &max);
if ((ret1 == AI_SUCCESS) && (ret2 == AI_SUCCESS)) {
materialList[i]->shininess = shininess;
materialList[i]->specularIntensity = specularIntensity * 4;
}
if (material->GetTextureCount(aiTextureType_DIFFUSE))
{
aiString path;
if (material->GetTexture(aiTextureType_DIFFUSE, 0, &path) == AI_SUCCESS)
{
std::string filename = std::string(path.data);
std::string texPath = std::string("models\\") + filename;
bool inserted = false;
// SprawdŸ czy tekstura ju¿ istnieje w s³owniku
if (textureMap.count(texPath) == 0)
{
// Je¿eli nie zaladuj i dodaj do s³ownika
Texture* tempTexture = new Texture(texPath.c_str());
if (!tempTexture->LoadTexture(TextureType::DIFFUSE)) {
printf("Failed to load texture at: %s\n", texPath.c_str());
} else {
inserted = true;
printf("Texture loaded and inserted: %s\n", texPath.c_str());
textureMap.insert({ texPath, tempTexture });
}
}
if (!inserted) {
printf("Texture reused: %s\n", texPath.c_str());
}
// ZnajdŸ teksturê w s³owniku, i przypisz teksturê do materia³u
auto currentTexture = textureMap.find(texPath);
currentTexture->second->assignToMaterial(materialList[i]);
}
}
materialList[i]->name = material->GetName().C_Str();
}
}

View File

@ -0,0 +1,62 @@
#pragma once
#include <GL\glew.h>
#include <GLFW\glfw3.h>
#include <GLM\glm.hpp>
#include <GLM\ext.hpp>
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <map>
#include <string>
#include "RenderContextMesh.h"
#include "RenderContextTexture.h"
#include "RenderContextMaterial.h"
#include "Shader.h"
static inline glm::mat4 mat4_cast(const aiMatrix4x4& m) { return glm::transpose(glm::make_mat4(&m.a1)); }
struct Node {
std::string name;
std::vector<Mesh*> meshList;
std::vector<unsigned int> meshToMaterial;
glm::mat4 matrix;
int parent;
};
class RenderContext
{
public:
RenderContext(const char* modelPath);
void Render(Shader* shader, glm::mat4 modelMatrix);
~RenderContext();
Node* FindNode(const char* name){
for (auto node : nodes) {
if (node->name == name) {
return node;
}
}
}
Material* FindMaterial(const char* name) {
for (auto material : materialList) {
if (material->name == name) {
return material;
}
}
}
private:
std::vector<Node*> nodes;
std::vector<Material*> materialList;
std::map<std::string, Texture*> textureMap;
void LoadModel(const char* modelPath);
void LoadNode(aiNode* node, const aiScene* scene, int parentId);
void LoadMesh(aiMesh* mesh, const aiScene* scene, std::vector<Mesh*>& meshes, std::vector<unsigned int>& meshToMaterial);
void LoadMaterials(const aiScene* scene);
};

View File

@ -0,0 +1,13 @@
#pragma once
struct Material {
std::string name = "";
bool useDiffuseTexture = false;
int diffuseTextureUnit = 0;
GLuint diffuseTextureID = 0;
glm::vec3 objectColor = glm::vec3(1.0f, 1.0f, 1.0f);
GLfloat specularIntensity = 0.0f;
GLfloat shininess = 0.0f;
};

View File

@ -0,0 +1,43 @@
#pragma once
struct Mesh {
GLuint VAO = 0;
GLuint VBO = 0;
GLuint IBO = 0;
GLsizei indexCount = 0;
Mesh(const GLfloat* vertices, const unsigned int* indices, const unsigned int numOfVertices, const unsigned int numOfIndices)
{
indexCount = numOfIndices;
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
glGenBuffers(1, &IBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices[0]) * numOfIndices, indices, GL_STATIC_DRAW);
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices[0]) * numOfVertices, vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(vertices[0]) * 8, 0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(vertices[0]) * 8, (void*)(sizeof(vertices[0]) * 3));
glEnableVertexAttribArray(1);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(vertices[0]) * 8, (void*)(sizeof(vertices[0]) * 5));
glEnableVertexAttribArray(2);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
~Mesh()
{
if (IBO != 0) { glDeleteBuffers(1, &IBO); IBO = 0; }
if (VBO != 0) { glDeleteBuffers(1, &VBO); VBO = 0; }
if (VAO != 0) { glDeleteVertexArrays(1, &VAO); VAO = 0; }
indexCount = 0;
}
};

View File

@ -0,0 +1,76 @@
#pragma once
#include "CommonValues.h"
#include "RenderContextMaterial.h"
enum TextureType
{
DIFFUSE,
SPECULAR
};
struct Texture {
GLuint textureId;
TextureType type;
int width = 0;
int height = 0;
int bitDepth = 0;
const char* fileLocation = "";
Texture() {};
Texture(const char* fileLoc)
{
fileLocation = fileLoc;
}
~Texture()
{
if (textureId) glDeleteTextures(1, &textureId);
width = 0;
height = 0;
bitDepth = 0;
fileLocation = "";
}
bool LoadTexture(TextureType _type)
{
unsigned char* texData = stbi_load(fileLocation, &width, &height, &bitDepth, 0);
if (!texData)
{
printf("Failed to find: %s\n", fileLocation);
return false;
}
GLenum format = GL_RGB;
if (bitDepth == 1)
format = GL_RED;
else if (bitDepth == 3)
format = GL_RGB;
else if (bitDepth == 4)
format = GL_RGBA;
type = _type;
glGenTextures(1, &textureId);
glBindTexture(GL_TEXTURE_2D, textureId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, texData);
glGenerateMipmap(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
stbi_image_free(texData);
return true;
}
void assignToMaterial(Material* material) {
if (type == TextureType::DIFFUSE) {
material->diffuseTextureID = textureId;
material->useDiffuseTexture = true;
}
}
};

104
Grk-Projekt/src/Renderer.h Normal file
View File

@ -0,0 +1,104 @@
#pragma once
#include "Scene.h"
class Renderer
{
public:
Renderer(){};
void ToggleDebugLights() { debugLights = !debugLights; }
void ToggleSkybox() { showSkybox = !showSkybox; }
void ToggleFog() { showFog = !showFog; }
void DirectionalShadowMapPass(Scene* scene)
{
scene->directionalShadowShader->UseShader();
glViewport(0, 0, scene->mainLight->GetShadowMap()->GetShadowWidth(), scene->mainLight->GetShadowMap()->GetShadowHeight());
scene->mainLight->GetShadowMap()->Write();
glClear(GL_DEPTH_BUFFER_BIT);
scene->directionalShadowShader->SetDirectionaLightTransform(scene->mainLight->CalculateLightTransform());
RenderScene(scene, scene->directionalShadowShader);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
void RenderPass(Scene* scene, glm::mat4* projectionMatrix, glm::mat4* viewMatrix)
{
glViewport(0, 0, 1366, 768);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (showSkybox) {
scene->skybox->DrawSkybox(viewMatrix, projectionMatrix, scene->activeCamera->GetCameraPosition(), showFog, &fogColor);
}
scene->shader->UseShader();
scene->shader->SetShowFog(showFog);
scene->shader->SetFogColor(&fogColor);
scene->shader->SetProjectionmatrix(projectionMatrix);
scene->shader->SetViewMatrix(viewMatrix);
scene->shader->SetEyePosition(scene->activeCamera->GetCameraPosition());
scene->shader->SetDirectionalLight(scene->mainLight);
scene->shader->SetPointLights(scene->pointLights, scene->pointLights.size());
scene->shader->SetSpotLights(scene->spotLights, scene->spotLights.size());
scene->shader->SetDirectionaLightTransform(scene->mainLight->CalculateLightTransform());
scene->mainLight->GetShadowMap()->Read(GL_TEXTURE2);
scene->shader->SetDirectionalShadowMap(2);
RenderScene(scene, scene->shader);
if (debugLights) {
DebugLights(scene);
}
}
void ParticlePass(Scene* scene, glm::mat4* projectionMatrix, glm::mat4* viewMatrix)
{
for (size_t i = 0; i < scene->particleGenerators.size(); i++)
{
scene->particleGenerators[i]->Draw(viewMatrix, projectionMatrix, showFog, &fogColor);
}
}
private:
bool debugLights = false;
bool showSkybox = true;
bool showFog = true;
//glm::vec3 fogColor = glm::vec3(0.39f, 0.56f, 0.55f); // 98, 143, 140
//glm::vec3 fogColor = glm::vec3(0.45f, 0.61f, 0.6f); // 130, 171, 168
//glm::vec3 fogColor = glm::vec3(0.51, 0.67, 0.66); // 130, 171, 168
//glm::vec3 fogColor = glm::vec3(0.66, 0.71, 0.57); // 170, 181, 147
//glm::vec3 fogColor = glm::vec3(0.66, 0.6, 0.49); // 171, 154, 126
//glm::vec3 fogColor = glm::vec3(0.52, 0.67, 0.59); // 132, 171, 152
glm::vec3 fogColor = glm::vec3(0.59, 0.8, 0.69); // 151, 204, 178
void RenderScene(Scene* scene, Shader* shader)
{
for (size_t i = 0; i < scene->gameObjects.size(); i++)
{
scene->gameObjects[i]->Render(shader);
}
}
void DebugLights(Scene* scene) {
for (auto light : scene->pointLights)
{
StaticObject* tempObject = new StaticObject(scene->cubeContext);
tempObject->Translate(*light->GetPosition());
tempObject->Scale(glm::vec3(0.1f));
tempObject->Render(scene->shader);
delete tempObject;
}
for (auto light : scene->spotLights)
{
StaticObject* tempObject = new StaticObject(scene->coneContext);
auto pos = light->GetPosition();
auto model = glm::inverse(glm::lookAt(*light->GetPosition(), (*light->GetDirection()) + *light->GetPosition(), glm::vec3(0, 1, 0)));
model *= glm::scale(glm::vec3(0.1f));
tempObject->SetMat4(model);
tempObject->Render(scene->shader);
delete tempObject;
}
}
};

View File

@ -0,0 +1,36 @@
#include "Physics.h"
#define PX_RELEASE(x) if(x) { x->release(); x = NULL; }
Physics::Physics(float gravity,
PxSimulationFilterShader simulationFilterShader,
PxSimulationEventCallback *simulationEventCallback)
{
foundation = PxCreateFoundation(PX_PHYSICS_VERSION, allocator, errorCallback);
physics = PxCreatePhysics(PX_PHYSICS_VERSION, *foundation, PxTolerancesScale(), true);
PxSceneDesc sceneDesc(physics->getTolerancesScale());
sceneDesc.gravity = PxVec3(0.0f, -gravity, 0.0f);
dispatcher = PxDefaultCpuDispatcherCreate(2);
sceneDesc.cpuDispatcher = dispatcher;
sceneDesc.filterShader = simulationFilterShader;
sceneDesc.kineKineFilteringMode = PxPairFilteringMode::eKEEP; // So kin-kin contacts with be reported
sceneDesc.staticKineFilteringMode = PxPairFilteringMode::eKEEP; // So static-kin constacts will be reported
sceneDesc.simulationEventCallback = simulationEventCallback;
scene = physics->createScene(sceneDesc);
}
Physics::~Physics()
{
PX_RELEASE(scene);
PX_RELEASE(dispatcher);
PX_RELEASE(physics);
PX_RELEASE(foundation);
}
void Physics::step(float dt)
{
scene->simulate(dt);
scene->fetchResults(true);
}

View File

@ -0,0 +1,23 @@
#pragma once
#include "PxPhysicsAPI.h"
using namespace physx;
class Physics
{
public:
Physics(float gravity,
PxSimulationFilterShader simulationFilterShader,
PxSimulationEventCallback *simulationEventCallback);
virtual ~Physics();
PxPhysics* physics = nullptr;
PxScene* scene = nullptr;
void step(float dt);
private:
PxDefaultAllocator allocator;
PxDefaultErrorCallback errorCallback;
PxFoundation* foundation = nullptr;
PxDefaultCpuDispatcher* dispatcher = nullptr;
};

2024
Grk-Projekt/src/SOIL/SOIL.c Normal file

File diff suppressed because it is too large Load Diff

433
Grk-Projekt/src/SOIL/SOIL.h Normal file
View File

@ -0,0 +1,433 @@
/**
@mainpage SOIL
Jonathan Dummer
2007-07-26-10.36
Simple OpenGL Image Library
A tiny c library for uploading images as
textures into OpenGL. Also saving and
loading of images is supported.
I'm using Sean's Tool Box image loader as a base:
http://www.nothings.org/
I'm upgrading it to load TGA and DDS files, and a direct
path for loading DDS files straight into OpenGL textures,
when applicable.
Image Formats:
- BMP load & save
- TGA load & save
- DDS load & save
- PNG load
- JPG load
OpenGL Texture Features:
- resample to power-of-two sizes
- MIPmap generation
- compressed texture S3TC formats (if supported)
- can pre-multiply alpha for you, for better compositing
- can flip image about the y-axis (except pre-compressed DDS files)
Thanks to:
* Sean Barret - for the awesome stb_image
* Dan Venkitachalam - for finding some non-compliant DDS files, and patching some explicit casts
* everybody at gamedev.net
**/
#ifndef HEADER_SIMPLE_OPENGL_IMAGE_LIBRARY
#define HEADER_SIMPLE_OPENGL_IMAGE_LIBRARY
#ifdef __cplusplus
extern "C" {
#endif
/**
The format of images that may be loaded (force_channels).
SOIL_LOAD_AUTO leaves the image in whatever format it was found.
SOIL_LOAD_L forces the image to load as Luminous (greyscale)
SOIL_LOAD_LA forces the image to load as Luminous with Alpha
SOIL_LOAD_RGB forces the image to load as Red Green Blue
SOIL_LOAD_RGBA forces the image to load as Red Green Blue Alpha
**/
enum
{
SOIL_LOAD_AUTO = 0,
SOIL_LOAD_L = 1,
SOIL_LOAD_LA = 2,
SOIL_LOAD_RGB = 3,
SOIL_LOAD_RGBA = 4
};
/**
Passed in as reuse_texture_ID, will cause SOIL to
register a new texture ID using glGenTextures().
If the value passed into reuse_texture_ID > 0 then
SOIL will just re-use that texture ID (great for
reloading image assets in-game!)
**/
enum
{
SOIL_CREATE_NEW_ID = 0
};
/**
flags you can pass into SOIL_load_OGL_texture()
and SOIL_create_OGL_texture().
(note that if SOIL_FLAG_DDS_LOAD_DIRECT is used
the rest of the flags with the exception of
SOIL_FLAG_TEXTURE_REPEATS will be ignored while
loading already-compressed DDS files.)
SOIL_FLAG_POWER_OF_TWO: force the image to be POT
SOIL_FLAG_MIPMAPS: generate mipmaps for the texture
SOIL_FLAG_TEXTURE_REPEATS: otherwise will clamp
SOIL_FLAG_MULTIPLY_ALPHA: for using (GL_ONE,GL_ONE_MINUS_SRC_ALPHA) blending
SOIL_FLAG_INVERT_Y: flip the image vertically
SOIL_FLAG_COMPRESS_TO_DXT: if the card can display them, will convert RGB to DXT1, RGBA to DXT5
SOIL_FLAG_DDS_LOAD_DIRECT: will load DDS files directly without _ANY_ additional processing
SOIL_FLAG_NTSC_SAFE_RGB: clamps RGB components to the range [16,235]
SOIL_FLAG_CoCg_Y: Google YCoCg; RGB=>CoYCg, RGBA=>CoCgAY
SOIL_FLAG_TEXTURE_RECTANGE: uses ARB_texture_rectangle ; pixel indexed & no repeat or MIPmaps or cubemaps
**/
enum
{
SOIL_FLAG_POWER_OF_TWO = 1,
SOIL_FLAG_MIPMAPS = 2,
SOIL_FLAG_TEXTURE_REPEATS = 4,
SOIL_FLAG_MULTIPLY_ALPHA = 8,
SOIL_FLAG_INVERT_Y = 16,
SOIL_FLAG_COMPRESS_TO_DXT = 32,
SOIL_FLAG_DDS_LOAD_DIRECT = 64,
SOIL_FLAG_NTSC_SAFE_RGB = 128,
SOIL_FLAG_CoCg_Y = 256,
SOIL_FLAG_TEXTURE_RECTANGLE = 512
};
/**
The types of images that may be saved.
(TGA supports uncompressed RGB / RGBA)
(BMP supports uncompressed RGB)
(DDS supports DXT1 and DXT5)
**/
enum
{
SOIL_SAVE_TYPE_TGA = 0,
SOIL_SAVE_TYPE_BMP = 1,
SOIL_SAVE_TYPE_DDS = 2
};
/**
Defines the order of faces in a DDS cubemap.
I recommend that you use the same order in single
image cubemap files, so they will be interchangeable
with DDS cubemaps when using SOIL.
**/
#define SOIL_DDS_CUBEMAP_FACE_ORDER "EWUDNS"
/**
The types of internal fake HDR representations
SOIL_HDR_RGBE: RGB * pow( 2.0, A - 128.0 )
SOIL_HDR_RGBdivA: RGB / A
SOIL_HDR_RGBdivA2: RGB / (A*A)
**/
enum
{
SOIL_HDR_RGBE = 0,
SOIL_HDR_RGBdivA = 1,
SOIL_HDR_RGBdivA2 = 2
};
/**
Loads an image from disk into an OpenGL texture.
\param filename the name of the file to upload as a texture
\param force_channels 0-image format, 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA
\param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)
\param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT
\return 0-failed, otherwise returns the OpenGL texture handle
**/
unsigned int
SOIL_load_OGL_texture
(
const char *filename,
int force_channels,
unsigned int reuse_texture_ID,
unsigned int flags
);
/**
Loads 6 images from disk into an OpenGL cubemap texture.
\param x_pos_file the name of the file to upload as the +x cube face
\param x_neg_file the name of the file to upload as the -x cube face
\param y_pos_file the name of the file to upload as the +y cube face
\param y_neg_file the name of the file to upload as the -y cube face
\param z_pos_file the name of the file to upload as the +z cube face
\param z_neg_file the name of the file to upload as the -z cube face
\param force_channels 0-image format, 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA
\param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)
\param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT
\return 0-failed, otherwise returns the OpenGL texture handle
**/
unsigned int
SOIL_load_OGL_cubemap
(
const char *x_pos_file,
const char *x_neg_file,
const char *y_pos_file,
const char *y_neg_file,
const char *z_pos_file,
const char *z_neg_file,
int force_channels,
unsigned int reuse_texture_ID,
unsigned int flags
);
/**
Loads 1 image from disk and splits it into an OpenGL cubemap texture.
\param filename the name of the file to upload as a texture
\param face_order the order of the faces in the file, any combination of NSWEUD, for North, South, Up, etc.
\param force_channels 0-image format, 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA
\param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)
\param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT
\return 0-failed, otherwise returns the OpenGL texture handle
**/
unsigned int
SOIL_load_OGL_single_cubemap
(
const char *filename,
const char face_order[6],
int force_channels,
unsigned int reuse_texture_ID,
unsigned int flags
);
/**
Loads an HDR image from disk into an OpenGL texture.
\param filename the name of the file to upload as a texture
\param fake_HDR_format SOIL_HDR_RGBE, SOIL_HDR_RGBdivA, SOIL_HDR_RGBdivA2
\param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)
\param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT
\return 0-failed, otherwise returns the OpenGL texture handle
**/
unsigned int
SOIL_load_OGL_HDR_texture
(
const char *filename,
int fake_HDR_format,
int rescale_to_max,
unsigned int reuse_texture_ID,
unsigned int flags
);
/**
Loads an image from RAM into an OpenGL texture.
\param buffer the image data in RAM just as if it were still in a file
\param buffer_length the size of the buffer in bytes
\param force_channels 0-image format, 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA
\param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)
\param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT
\return 0-failed, otherwise returns the OpenGL texture handle
**/
unsigned int
SOIL_load_OGL_texture_from_memory
(
const unsigned char *const buffer,
int buffer_length,
int force_channels,
unsigned int reuse_texture_ID,
unsigned int flags
);
/**
Loads 6 images from memory into an OpenGL cubemap texture.
\param x_pos_buffer the image data in RAM to upload as the +x cube face
\param x_pos_buffer_length the size of the above buffer
\param x_neg_buffer the image data in RAM to upload as the +x cube face
\param x_neg_buffer_length the size of the above buffer
\param y_pos_buffer the image data in RAM to upload as the +x cube face
\param y_pos_buffer_length the size of the above buffer
\param y_neg_buffer the image data in RAM to upload as the +x cube face
\param y_neg_buffer_length the size of the above buffer
\param z_pos_buffer the image data in RAM to upload as the +x cube face
\param z_pos_buffer_length the size of the above buffer
\param z_neg_buffer the image data in RAM to upload as the +x cube face
\param z_neg_buffer_length the size of the above buffer
\param force_channels 0-image format, 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA
\param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)
\param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT
\return 0-failed, otherwise returns the OpenGL texture handle
**/
unsigned int
SOIL_load_OGL_cubemap_from_memory
(
const unsigned char *const x_pos_buffer,
int x_pos_buffer_length,
const unsigned char *const x_neg_buffer,
int x_neg_buffer_length,
const unsigned char *const y_pos_buffer,
int y_pos_buffer_length,
const unsigned char *const y_neg_buffer,
int y_neg_buffer_length,
const unsigned char *const z_pos_buffer,
int z_pos_buffer_length,
const unsigned char *const z_neg_buffer,
int z_neg_buffer_length,
int force_channels,
unsigned int reuse_texture_ID,
unsigned int flags
);
/**
Loads 1 image from RAM and splits it into an OpenGL cubemap texture.
\param buffer the image data in RAM just as if it were still in a file
\param buffer_length the size of the buffer in bytes
\param face_order the order of the faces in the file, any combination of NSWEUD, for North, South, Up, etc.
\param force_channels 0-image format, 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA
\param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)
\param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT
\return 0-failed, otherwise returns the OpenGL texture handle
**/
unsigned int
SOIL_load_OGL_single_cubemap_from_memory
(
const unsigned char *const buffer,
int buffer_length,
const char face_order[6],
int force_channels,
unsigned int reuse_texture_ID,
unsigned int flags
);
/**
Creates a 2D OpenGL texture from raw image data. Note that the raw data is
_NOT_ freed after the upload (so the user can load various versions).
\param data the raw data to be uploaded as an OpenGL texture
\param width the width of the image in pixels
\param height the height of the image in pixels
\param channels the number of channels: 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA
\param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)
\param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT
\return 0-failed, otherwise returns the OpenGL texture handle
**/
unsigned int
SOIL_create_OGL_texture
(
const unsigned char *const data,
int width, int height, int channels,
unsigned int reuse_texture_ID,
unsigned int flags
);
/**
Creates an OpenGL cubemap texture by splitting up 1 image into 6 parts.
\param data the raw data to be uploaded as an OpenGL texture
\param width the width of the image in pixels
\param height the height of the image in pixels
\param channels the number of channels: 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA
\param face_order the order of the faces in the file, and combination of NSWEUD, for North, South, Up, etc.
\param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)
\param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT
\return 0-failed, otherwise returns the OpenGL texture handle
**/
unsigned int
SOIL_create_OGL_single_cubemap
(
const unsigned char *const data,
int width, int height, int channels,
const char face_order[6],
unsigned int reuse_texture_ID,
unsigned int flags
);
/**
Captures the OpenGL window (RGB) and saves it to disk
\return 0 if it failed, otherwise returns 1
**/
int
SOIL_save_screenshot
(
const char *filename,
int image_type,
int x, int y,
int width, int height
);
/**
Loads an image from disk into an array of unsigned chars.
Note that *channels return the original channel count of the
image. If force_channels was other than SOIL_LOAD_AUTO,
the resulting image has force_channels, but *channels may be
different (if the original image had a different channel
count).
\return 0 if failed, otherwise returns 1
**/
unsigned char*
SOIL_load_image
(
const char *filename,
int *width, int *height, int *channels,
int force_channels
);
/**
Loads an image from memory into an array of unsigned chars.
Note that *channels return the original channel count of the
image. If force_channels was other than SOIL_LOAD_AUTO,
the resulting image has force_channels, but *channels may be
different (if the original image had a different channel
count).
\return 0 if failed, otherwise returns 1
**/
unsigned char*
SOIL_load_image_from_memory
(
const unsigned char *const buffer,
int buffer_length,
int *width, int *height, int *channels,
int force_channels
);
/**
Saves an image from an array of unsigned chars (RGBA) to disk
\return 0 if failed, otherwise returns 1
**/
int
SOIL_save_image
(
const char *filename,
int image_type,
int width, int height, int channels,
const unsigned char *const data
);
/**
Frees the image data (note, this is just C's "free()"...this function is
present mostly so C++ programmers don't forget to use "free()" and call
"delete []" instead [8^)
**/
void
SOIL_free_image_data
(
unsigned char *img_data
);
/**
This function resturn a pointer to a string describing the last thing
that happened inside SOIL. It can be used to determine why an image
failed to load.
**/
const char*
SOIL_last_result
(
void
);
#ifdef __cplusplus
}
#endif
#endif /* HEADER_SIMPLE_OPENGL_IMAGE_LIBRARY */

View File

@ -0,0 +1,632 @@
/*
Jonathan Dummer
2007-07-31-10.32
simple DXT compression / decompression code
public domain
*/
#include "image_DXT.h"
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
/* set this =1 if you want to use the covarince matrix method...
which is better than my method of using standard deviations
overall, except on the infintesimal chance that the power
method fails for finding the largest eigenvector */
#define USE_COV_MAT 1
/********* Function Prototypes *********/
/*
Takes a 4x4 block of pixels and compresses it into 8 bytes
in DXT1 format (color only, no alpha). Speed is valued
over prettyness, at least for now.
*/
void compress_DDS_color_block(
int channels,
const unsigned char *const uncompressed,
unsigned char compressed[8] );
/*
Takes a 4x4 block of pixels and compresses the alpha
component it into 8 bytes for use in DXT5 DDS files.
Speed is valued over prettyness, at least for now.
*/
void compress_DDS_alpha_block(
const unsigned char *const uncompressed,
unsigned char compressed[8] );
/********* Actual Exposed Functions *********/
int
save_image_as_DDS
(
const char *filename,
int width, int height, int channels,
const unsigned char *const data
)
{
/* variables */
FILE *fout;
unsigned char *DDS_data;
DDS_header header;
int DDS_size;
/* error check */
if( (NULL == filename) ||
(width < 1) || (height < 1) ||
(channels < 1) || (channels > 4) ||
(data == NULL ) )
{
return 0;
}
/* Convert the image */
if( (channels & 1) == 1 )
{
/* no alpha, just use DXT1 */
DDS_data = convert_image_to_DXT1( data, width, height, channels, &DDS_size );
} else
{
/* has alpha, so use DXT5 */
DDS_data = convert_image_to_DXT5( data, width, height, channels, &DDS_size );
}
/* save it */
memset( &header, 0, sizeof( DDS_header ) );
header.dwMagic = ('D' << 0) | ('D' << 8) | ('S' << 16) | (' ' << 24);
header.dwSize = 124;
header.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT | DDSD_LINEARSIZE;
header.dwWidth = width;
header.dwHeight = height;
header.dwPitchOrLinearSize = DDS_size;
header.sPixelFormat.dwSize = 32;
header.sPixelFormat.dwFlags = DDPF_FOURCC;
if( (channels & 1) == 1 )
{
header.sPixelFormat.dwFourCC = ('D' << 0) | ('X' << 8) | ('T' << 16) | ('1' << 24);
} else
{
header.sPixelFormat.dwFourCC = ('D' << 0) | ('X' << 8) | ('T' << 16) | ('5' << 24);
}
header.sCaps.dwCaps1 = DDSCAPS_TEXTURE;
/* write it out */
fout = fopen( filename, "wb");
fwrite( &header, sizeof( DDS_header ), 1, fout );
fwrite( DDS_data, 1, DDS_size, fout );
fclose( fout );
/* done */
free( DDS_data );
return 1;
}
unsigned char* convert_image_to_DXT1(
const unsigned char *const uncompressed,
int width, int height, int channels,
int *out_size )
{
unsigned char *compressed;
int i, j, x, y;
unsigned char ublock[16*3];
unsigned char cblock[8];
int index = 0, chan_step = 1;
int block_count = 0;
/* error check */
*out_size = 0;
if( (width < 1) || (height < 1) ||
(NULL == uncompressed) ||
(channels < 1) || (channels > 4) )
{
return NULL;
}
/* for channels == 1 or 2, I do not step forward for R,G,B values */
if( channels < 3 )
{
chan_step = 0;
}
/* get the RAM for the compressed image
(8 bytes per 4x4 pixel block) */
*out_size = ((width+3) >> 2) * ((height+3) >> 2) * 8;
compressed = (unsigned char*)malloc( *out_size );
/* go through each block */
for( j = 0; j < height; j += 4 )
{
for( i = 0; i < width; i += 4 )
{
/* copy this block into a new one */
int idx = 0;
int mx = 4, my = 4;
if( j+4 >= height )
{
my = height - j;
}
if( i+4 >= width )
{
mx = width - i;
}
for( y = 0; y < my; ++y )
{
for( x = 0; x < mx; ++x )
{
ublock[idx++] = uncompressed[(j+y)*width*channels+(i+x)*channels];
ublock[idx++] = uncompressed[(j+y)*width*channels+(i+x)*channels+chan_step];
ublock[idx++] = uncompressed[(j+y)*width*channels+(i+x)*channels+chan_step+chan_step];
}
for( x = mx; x < 4; ++x )
{
ublock[idx++] = ublock[0];
ublock[idx++] = ublock[1];
ublock[idx++] = ublock[2];
}
}
for( y = my; y < 4; ++y )
{
for( x = 0; x < 4; ++x )
{
ublock[idx++] = ublock[0];
ublock[idx++] = ublock[1];
ublock[idx++] = ublock[2];
}
}
/* compress the block */
++block_count;
compress_DDS_color_block( 3, ublock, cblock );
/* copy the data from the block into the main block */
for( x = 0; x < 8; ++x )
{
compressed[index++] = cblock[x];
}
}
}
return compressed;
}
unsigned char* convert_image_to_DXT5(
const unsigned char *const uncompressed,
int width, int height, int channels,
int *out_size )
{
unsigned char *compressed;
int i, j, x, y;
unsigned char ublock[16*4];
unsigned char cblock[8];
int index = 0, chan_step = 1;
int block_count = 0, has_alpha;
/* error check */
*out_size = 0;
if( (width < 1) || (height < 1) ||
(NULL == uncompressed) ||
(channels < 1) || ( channels > 4) )
{
return NULL;
}
/* for channels == 1 or 2, I do not step forward for R,G,B vales */
if( channels < 3 )
{
chan_step = 0;
}
/* # channels = 1 or 3 have no alpha, 2 & 4 do have alpha */
has_alpha = 1 - (channels & 1);
/* get the RAM for the compressed image
(16 bytes per 4x4 pixel block) */
*out_size = ((width+3) >> 2) * ((height+3) >> 2) * 16;
compressed = (unsigned char*)malloc( *out_size );
/* go through each block */
for( j = 0; j < height; j += 4 )
{
for( i = 0; i < width; i += 4 )
{
/* local variables, and my block counter */
int idx = 0;
int mx = 4, my = 4;
if( j+4 >= height )
{
my = height - j;
}
if( i+4 >= width )
{
mx = width - i;
}
for( y = 0; y < my; ++y )
{
for( x = 0; x < mx; ++x )
{
ublock[idx++] = uncompressed[(j+y)*width*channels+(i+x)*channels];
ublock[idx++] = uncompressed[(j+y)*width*channels+(i+x)*channels+chan_step];
ublock[idx++] = uncompressed[(j+y)*width*channels+(i+x)*channels+chan_step+chan_step];
ublock[idx++] =
has_alpha * uncompressed[(j+y)*width*channels+(i+x)*channels+channels-1]
+ (1-has_alpha)*255;
}
for( x = mx; x < 4; ++x )
{
ublock[idx++] = ublock[0];
ublock[idx++] = ublock[1];
ublock[idx++] = ublock[2];
ublock[idx++] = ublock[3];
}
}
for( y = my; y < 4; ++y )
{
for( x = 0; x < 4; ++x )
{
ublock[idx++] = ublock[0];
ublock[idx++] = ublock[1];
ublock[idx++] = ublock[2];
ublock[idx++] = ublock[3];
}
}
/* now compress the alpha block */
compress_DDS_alpha_block( ublock, cblock );
/* copy the data from the compressed alpha block into the main buffer */
for( x = 0; x < 8; ++x )
{
compressed[index++] = cblock[x];
}
/* then compress the color block */
++block_count;
compress_DDS_color_block( 4, ublock, cblock );
/* copy the data from the compressed color block into the main buffer */
for( x = 0; x < 8; ++x )
{
compressed[index++] = cblock[x];
}
}
}
return compressed;
}
/********* Helper Functions *********/
int convert_bit_range( int c, int from_bits, int to_bits )
{
int b = (1 << (from_bits - 1)) + c * ((1 << to_bits) - 1);
return (b + (b >> from_bits)) >> from_bits;
}
int rgb_to_565( int r, int g, int b )
{
return
(convert_bit_range( r, 8, 5 ) << 11) |
(convert_bit_range( g, 8, 6 ) << 05) |
(convert_bit_range( b, 8, 5 ) << 00);
}
void rgb_888_from_565( unsigned int c, int *r, int *g, int *b )
{
*r = convert_bit_range( (c >> 11) & 31, 5, 8 );
*g = convert_bit_range( (c >> 05) & 63, 6, 8 );
*b = convert_bit_range( (c >> 00) & 31, 5, 8 );
}
void compute_color_line_STDEV(
const unsigned char *const uncompressed,
int channels,
float point[3], float direction[3] )
{
const float inv_16 = 1.0f / 16.0f;
int i;
float sum_r = 0.0f, sum_g = 0.0f, sum_b = 0.0f;
float sum_rr = 0.0f, sum_gg = 0.0f, sum_bb = 0.0f;
float sum_rg = 0.0f, sum_rb = 0.0f, sum_gb = 0.0f;
/* calculate all data needed for the covariance matrix
( to compare with _rygdxt code) */
for( i = 0; i < 16*channels; i += channels )
{
sum_r += uncompressed[i+0];
sum_rr += uncompressed[i+0] * uncompressed[i+0];
sum_g += uncompressed[i+1];
sum_gg += uncompressed[i+1] * uncompressed[i+1];
sum_b += uncompressed[i+2];
sum_bb += uncompressed[i+2] * uncompressed[i+2];
sum_rg += uncompressed[i+0] * uncompressed[i+1];
sum_rb += uncompressed[i+0] * uncompressed[i+2];
sum_gb += uncompressed[i+1] * uncompressed[i+2];
}
/* convert the sums to averages */
sum_r *= inv_16;
sum_g *= inv_16;
sum_b *= inv_16;
/* and convert the squares to the squares of the value - avg_value */
sum_rr -= 16.0f * sum_r * sum_r;
sum_gg -= 16.0f * sum_g * sum_g;
sum_bb -= 16.0f * sum_b * sum_b;
sum_rg -= 16.0f * sum_r * sum_g;
sum_rb -= 16.0f * sum_r * sum_b;
sum_gb -= 16.0f * sum_g * sum_b;
/* the point on the color line is the average */
point[0] = sum_r;
point[1] = sum_g;
point[2] = sum_b;
#if USE_COV_MAT
/*
The following idea was from ryg.
(https://mollyrocket.com/forums/viewtopic.php?t=392)
The method worked great (less RMSE than mine) most of
the time, but had some issues handling some simple
boundary cases, like full green next to full red,
which would generate a covariance matrix like this:
| 1 -1 0 |
| -1 1 0 |
| 0 0 0 |
For a given starting vector, the power method can
generate all zeros! So no starting with {1,1,1}
as I was doing! This kind of error is still a
slight posibillity, but will be very rare.
*/
/* use the covariance matrix directly
(1st iteration, don't use all 1.0 values!) */
sum_r = 1.0f;
sum_g = 2.718281828f;
sum_b = 3.141592654f;
direction[0] = sum_r*sum_rr + sum_g*sum_rg + sum_b*sum_rb;
direction[1] = sum_r*sum_rg + sum_g*sum_gg + sum_b*sum_gb;
direction[2] = sum_r*sum_rb + sum_g*sum_gb + sum_b*sum_bb;
/* 2nd iteration, use results from the 1st guy */
sum_r = direction[0];
sum_g = direction[1];
sum_b = direction[2];
direction[0] = sum_r*sum_rr + sum_g*sum_rg + sum_b*sum_rb;
direction[1] = sum_r*sum_rg + sum_g*sum_gg + sum_b*sum_gb;
direction[2] = sum_r*sum_rb + sum_g*sum_gb + sum_b*sum_bb;
/* 3rd iteration, use results from the 2nd guy */
sum_r = direction[0];
sum_g = direction[1];
sum_b = direction[2];
direction[0] = sum_r*sum_rr + sum_g*sum_rg + sum_b*sum_rb;
direction[1] = sum_r*sum_rg + sum_g*sum_gg + sum_b*sum_gb;
direction[2] = sum_r*sum_rb + sum_g*sum_gb + sum_b*sum_bb;
#else
/* use my standard deviation method
(very robust, a tiny bit slower and less accurate) */
direction[0] = sqrt( sum_rr );
direction[1] = sqrt( sum_gg );
direction[2] = sqrt( sum_bb );
/* which has a greater component */
if( sum_gg > sum_rr )
{
/* green has greater component, so base the other signs off of green */
if( sum_rg < 0.0f )
{
direction[0] = -direction[0];
}
if( sum_gb < 0.0f )
{
direction[2] = -direction[2];
}
} else
{
/* red has a greater component */
if( sum_rg < 0.0f )
{
direction[1] = -direction[1];
}
if( sum_rb < 0.0f )
{
direction[2] = -direction[2];
}
}
#endif
}
void LSE_master_colors_max_min(
int *cmax, int *cmin,
int channels,
const unsigned char *const uncompressed )
{
int i, j;
/* the master colors */
int c0[3], c1[3];
/* used for fitting the line */
float sum_x[] = { 0.0f, 0.0f, 0.0f };
float sum_x2[] = { 0.0f, 0.0f, 0.0f };
float dot_max = 1.0f, dot_min = -1.0f;
float vec_len2 = 0.0f;
float dot;
/* error check */
if( (channels < 3) || (channels > 4) )
{
return;
}
compute_color_line_STDEV( uncompressed, channels, sum_x, sum_x2 );
vec_len2 = 1.0f / ( 0.00001f +
sum_x2[0]*sum_x2[0] + sum_x2[1]*sum_x2[1] + sum_x2[2]*sum_x2[2] );
/* finding the max and min vector values */
dot_max =
(
sum_x2[0] * uncompressed[0] +
sum_x2[1] * uncompressed[1] +
sum_x2[2] * uncompressed[2]
);
dot_min = dot_max;
for( i = 1; i < 16; ++i )
{
dot =
(
sum_x2[0] * uncompressed[i*channels+0] +
sum_x2[1] * uncompressed[i*channels+1] +
sum_x2[2] * uncompressed[i*channels+2]
);
if( dot < dot_min )
{
dot_min = dot;
} else if( dot > dot_max )
{
dot_max = dot;
}
}
/* and the offset (from the average location) */
dot = sum_x2[0]*sum_x[0] + sum_x2[1]*sum_x[1] + sum_x2[2]*sum_x[2];
dot_min -= dot;
dot_max -= dot;
/* post multiply by the scaling factor */
dot_min *= vec_len2;
dot_max *= vec_len2;
/* OK, build the master colors */
for( i = 0; i < 3; ++i )
{
/* color 0 */
c0[i] = (int)(0.5f + sum_x[i] + dot_max * sum_x2[i]);
if( c0[i] < 0 )
{
c0[i] = 0;
} else if( c0[i] > 255 )
{
c0[i] = 255;
}
/* color 1 */
c1[i] = (int)(0.5f + sum_x[i] + dot_min * sum_x2[i]);
if( c1[i] < 0 )
{
c1[i] = 0;
} else if( c1[i] > 255 )
{
c1[i] = 255;
}
}
/* down_sample (with rounding?) */
i = rgb_to_565( c0[0], c0[1], c0[2] );
j = rgb_to_565( c1[0], c1[1], c1[2] );
if( i > j )
{
*cmax = i;
*cmin = j;
} else
{
*cmax = j;
*cmin = i;
}
}
void
compress_DDS_color_block
(
int channels,
const unsigned char *const uncompressed,
unsigned char compressed[8]
)
{
/* variables */
int i;
int next_bit;
int enc_c0, enc_c1;
int c0[4], c1[4];
float color_line[] = { 0.0f, 0.0f, 0.0f, 0.0f };
float vec_len2 = 0.0f, dot_offset = 0.0f;
/* stupid order */
int swizzle4[] = { 0, 2, 3, 1 };
/* get the master colors */
LSE_master_colors_max_min( &enc_c0, &enc_c1, channels, uncompressed );
/* store the 565 color 0 and color 1 */
compressed[0] = (enc_c0 >> 0) & 255;
compressed[1] = (enc_c0 >> 8) & 255;
compressed[2] = (enc_c1 >> 0) & 255;
compressed[3] = (enc_c1 >> 8) & 255;
/* zero out the compressed data */
compressed[4] = 0;
compressed[5] = 0;
compressed[6] = 0;
compressed[7] = 0;
/* reconstitute the master color vectors */
rgb_888_from_565( enc_c0, &c0[0], &c0[1], &c0[2] );
rgb_888_from_565( enc_c1, &c1[0], &c1[1], &c1[2] );
/* the new vector */
vec_len2 = 0.0f;
for( i = 0; i < 3; ++i )
{
color_line[i] = (float)(c1[i] - c0[i]);
vec_len2 += color_line[i] * color_line[i];
}
if( vec_len2 > 0.0f )
{
vec_len2 = 1.0f / vec_len2;
}
/* pre-proform the scaling */
color_line[0] *= vec_len2;
color_line[1] *= vec_len2;
color_line[2] *= vec_len2;
/* compute the offset (constant) portion of the dot product */
dot_offset = color_line[0]*c0[0] + color_line[1]*c0[1] + color_line[2]*c0[2];
/* store the rest of the bits */
next_bit = 8*4;
for( i = 0; i < 16; ++i )
{
/* find the dot product of this color, to place it on the line
(should be [-1,1]) */
int next_value = 0;
float dot_product =
color_line[0] * uncompressed[i*channels+0] +
color_line[1] * uncompressed[i*channels+1] +
color_line[2] * uncompressed[i*channels+2] -
dot_offset;
/* map to [0,3] */
next_value = (int)( dot_product * 3.0f + 0.5f );
if( next_value > 3 )
{
next_value = 3;
} else if( next_value < 0 )
{
next_value = 0;
}
/* OK, store this value */
compressed[next_bit >> 3] |= swizzle4[ next_value ] << (next_bit & 7);
next_bit += 2;
}
/* done compressing to DXT1 */
}
void
compress_DDS_alpha_block
(
const unsigned char *const uncompressed,
unsigned char compressed[8]
)
{
/* variables */
int i;
int next_bit;
int a0, a1;
float scale_me;
/* stupid order */
int swizzle8[] = { 1, 7, 6, 5, 4, 3, 2, 0 };
/* get the alpha limits (a0 > a1) */
a0 = a1 = uncompressed[3];
for( i = 4+3; i < 16*4; i += 4 )
{
if( uncompressed[i] > a0 )
{
a0 = uncompressed[i];
} else if( uncompressed[i] < a1 )
{
a1 = uncompressed[i];
}
}
/* store those limits, and zero the rest of the compressed dataset */
compressed[0] = a0;
compressed[1] = a1;
/* zero out the compressed data */
compressed[2] = 0;
compressed[3] = 0;
compressed[4] = 0;
compressed[5] = 0;
compressed[6] = 0;
compressed[7] = 0;
/* store the all of the alpha values */
next_bit = 8*2;
scale_me = 7.9999f / (a0 - a1);
for( i = 3; i < 16*4; i += 4 )
{
/* convert this alpha value to a 3 bit number */
int svalue;
int value = (int)((uncompressed[i] - a1) * scale_me);
svalue = swizzle8[ value&7 ];
/* OK, store this value, start with the 1st byte */
compressed[next_bit >> 3] |= svalue << (next_bit & 7);
if( (next_bit & 7) > 5 )
{
/* spans 2 bytes, fill in the start of the 2nd byte */
compressed[1 + (next_bit >> 3)] |= svalue >> (8 - (next_bit & 7) );
}
next_bit += 3;
}
/* done compressing to DXT1 */
}

View File

@ -0,0 +1,123 @@
/*
Jonathan Dummer
2007-07-31-10.32
simple DXT compression / decompression code
public domain
*/
#ifndef HEADER_IMAGE_DXT
#define HEADER_IMAGE_DXT
/**
Converts an image from an array of unsigned chars (RGB or RGBA) to
DXT1 or DXT5, then saves the converted image to disk.
\return 0 if failed, otherwise returns 1
**/
int
save_image_as_DDS
(
const char *filename,
int width, int height, int channels,
const unsigned char *const data
);
/**
take an image and convert it to DXT1 (no alpha)
**/
unsigned char*
convert_image_to_DXT1
(
const unsigned char *const uncompressed,
int width, int height, int channels,
int *out_size
);
/**
take an image and convert it to DXT5 (with alpha)
**/
unsigned char*
convert_image_to_DXT5
(
const unsigned char *const uncompressed,
int width, int height, int channels,
int *out_size
);
/** A bunch of DirectDraw Surface structures and flags **/
typedef struct
{
unsigned int dwMagic;
unsigned int dwSize;
unsigned int dwFlags;
unsigned int dwHeight;
unsigned int dwWidth;
unsigned int dwPitchOrLinearSize;
unsigned int dwDepth;
unsigned int dwMipMapCount;
unsigned int dwReserved1[ 11 ];
/* DDPIXELFORMAT */
struct
{
unsigned int dwSize;
unsigned int dwFlags;
unsigned int dwFourCC;
unsigned int dwRGBBitCount;
unsigned int dwRBitMask;
unsigned int dwGBitMask;
unsigned int dwBBitMask;
unsigned int dwAlphaBitMask;
}
sPixelFormat;
/* DDCAPS2 */
struct
{
unsigned int dwCaps1;
unsigned int dwCaps2;
unsigned int dwDDSX;
unsigned int dwReserved;
}
sCaps;
unsigned int dwReserved2;
}
DDS_header ;
/* the following constants were copied directly off the MSDN website */
/* The dwFlags member of the original DDSURFACEDESC2 structure
can be set to one or more of the following values. */
#define DDSD_CAPS 0x00000001
#define DDSD_HEIGHT 0x00000002
#define DDSD_WIDTH 0x00000004
#define DDSD_PITCH 0x00000008
#define DDSD_PIXELFORMAT 0x00001000
#define DDSD_MIPMAPCOUNT 0x00020000
#define DDSD_LINEARSIZE 0x00080000
#define DDSD_DEPTH 0x00800000
/* DirectDraw Pixel Format */
#define DDPF_ALPHAPIXELS 0x00000001
#define DDPF_FOURCC 0x00000004
#define DDPF_RGB 0x00000040
/* The dwCaps1 member of the DDSCAPS2 structure can be
set to one or more of the following values. */
#define DDSCAPS_COMPLEX 0x00000008
#define DDSCAPS_TEXTURE 0x00001000
#define DDSCAPS_MIPMAP 0x00400000
/* The dwCaps2 member of the DDSCAPS2 structure can be
set to one or more of the following values. */
#define DDSCAPS2_CUBEMAP 0x00000200
#define DDSCAPS2_CUBEMAP_POSITIVEX 0x00000400
#define DDSCAPS2_CUBEMAP_NEGATIVEX 0x00000800
#define DDSCAPS2_CUBEMAP_POSITIVEY 0x00001000
#define DDSCAPS2_CUBEMAP_NEGATIVEY 0x00002000
#define DDSCAPS2_CUBEMAP_POSITIVEZ 0x00004000
#define DDSCAPS2_CUBEMAP_NEGATIVEZ 0x00008000
#define DDSCAPS2_VOLUME 0x00200000
#endif /* HEADER_IMAGE_DXT */

View File

@ -0,0 +1,435 @@
/*
Jonathan Dummer
image helper functions
MIT license
*/
#include "image_helper.h"
#include <stdlib.h>
#include <math.h>
/* Upscaling the image uses simple bilinear interpolation */
int
up_scale_image
(
const unsigned char* const orig,
int width, int height, int channels,
unsigned char* resampled,
int resampled_width, int resampled_height
)
{
float dx, dy;
int x, y, c;
/* error(s) check */
if ( (width < 1) || (height < 1) ||
(resampled_width < 2) || (resampled_height < 2) ||
(channels < 1) ||
(NULL == orig) || (NULL == resampled) )
{
/* signify badness */
return 0;
}
/*
for each given pixel in the new map, find the exact location
from the original map which would contribute to this guy
*/
dx = (width - 1.0f) / (resampled_width - 1.0f);
dy = (height - 1.0f) / (resampled_height - 1.0f);
for ( y = 0; y < resampled_height; ++y )
{
/* find the base y index and fractional offset from that */
float sampley = y * dy;
int inty = (int)sampley;
/* if( inty < 0 ) { inty = 0; } else */
if( inty > height - 2 ) { inty = height - 2; }
sampley -= inty;
for ( x = 0; x < resampled_width; ++x )
{
float samplex = x * dx;
int intx = (int)samplex;
int base_index;
/* find the base x index and fractional offset from that */
/* if( intx < 0 ) { intx = 0; } else */
if( intx > width - 2 ) { intx = width - 2; }
samplex -= intx;
/* base index into the original image */
base_index = (inty * width + intx) * channels;
for ( c = 0; c < channels; ++c )
{
/* do the sampling */
float value = 0.5f;
value += orig[base_index]
*(1.0f-samplex)*(1.0f-sampley);
value += orig[base_index+channels]
*(samplex)*(1.0f-sampley);
value += orig[base_index+width*channels]
*(1.0f-samplex)*(sampley);
value += orig[base_index+width*channels+channels]
*(samplex)*(sampley);
/* move to the next channel */
++base_index;
/* save the new value */
resampled[y*resampled_width*channels+x*channels+c] =
(unsigned char)(value);
}
}
}
/* done */
return 1;
}
int
mipmap_image
(
const unsigned char* const orig,
int width, int height, int channels,
unsigned char* resampled,
int block_size_x, int block_size_y
)
{
int mip_width, mip_height;
int i, j, c;
/* error check */
if( (width < 1) || (height < 1) ||
(channels < 1) || (orig == NULL) ||
(resampled == NULL) ||
(block_size_x < 1) || (block_size_y < 1) )
{
/* nothing to do */
return 0;
}
mip_width = width / block_size_x;
mip_height = height / block_size_y;
if( mip_width < 1 )
{
mip_width = 1;
}
if( mip_height < 1 )
{
mip_height = 1;
}
for( j = 0; j < mip_height; ++j )
{
for( i = 0; i < mip_width; ++i )
{
for( c = 0; c < channels; ++c )
{
const int index = (j*block_size_y)*width*channels + (i*block_size_x)*channels + c;
int sum_value;
int u,v;
int u_block = block_size_x;
int v_block = block_size_y;
int block_area;
/* do a bit of checking so we don't over-run the boundaries
(necessary for non-square textures!) */
if( block_size_x * (i+1) > width )
{
u_block = width - i*block_size_y;
}
if( block_size_y * (j+1) > height )
{
v_block = height - j*block_size_y;
}
block_area = u_block*v_block;
/* for this pixel, see what the average
of all the values in the block are.
note: start the sum at the rounding value, not at 0 */
sum_value = block_area >> 1;
for( v = 0; v < v_block; ++v )
for( u = 0; u < u_block; ++u )
{
sum_value += orig[index + v*width*channels + u*channels];
}
resampled[j*mip_width*channels + i*channels + c] = sum_value / block_area;
}
}
}
return 1;
}
int
scale_image_RGB_to_NTSC_safe
(
unsigned char* orig,
int width, int height, int channels
)
{
const float scale_lo = 16.0f - 0.499f;
const float scale_hi = 235.0f + 0.499f;
int i, j;
int nc = channels;
unsigned char scale_LUT[256];
/* error check */
if( (width < 1) || (height < 1) ||
(channels < 1) || (orig == NULL) )
{
/* nothing to do */
return 0;
}
/* set up the scaling Look Up Table */
for( i = 0; i < 256; ++i )
{
scale_LUT[i] = (unsigned char)((scale_hi - scale_lo) * i / 255.0f + scale_lo);
}
/* for channels = 2 or 4, ignore the alpha component */
nc -= 1 - (channels & 1);
/* OK, go through the image and scale any non-alpha components */
for( i = 0; i < width*height*channels; i += channels )
{
for( j = 0; j < nc; ++j )
{
orig[i+j] = scale_LUT[orig[i+j]];
}
}
return 1;
}
unsigned char clamp_byte( int x ) { return ( (x) < 0 ? (0) : ( (x) > 255 ? 255 : (x) ) ); }
/*
This function takes the RGB components of the image
and converts them into YCoCg. 3 components will be
re-ordered to CoYCg (for optimum DXT1 compression),
while 4 components will be ordered CoCgAY (for DXT5
compression).
*/
int
convert_RGB_to_YCoCg
(
unsigned char* orig,
int width, int height, int channels
)
{
int i;
/* error check */
if( (width < 1) || (height < 1) ||
(channels < 3) || (channels > 4) ||
(orig == NULL) )
{
/* nothing to do */
return -1;
}
/* do the conversion */
if( channels == 3 )
{
for( i = 0; i < width*height*3; i += 3 )
{
int r = orig[i+0];
int g = (orig[i+1] + 1) >> 1;
int b = orig[i+2];
int tmp = (2 + r + b) >> 2;
/* Co */
orig[i+0] = clamp_byte( 128 + ((r - b + 1) >> 1) );
/* Y */
orig[i+1] = clamp_byte( g + tmp );
/* Cg */
orig[i+2] = clamp_byte( 128 + g - tmp );
}
} else
{
for( i = 0; i < width*height*4; i += 4 )
{
int r = orig[i+0];
int g = (orig[i+1] + 1) >> 1;
int b = orig[i+2];
unsigned char a = orig[i+3];
int tmp = (2 + r + b) >> 2;
/* Co */
orig[i+0] = clamp_byte( 128 + ((r - b + 1) >> 1) );
/* Cg */
orig[i+1] = clamp_byte( 128 + g - tmp );
/* Alpha */
orig[i+2] = a;
/* Y */
orig[i+3] = clamp_byte( g + tmp );
}
}
/* done */
return 0;
}
/*
This function takes the YCoCg components of the image
and converts them into RGB. See above.
*/
int
convert_YCoCg_to_RGB
(
unsigned char* orig,
int width, int height, int channels
)
{
int i;
/* error check */
if( (width < 1) || (height < 1) ||
(channels < 3) || (channels > 4) ||
(orig == NULL) )
{
/* nothing to do */
return -1;
}
/* do the conversion */
if( channels == 3 )
{
for( i = 0; i < width*height*3; i += 3 )
{
int co = orig[i+0] - 128;
int y = orig[i+1];
int cg = orig[i+2] - 128;
/* R */
orig[i+0] = clamp_byte( y + co - cg );
/* G */
orig[i+1] = clamp_byte( y + cg );
/* B */
orig[i+2] = clamp_byte( y - co - cg );
}
} else
{
for( i = 0; i < width*height*4; i += 4 )
{
int co = orig[i+0] - 128;
int cg = orig[i+1] - 128;
unsigned char a = orig[i+2];
int y = orig[i+3];
/* R */
orig[i+0] = clamp_byte( y + co - cg );
/* G */
orig[i+1] = clamp_byte( y + cg );
/* B */
orig[i+2] = clamp_byte( y - co - cg );
/* A */
orig[i+3] = a;
}
}
/* done */
return 0;
}
float
find_max_RGBE
(
unsigned char *image,
int width, int height
)
{
float max_val = 0.0f;
unsigned char *img = image;
int i, j;
for( i = width * height; i > 0; --i )
{
/* float scale = powf( 2.0f, img[3] - 128.0f ) / 255.0f; */
float scale = ldexp( 1.0f / 255.0f, (int)(img[3]) - 128 );
for( j = 0; j < 3; ++j )
{
if( img[j] * scale > max_val )
{
max_val = img[j] * scale;
}
}
/* next pixel */
img += 4;
}
return max_val;
}
int
RGBE_to_RGBdivA
(
unsigned char *image,
int width, int height,
int rescale_to_max
)
{
/* local variables */
int i, iv;
unsigned char *img = image;
float scale = 1.0f;
/* error check */
if( (!image) || (width < 1) || (height < 1) )
{
return 0;
}
/* convert (note: no negative numbers, but 0.0 is possible) */
if( rescale_to_max )
{
scale = 255.0f / find_max_RGBE( image, width, height );
}
for( i = width * height; i > 0; --i )
{
/* decode this pixel, and find the max */
float r,g,b,e, m;
/* e = scale * powf( 2.0f, img[3] - 128.0f ) / 255.0f; */
e = scale * ldexp( 1.0f / 255.0f, (int)(img[3]) - 128 );
r = e * img[0];
g = e * img[1];
b = e * img[2];
m = (r > g) ? r : g;
m = (b > m) ? b : m;
/* and encode it into RGBdivA */
iv = (m != 0.0f) ? (int)(255.0f / m) : 1.0f;
iv = (iv < 1) ? 1 : iv;
img[3] = (iv > 255) ? 255 : iv;
iv = (int)(img[3] * r + 0.5f);
img[0] = (iv > 255) ? 255 : iv;
iv = (int)(img[3] * g + 0.5f);
img[1] = (iv > 255) ? 255 : iv;
iv = (int)(img[3] * b + 0.5f);
img[2] = (iv > 255) ? 255 : iv;
/* and on to the next pixel */
img += 4;
}
return 1;
}
int
RGBE_to_RGBdivA2
(
unsigned char *image,
int width, int height,
int rescale_to_max
)
{
/* local variables */
int i, iv;
unsigned char *img = image;
float scale = 1.0f;
/* error check */
if( (!image) || (width < 1) || (height < 1) )
{
return 0;
}
/* convert (note: no negative numbers, but 0.0 is possible) */
if( rescale_to_max )
{
scale = 255.0f * 255.0f / find_max_RGBE( image, width, height );
}
for( i = width * height; i > 0; --i )
{
/* decode this pixel, and find the max */
float r,g,b,e, m;
/* e = scale * powf( 2.0f, img[3] - 128.0f ) / 255.0f; */
e = scale * ldexp( 1.0f / 255.0f, (int)(img[3]) - 128 );
r = e * img[0];
g = e * img[1];
b = e * img[2];
m = (r > g) ? r : g;
m = (b > m) ? b : m;
/* and encode it into RGBdivA */
iv = (m != 0.0f) ? (int)sqrtf( 255.0f * 255.0f / m ) : 1.0f;
iv = (iv < 1) ? 1 : iv;
img[3] = (iv > 255) ? 255 : iv;
iv = (int)(img[3] * img[3] * r / 255.0f + 0.5f);
img[0] = (iv > 255) ? 255 : iv;
iv = (int)(img[3] * img[3] * g / 255.0f + 0.5f);
img[1] = (iv > 255) ? 255 : iv;
iv = (int)(img[3] * img[3] * b / 255.0f + 0.5f);
img[2] = (iv > 255) ? 255 : iv;
/* and on to the next pixel */
img += 4;
}
return 1;
}

View File

@ -0,0 +1,115 @@
/*
Jonathan Dummer
Image helper functions
MIT license
*/
#ifndef HEADER_IMAGE_HELPER
#define HEADER_IMAGE_HELPER
#ifdef __cplusplus
extern "C" {
#endif
/**
This function upscales an image.
Not to be used to create MIPmaps,
but to make it square,
or to make it a power-of-two sized.
**/
int
up_scale_image
(
const unsigned char* const orig,
int width, int height, int channels,
unsigned char* resampled,
int resampled_width, int resampled_height
);
/**
This function downscales an image.
Used for creating MIPmaps,
the incoming image should be a
power-of-two sized.
**/
int
mipmap_image
(
const unsigned char* const orig,
int width, int height, int channels,
unsigned char* resampled,
int block_size_x, int block_size_y
);
/**
This function takes the RGB components of the image
and scales each channel from [0,255] to [16,235].
This makes the colors "Safe" for display on NTSC
displays. Note that this is _NOT_ a good idea for
loading images like normal- or height-maps!
**/
int
scale_image_RGB_to_NTSC_safe
(
unsigned char* orig,
int width, int height, int channels
);
/**
This function takes the RGB components of the image
and converts them into YCoCg. 3 components will be
re-ordered to CoYCg (for optimum DXT1 compression),
while 4 components will be ordered CoCgAY (for DXT5
compression).
**/
int
convert_RGB_to_YCoCg
(
unsigned char* orig,
int width, int height, int channels
);
/**
This function takes the YCoCg components of the image
and converts them into RGB. See above.
**/
int
convert_YCoCg_to_RGB
(
unsigned char* orig,
int width, int height, int channels
);
/**
Converts an HDR image from an array
of unsigned chars (RGBE) to RGBdivA
\return 0 if failed, otherwise returns 1
**/
int
RGBE_to_RGBdivA
(
unsigned char *image,
int width, int height,
int rescale_to_max
);
/**
Converts an HDR image from an array
of unsigned chars (RGBE) to RGBdivA2
\return 0 if failed, otherwise returns 1
**/
int
RGBE_to_RGBdivA2
(
unsigned char *image,
int width, int height,
int rescale_to_max
);
#ifdef __cplusplus
}
#endif
#endif /* HEADER_IMAGE_HELPER */

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,354 @@
/* stbi-1.16 - public domain JPEG/PNG reader - http://nothings.org/stb_image.c
when you control the images you're loading
QUICK NOTES:
Primarily of interest to game developers and other people who can
avoid problematic images and only need the trivial interface
JPEG baseline (no JPEG progressive, no oddball channel decimations)
PNG non-interlaced
BMP non-1bpp, non-RLE
TGA (not sure what subset, if a subset)
PSD (composited view only, no extra channels)
HDR (radiance rgbE format)
writes BMP,TGA (define STBI_NO_WRITE to remove code)
decoded from memory or through stdio FILE (define STBI_NO_STDIO to remove code)
supports installable dequantizing-IDCT, YCbCr-to-RGB conversion (define STBI_SIMD)
TODO:
stbi_info_*
history:
1.16 major bugfix - convert_format converted one too many pixels
1.15 initialize some fields for thread safety
1.14 fix threadsafe conversion bug; header-file-only version (#define STBI_HEADER_FILE_ONLY before including)
1.13 threadsafe
1.12 const qualifiers in the API
1.11 Support installable IDCT, colorspace conversion routines
1.10 Fixes for 64-bit (don't use "unsigned long")
optimized upsampling by Fabian "ryg" Giesen
1.09 Fix format-conversion for PSD code (bad global variables!)
1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz
1.07 attempt to fix C++ warning/errors again
1.06 attempt to fix C++ warning/errors again
1.05 fix TGA loading to return correct *comp and use good luminance calc
1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free
1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR
1.02 support for (subset of) HDR files, float interface for preferred access to them
1.01 fix bug: possible bug in handling right-side up bmps... not sure
fix bug: the stbi_bmp_load() and stbi_tga_load() functions didn't work at all
1.00 interface to zlib that skips zlib header
0.99 correct handling of alpha in palette
0.98 TGA loader by lonesock; dynamically add loaders (untested)
0.97 jpeg errors on too large a file; also catch another malloc failure
0.96 fix detection of invalid v value - particleman@mollyrocket forum
0.95 during header scan, seek to markers in case of padding
0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same
0.93 handle jpegtran output; verbose errors
0.92 read 4,8,16,24,32-bit BMP files of several formats
0.91 output 24-bit Windows 3.0 BMP files
0.90 fix a few more warnings; bump version number to approach 1.0
0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd
0.60 fix compiling as c++
0.59 fix warnings: merge Dave Moore's -Wall fixes
0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian
0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less
than 16 available
0.56 fix bug: zlib uncompressed mode len vs. nlen
0.55 fix bug: restart_interval not initialized to 0
0.54 allow NULL for 'int *comp'
0.53 fix bug in png 3->4; speedup png decoding
0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments
0.51 obey req_comp requests, 1-component jpegs return as 1-component,
on 'test' only check type, not whether we support this variant
*/
#ifndef HEADER_STB_IMAGE_AUGMENTED
#define HEADER_STB_IMAGE_AUGMENTED
//// begin header file ////////////////////////////////////////////////////
//
// Limitations:
// - no progressive/interlaced support (jpeg, png)
// - 8-bit samples only (jpeg, png)
// - not threadsafe
// - channel subsampling of at most 2 in each dimension (jpeg)
// - no delayed line count (jpeg) -- IJG doesn't support either
//
// Basic usage (see HDR discussion below):
// int x,y,n;
// unsigned char *data = stbi_load(filename, &x, &y, &n, 0);
// // ... process data if not NULL ...
// // ... x = width, y = height, n = # 8-bit components per pixel ...
// // ... replace '0' with '1'..'4' to force that many components per pixel
// stbi_image_free(data)
//
// Standard parameters:
// int *x -- outputs image width in pixels
// int *y -- outputs image height in pixels
// int *comp -- outputs # of image components in image file
// int req_comp -- if non-zero, # of image components requested in result
//
// The return value from an image loader is an 'unsigned char *' which points
// to the pixel data. The pixel data consists of *y scanlines of *x pixels,
// with each pixel consisting of N interleaved 8-bit components; the first
// pixel pointed to is top-left-most in the image. There is no padding between
// image scanlines or between pixels, regardless of format. The number of
// components N is 'req_comp' if req_comp is non-zero, or *comp otherwise.
// If req_comp is non-zero, *comp has the number of components that _would_
// have been output otherwise. E.g. if you set req_comp to 4, you will always
// get RGBA output, but you can check *comp to easily see if it's opaque.
//
// An output image with N components has the following components interleaved
// in this order in each pixel:
//
// N=#comp components
// 1 grey
// 2 grey, alpha
// 3 red, green, blue
// 4 red, green, blue, alpha
//
// If image loading fails for any reason, the return value will be NULL,
// and *x, *y, *comp will be unchanged. The function stbi_failure_reason()
// can be queried for an extremely brief, end-user unfriendly explanation
// of why the load failed. Define STBI_NO_FAILURE_STRINGS to avoid
// compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly
// more user-friendly ones.
//
// Paletted PNG and BMP images are automatically depalettized.
//
//
// ===========================================================================
//
// HDR image support (disable by defining STBI_NO_HDR)
//
// stb_image now supports loading HDR images in general, and currently
// the Radiance .HDR file format, although the support is provided
// generically. You can still load any file through the existing interface;
// if you attempt to load an HDR file, it will be automatically remapped to
// LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1;
// both of these constants can be reconfigured through this interface:
//
// stbi_hdr_to_ldr_gamma(2.2f);
// stbi_hdr_to_ldr_scale(1.0f);
//
// (note, do not use _inverse_ constants; stbi_image will invert them
// appropriately).
//
// Additionally, there is a new, parallel interface for loading files as
// (linear) floats to preserve the full dynamic range:
//
// float *data = stbi_loadf(filename, &x, &y, &n, 0);
//
// If you load LDR images through this interface, those images will
// be promoted to floating point values, run through the inverse of
// constants corresponding to the above:
//
// stbi_ldr_to_hdr_scale(1.0f);
// stbi_ldr_to_hdr_gamma(2.2f);
//
// Finally, given a filename (or an open file or memory block--see header
// file for details) containing image data, you can query for the "most
// appropriate" interface to use (that is, whether the image is HDR or
// not), using:
//
// stbi_is_hdr(char *filename);
#ifndef STBI_NO_STDIO
#include <stdio.h>
#endif
#define STBI_VERSION 1
enum
{
STBI_default = 0, // only used for req_comp
STBI_grey = 1,
STBI_grey_alpha = 2,
STBI_rgb = 3,
STBI_rgb_alpha = 4,
};
typedef unsigned char stbi_uc;
#ifdef __cplusplus
extern "C" {
#endif
// WRITING API
#if !defined(STBI_NO_WRITE) && !defined(STBI_NO_STDIO)
// write a BMP/TGA file given tightly packed 'comp' channels (no padding, nor bmp-stride-padding)
// (you must include the appropriate extension in the filename).
// returns TRUE on success, FALSE if couldn't open file, error writing file
extern int stbi_write_bmp (char const *filename, int x, int y, int comp, void *data);
extern int stbi_write_tga (char const *filename, int x, int y, int comp, void *data);
#endif
// PRIMARY API - works on images of any type
// load image by filename, open file, or memory buffer
#ifndef STBI_NO_STDIO
extern stbi_uc *stbi_load (char const *filename, int *x, int *y, int *comp, int req_comp);
extern stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);
extern int stbi_info_from_file (FILE *f, int *x, int *y, int *comp);
#endif
extern stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
// for stbi_load_from_file, file pointer is left pointing immediately after image
#ifndef STBI_NO_HDR
#ifndef STBI_NO_STDIO
extern float *stbi_loadf (char const *filename, int *x, int *y, int *comp, int req_comp);
extern float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);
#endif
extern float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
extern void stbi_hdr_to_ldr_gamma(float gamma);
extern void stbi_hdr_to_ldr_scale(float scale);
extern void stbi_ldr_to_hdr_gamma(float gamma);
extern void stbi_ldr_to_hdr_scale(float scale);
#endif // STBI_NO_HDR
// get a VERY brief reason for failure
// NOT THREADSAFE
extern char *stbi_failure_reason (void);
// free the loaded image -- this is just free()
extern void stbi_image_free (void *retval_from_stbi_load);
// get image dimensions & components without fully decoding
extern int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);
extern int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len);
#ifndef STBI_NO_STDIO
extern int stbi_info (char const *filename, int *x, int *y, int *comp);
extern int stbi_is_hdr (char const *filename);
extern int stbi_is_hdr_from_file(FILE *f);
#endif
// ZLIB client - used by PNG, available for other purposes
extern char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen);
extern char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen);
extern int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);
extern char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen);
extern int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);
// TYPE-SPECIFIC ACCESS
// is it a jpeg?
extern int stbi_jpeg_test_memory (stbi_uc const *buffer, int len);
extern stbi_uc *stbi_jpeg_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
extern int stbi_jpeg_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);
#ifndef STBI_NO_STDIO
extern stbi_uc *stbi_jpeg_load (char const *filename, int *x, int *y, int *comp, int req_comp);
extern int stbi_jpeg_test_file (FILE *f);
extern stbi_uc *stbi_jpeg_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);
extern int stbi_jpeg_info (char const *filename, int *x, int *y, int *comp);
extern int stbi_jpeg_info_from_file (FILE *f, int *x, int *y, int *comp);
#endif
// is it a png?
extern int stbi_png_test_memory (stbi_uc const *buffer, int len);
extern stbi_uc *stbi_png_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
extern int stbi_png_info_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp);
#ifndef STBI_NO_STDIO
extern stbi_uc *stbi_png_load (char const *filename, int *x, int *y, int *comp, int req_comp);
extern int stbi_png_info (char const *filename, int *x, int *y, int *comp);
extern int stbi_png_test_file (FILE *f);
extern stbi_uc *stbi_png_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);
extern int stbi_png_info_from_file (FILE *f, int *x, int *y, int *comp);
#endif
// is it a bmp?
extern int stbi_bmp_test_memory (stbi_uc const *buffer, int len);
extern stbi_uc *stbi_bmp_load (char const *filename, int *x, int *y, int *comp, int req_comp);
extern stbi_uc *stbi_bmp_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
#ifndef STBI_NO_STDIO
extern int stbi_bmp_test_file (FILE *f);
extern stbi_uc *stbi_bmp_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);
#endif
// is it a tga?
extern int stbi_tga_test_memory (stbi_uc const *buffer, int len);
extern stbi_uc *stbi_tga_load (char const *filename, int *x, int *y, int *comp, int req_comp);
extern stbi_uc *stbi_tga_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
#ifndef STBI_NO_STDIO
extern int stbi_tga_test_file (FILE *f);
extern stbi_uc *stbi_tga_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);
#endif
// is it a psd?
extern int stbi_psd_test_memory (stbi_uc const *buffer, int len);
extern stbi_uc *stbi_psd_load (char const *filename, int *x, int *y, int *comp, int req_comp);
extern stbi_uc *stbi_psd_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
#ifndef STBI_NO_STDIO
extern int stbi_psd_test_file (FILE *f);
extern stbi_uc *stbi_psd_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);
#endif
// is it an hdr?
extern int stbi_hdr_test_memory (stbi_uc const *buffer, int len);
extern float * stbi_hdr_load (char const *filename, int *x, int *y, int *comp, int req_comp);
extern float * stbi_hdr_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
extern stbi_uc *stbi_hdr_load_rgbe (char const *filename, int *x, int *y, int *comp, int req_comp);
extern float * stbi_hdr_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
#ifndef STBI_NO_STDIO
extern int stbi_hdr_test_file (FILE *f);
extern float * stbi_hdr_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);
extern stbi_uc *stbi_hdr_load_rgbe_file (FILE *f, int *x, int *y, int *comp, int req_comp);
#endif
// define new loaders
typedef struct
{
int (*test_memory)(stbi_uc const *buffer, int len);
stbi_uc * (*load_from_memory)(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
#ifndef STBI_NO_STDIO
int (*test_file)(FILE *f);
stbi_uc * (*load_from_file)(FILE *f, int *x, int *y, int *comp, int req_comp);
#endif
} stbi_loader;
// register a loader by filling out the above structure (you must defined ALL functions)
// returns 1 if added or already added, 0 if not added (too many loaders)
// NOT THREADSAFE
extern int stbi_register_loader(stbi_loader *loader);
// define faster low-level operations (typically SIMD support)
#if STBI_SIMD
typedef void (*stbi_idct_8x8)(uint8 *out, int out_stride, short data[64], unsigned short *dequantize);
// compute an integer IDCT on "input"
// input[x] = data[x] * dequantize[x]
// write results to 'out': 64 samples, each run of 8 spaced by 'out_stride'
// CLAMP results to 0..255
typedef void (*stbi_YCbCr_to_RGB_run)(uint8 *output, uint8 const *y, uint8 const *cb, uint8 const *cr, int count, int step);
// compute a conversion from YCbCr to RGB
// 'count' pixels
// write pixels to 'output'; each pixel is 'step' bytes (either 3 or 4; if 4, write '255' as 4th), order R,G,B
// y: Y input channel
// cb: Cb input channel; scale/biased to be 0..255
// cr: Cr input channel; scale/biased to be 0..255
extern void stbi_install_idct(stbi_idct_8x8 func);
extern void stbi_install_YCbCr_to_RGB(stbi_YCbCr_to_RGB_run func);
#endif // STBI_SIMD
#ifdef __cplusplus
}
#endif
//
//
//// end header file /////////////////////////////////////////////////////
#endif // STBI_INCLUDE_STB_IMAGE_H

View File

@ -0,0 +1,21 @@
/*
adding DDS loading support to stbi
*/
#ifndef HEADER_STB_IMAGE_DDS_AUGMENTATION
#define HEADER_STB_IMAGE_DDS_AUGMENTATION
// is it a DDS file?
extern int stbi_dds_test_memory (stbi_uc const *buffer, int len);
extern stbi_uc *stbi_dds_load (char *filename, int *x, int *y, int *comp, int req_comp);
extern stbi_uc *stbi_dds_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
#ifndef STBI_NO_STDIO
extern int stbi_dds_test_file (FILE *f);
extern stbi_uc *stbi_dds_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);
#endif
//
//
//// end header file /////////////////////////////////////////////////////
#endif // HEADER_STB_IMAGE_DDS_AUGMENTATION

View File

@ -0,0 +1,511 @@
/// DDS file support, does decoding, _not_ direct uploading
/// (use SOIL for that ;-)
/// A bunch of DirectDraw Surface structures and flags
typedef struct {
unsigned int dwMagic;
unsigned int dwSize;
unsigned int dwFlags;
unsigned int dwHeight;
unsigned int dwWidth;
unsigned int dwPitchOrLinearSize;
unsigned int dwDepth;
unsigned int dwMipMapCount;
unsigned int dwReserved1[ 11 ];
// DDPIXELFORMAT
struct {
unsigned int dwSize;
unsigned int dwFlags;
unsigned int dwFourCC;
unsigned int dwRGBBitCount;
unsigned int dwRBitMask;
unsigned int dwGBitMask;
unsigned int dwBBitMask;
unsigned int dwAlphaBitMask;
} sPixelFormat;
// DDCAPS2
struct {
unsigned int dwCaps1;
unsigned int dwCaps2;
unsigned int dwDDSX;
unsigned int dwReserved;
} sCaps;
unsigned int dwReserved2;
} DDS_header ;
// the following constants were copied directly off the MSDN website
// The dwFlags member of the original DDSURFACEDESC2 structure
// can be set to one or more of the following values.
#define DDSD_CAPS 0x00000001
#define DDSD_HEIGHT 0x00000002
#define DDSD_WIDTH 0x00000004
#define DDSD_PITCH 0x00000008
#define DDSD_PIXELFORMAT 0x00001000
#define DDSD_MIPMAPCOUNT 0x00020000
#define DDSD_LINEARSIZE 0x00080000
#define DDSD_DEPTH 0x00800000
// DirectDraw Pixel Format
#define DDPF_ALPHAPIXELS 0x00000001
#define DDPF_FOURCC 0x00000004
#define DDPF_RGB 0x00000040
// The dwCaps1 member of the DDSCAPS2 structure can be
// set to one or more of the following values.
#define DDSCAPS_COMPLEX 0x00000008
#define DDSCAPS_TEXTURE 0x00001000
#define DDSCAPS_MIPMAP 0x00400000
// The dwCaps2 member of the DDSCAPS2 structure can be
// set to one or more of the following values.
#define DDSCAPS2_CUBEMAP 0x00000200
#define DDSCAPS2_CUBEMAP_POSITIVEX 0x00000400
#define DDSCAPS2_CUBEMAP_NEGATIVEX 0x00000800
#define DDSCAPS2_CUBEMAP_POSITIVEY 0x00001000
#define DDSCAPS2_CUBEMAP_NEGATIVEY 0x00002000
#define DDSCAPS2_CUBEMAP_POSITIVEZ 0x00004000
#define DDSCAPS2_CUBEMAP_NEGATIVEZ 0x00008000
#define DDSCAPS2_VOLUME 0x00200000
static int dds_test(stbi *s)
{
// check the magic number
if (get8(s) != 'D') return 0;
if (get8(s) != 'D') return 0;
if (get8(s) != 'S') return 0;
if (get8(s) != ' ') return 0;
// check header size
if (get32le(s) != 124) return 0;
return 1;
}
#ifndef STBI_NO_STDIO
int stbi_dds_test_file (FILE *f)
{
stbi s;
int r,n = ftell(f);
start_file(&s,f);
r = dds_test(&s);
fseek(f,n,SEEK_SET);
return r;
}
#endif
int stbi_dds_test_memory (stbi_uc const *buffer, int len)
{
stbi s;
start_mem(&s,buffer, len);
return dds_test(&s);
}
// helper functions
int stbi_convert_bit_range( int c, int from_bits, int to_bits )
{
int b = (1 << (from_bits - 1)) + c * ((1 << to_bits) - 1);
return (b + (b >> from_bits)) >> from_bits;
}
void stbi_rgb_888_from_565( unsigned int c, int *r, int *g, int *b )
{
*r = stbi_convert_bit_range( (c >> 11) & 31, 5, 8 );
*g = stbi_convert_bit_range( (c >> 05) & 63, 6, 8 );
*b = stbi_convert_bit_range( (c >> 00) & 31, 5, 8 );
}
void stbi_decode_DXT1_block(
unsigned char uncompressed[16*4],
unsigned char compressed[8] )
{
int next_bit = 4*8;
int i, r, g, b;
int c0, c1;
unsigned char decode_colors[4*4];
// find the 2 primary colors
c0 = compressed[0] + (compressed[1] << 8);
c1 = compressed[2] + (compressed[3] << 8);
stbi_rgb_888_from_565( c0, &r, &g, &b );
decode_colors[0] = r;
decode_colors[1] = g;
decode_colors[2] = b;
decode_colors[3] = 255;
stbi_rgb_888_from_565( c1, &r, &g, &b );
decode_colors[4] = r;
decode_colors[5] = g;
decode_colors[6] = b;
decode_colors[7] = 255;
if( c0 > c1 )
{
// no alpha, 2 interpolated colors
decode_colors[8] = (2*decode_colors[0] + decode_colors[4]) / 3;
decode_colors[9] = (2*decode_colors[1] + decode_colors[5]) / 3;
decode_colors[10] = (2*decode_colors[2] + decode_colors[6]) / 3;
decode_colors[11] = 255;
decode_colors[12] = (decode_colors[0] + 2*decode_colors[4]) / 3;
decode_colors[13] = (decode_colors[1] + 2*decode_colors[5]) / 3;
decode_colors[14] = (decode_colors[2] + 2*decode_colors[6]) / 3;
decode_colors[15] = 255;
} else
{
// 1 interpolated color, alpha
decode_colors[8] = (decode_colors[0] + decode_colors[4]) / 2;
decode_colors[9] = (decode_colors[1] + decode_colors[5]) / 2;
decode_colors[10] = (decode_colors[2] + decode_colors[6]) / 2;
decode_colors[11] = 255;
decode_colors[12] = 0;
decode_colors[13] = 0;
decode_colors[14] = 0;
decode_colors[15] = 0;
}
// decode the block
for( i = 0; i < 16*4; i += 4 )
{
int idx = ((compressed[next_bit>>3] >> (next_bit & 7)) & 3) * 4;
next_bit += 2;
uncompressed[i+0] = decode_colors[idx+0];
uncompressed[i+1] = decode_colors[idx+1];
uncompressed[i+2] = decode_colors[idx+2];
uncompressed[i+3] = decode_colors[idx+3];
}
// done
}
void stbi_decode_DXT23_alpha_block(
unsigned char uncompressed[16*4],
unsigned char compressed[8] )
{
int i, next_bit = 0;
// each alpha value gets 4 bits
for( i = 3; i < 16*4; i += 4 )
{
uncompressed[i] = stbi_convert_bit_range(
(compressed[next_bit>>3] >> (next_bit&7)) & 15,
4, 8 );
next_bit += 4;
}
}
void stbi_decode_DXT45_alpha_block(
unsigned char uncompressed[16*4],
unsigned char compressed[8] )
{
int i, next_bit = 8*2;
unsigned char decode_alpha[8];
// each alpha value gets 3 bits, and the 1st 2 bytes are the range
decode_alpha[0] = compressed[0];
decode_alpha[1] = compressed[1];
if( decode_alpha[0] > decode_alpha[1] )
{
// 6 step intermediate
decode_alpha[2] = (6*decode_alpha[0] + 1*decode_alpha[1]) / 7;
decode_alpha[3] = (5*decode_alpha[0] + 2*decode_alpha[1]) / 7;
decode_alpha[4] = (4*decode_alpha[0] + 3*decode_alpha[1]) / 7;
decode_alpha[5] = (3*decode_alpha[0] + 4*decode_alpha[1]) / 7;
decode_alpha[6] = (2*decode_alpha[0] + 5*decode_alpha[1]) / 7;
decode_alpha[7] = (1*decode_alpha[0] + 6*decode_alpha[1]) / 7;
} else
{
// 4 step intermediate, pluss full and none
decode_alpha[2] = (4*decode_alpha[0] + 1*decode_alpha[1]) / 5;
decode_alpha[3] = (3*decode_alpha[0] + 2*decode_alpha[1]) / 5;
decode_alpha[4] = (2*decode_alpha[0] + 3*decode_alpha[1]) / 5;
decode_alpha[5] = (1*decode_alpha[0] + 4*decode_alpha[1]) / 5;
decode_alpha[6] = 0;
decode_alpha[7] = 255;
}
for( i = 3; i < 16*4; i += 4 )
{
int idx = 0, bit;
bit = (compressed[next_bit>>3] >> (next_bit&7)) & 1;
idx += bit << 0;
++next_bit;
bit = (compressed[next_bit>>3] >> (next_bit&7)) & 1;
idx += bit << 1;
++next_bit;
bit = (compressed[next_bit>>3] >> (next_bit&7)) & 1;
idx += bit << 2;
++next_bit;
uncompressed[i] = decode_alpha[idx & 7];
}
// done
}
void stbi_decode_DXT_color_block(
unsigned char uncompressed[16*4],
unsigned char compressed[8] )
{
int next_bit = 4*8;
int i, r, g, b;
int c0, c1;
unsigned char decode_colors[4*3];
// find the 2 primary colors
c0 = compressed[0] + (compressed[1] << 8);
c1 = compressed[2] + (compressed[3] << 8);
stbi_rgb_888_from_565( c0, &r, &g, &b );
decode_colors[0] = r;
decode_colors[1] = g;
decode_colors[2] = b;
stbi_rgb_888_from_565( c1, &r, &g, &b );
decode_colors[3] = r;
decode_colors[4] = g;
decode_colors[5] = b;
// Like DXT1, but no choicees:
// no alpha, 2 interpolated colors
decode_colors[6] = (2*decode_colors[0] + decode_colors[3]) / 3;
decode_colors[7] = (2*decode_colors[1] + decode_colors[4]) / 3;
decode_colors[8] = (2*decode_colors[2] + decode_colors[5]) / 3;
decode_colors[9] = (decode_colors[0] + 2*decode_colors[3]) / 3;
decode_colors[10] = (decode_colors[1] + 2*decode_colors[4]) / 3;
decode_colors[11] = (decode_colors[2] + 2*decode_colors[5]) / 3;
// decode the block
for( i = 0; i < 16*4; i += 4 )
{
int idx = ((compressed[next_bit>>3] >> (next_bit & 7)) & 3) * 3;
next_bit += 2;
uncompressed[i+0] = decode_colors[idx+0];
uncompressed[i+1] = decode_colors[idx+1];
uncompressed[i+2] = decode_colors[idx+2];
}
// done
}
static stbi_uc *dds_load(stbi *s, int *x, int *y, int *comp, int req_comp)
{
// all variables go up front
stbi_uc *dds_data = NULL;
stbi_uc block[16*4];
stbi_uc compressed[8];
int flags, DXT_family;
int has_alpha, has_mipmap;
int is_compressed, cubemap_faces;
int block_pitch, num_blocks;
DDS_header header;
int i, sz, cf;
// load the header
if( sizeof( DDS_header ) != 128 )
{
return NULL;
}
getn( s, (stbi_uc*)(&header), 128 );
// and do some checking
if( header.dwMagic != (('D' << 0) | ('D' << 8) | ('S' << 16) | (' ' << 24)) ) return NULL;
if( header.dwSize != 124 ) return NULL;
flags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT;
if( (header.dwFlags & flags) != flags ) return NULL;
/* According to the MSDN spec, the dwFlags should contain
DDSD_LINEARSIZE if it's compressed, or DDSD_PITCH if
uncompressed. Some DDS writers do not conform to the
spec, so I need to make my reader more tolerant */
if( header.sPixelFormat.dwSize != 32 ) return NULL;
flags = DDPF_FOURCC | DDPF_RGB;
if( (header.sPixelFormat.dwFlags & flags) == 0 ) return NULL;
if( (header.sCaps.dwCaps1 & DDSCAPS_TEXTURE) == 0 ) return NULL;
// get the image data
s->img_x = header.dwWidth;
s->img_y = header.dwHeight;
s->img_n = 4;
is_compressed = (header.sPixelFormat.dwFlags & DDPF_FOURCC) / DDPF_FOURCC;
has_alpha = (header.sPixelFormat.dwFlags & DDPF_ALPHAPIXELS) / DDPF_ALPHAPIXELS;
has_mipmap = (header.sCaps.dwCaps1 & DDSCAPS_MIPMAP) && (header.dwMipMapCount > 1);
cubemap_faces = (header.sCaps.dwCaps2 & DDSCAPS2_CUBEMAP) / DDSCAPS2_CUBEMAP;
/* I need cubemaps to have square faces */
cubemap_faces &= (s->img_x == s->img_y);
cubemap_faces *= 5;
cubemap_faces += 1;
block_pitch = (s->img_x+3) >> 2;
num_blocks = block_pitch * ((s->img_y+3) >> 2);
/* let the user know what's going on */
*x = s->img_x;
*y = s->img_y;
*comp = s->img_n;
/* is this uncompressed? */
if( is_compressed )
{
/* compressed */
// note: header.sPixelFormat.dwFourCC is something like (('D'<<0)|('X'<<8)|('T'<<16)|('1'<<24))
DXT_family = 1 + (header.sPixelFormat.dwFourCC >> 24) - '1';
if( (DXT_family < 1) || (DXT_family > 5) ) return NULL;
/* check the expected size...oops, nevermind...
those non-compliant writers leave
dwPitchOrLinearSize == 0 */
// passed all the tests, get the RAM for decoding
sz = (s->img_x)*(s->img_y)*4*cubemap_faces;
dds_data = (unsigned char*)malloc( sz );
/* do this once for each face */
for( cf = 0; cf < cubemap_faces; ++ cf )
{
// now read and decode all the blocks
for( i = 0; i < num_blocks; ++i )
{
// where are we?
int bx, by, bw=4, bh=4;
int ref_x = 4 * (i % block_pitch);
int ref_y = 4 * (i / block_pitch);
// get the next block's worth of compressed data, and decompress it
if( DXT_family == 1 )
{
// DXT1
getn( s, compressed, 8 );
stbi_decode_DXT1_block( block, compressed );
} else if( DXT_family < 4 )
{
// DXT2/3
getn( s, compressed, 8 );
stbi_decode_DXT23_alpha_block ( block, compressed );
getn( s, compressed, 8 );
stbi_decode_DXT_color_block ( block, compressed );
} else
{
// DXT4/5
getn( s, compressed, 8 );
stbi_decode_DXT45_alpha_block ( block, compressed );
getn( s, compressed, 8 );
stbi_decode_DXT_color_block ( block, compressed );
}
// is this a partial block?
if( ref_x + 4 > s->img_x )
{
bw = s->img_x - ref_x;
}
if( ref_y + 4 > s->img_y )
{
bh = s->img_y - ref_y;
}
// now drop our decompressed data into the buffer
for( by = 0; by < bh; ++by )
{
int idx = 4*((ref_y+by+cf*s->img_x)*s->img_x + ref_x);
for( bx = 0; bx < bw*4; ++bx )
{
dds_data[idx+bx] = block[by*16+bx];
}
}
}
/* done reading and decoding the main image...
skip MIPmaps if present */
if( has_mipmap )
{
int block_size = 16;
if( DXT_family == 1 )
{
block_size = 8;
}
for( i = 1; i < header.dwMipMapCount; ++i )
{
int mx = s->img_x >> (i + 2);
int my = s->img_y >> (i + 2);
if( mx < 1 )
{
mx = 1;
}
if( my < 1 )
{
my = 1;
}
skip( s, mx*my*block_size );
}
}
}/* per cubemap face */
} else
{
/* uncompressed */
DXT_family = 0;
s->img_n = 3;
if( has_alpha )
{
s->img_n = 4;
}
*comp = s->img_n;
sz = s->img_x*s->img_y*s->img_n*cubemap_faces;
dds_data = (unsigned char*)malloc( sz );
/* do this once for each face */
for( cf = 0; cf < cubemap_faces; ++ cf )
{
/* read the main image for this face */
getn( s, &dds_data[cf*s->img_x*s->img_y*s->img_n], s->img_x*s->img_y*s->img_n );
/* done reading and decoding the main image...
skip MIPmaps if present */
if( has_mipmap )
{
for( i = 1; i < header.dwMipMapCount; ++i )
{
int mx = s->img_x >> i;
int my = s->img_y >> i;
if( mx < 1 )
{
mx = 1;
}
if( my < 1 )
{
my = 1;
}
skip( s, mx*my*s->img_n );
}
}
}
/* data was BGR, I need it RGB */
for( i = 0; i < sz; i += s->img_n )
{
unsigned char temp = dds_data[i];
dds_data[i] = dds_data[i+2];
dds_data[i+2] = temp;
}
}
/* finished decompressing into RGBA,
adjust the y size if we have a cubemap
note: sz is already up to date */
s->img_y *= cubemap_faces;
*y = s->img_y;
// did the user want something else, or
// see if all the alpha values are 255 (i.e. no transparency)
has_alpha = 0;
if( s->img_n == 4)
{
for( i = 3; (i < sz) && (has_alpha == 0); i += 4 )
{
has_alpha |= (dds_data[i] < 255);
}
}
if( (req_comp <= 4) && (req_comp >= 1) )
{
// user has some requirements, meet them
if( req_comp != s->img_n )
{
dds_data = convert_format( dds_data, s->img_n, req_comp, s->img_x, s->img_y );
*comp = s->img_n;
}
} else
{
// user had no requirements, only drop to RGB is no alpha
if( (has_alpha == 0) && (s->img_n == 4) )
{
dds_data = convert_format( dds_data, 4, 3, s->img_x, s->img_y );
*comp = 3;
}
}
// OK, done
return dds_data;
}
#ifndef STBI_NO_STDIO
stbi_uc *stbi_dds_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp)
{
stbi s;
start_file(&s,f);
return dds_load(&s,x,y,comp,req_comp);
}
stbi_uc *stbi_dds_load (char *filename, int *x, int *y, int *comp, int req_comp)
{
stbi_uc *data;
FILE *f = fopen(filename, "rb");
if (!f) return NULL;
data = stbi_dds_load_from_file(f,x,y,comp,req_comp);
fclose(f);
return data;
}
#endif
stbi_uc *stbi_dds_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
{
stbi s;
start_mem(&s,buffer, len);
return dds_load(&s,x,y,comp,req_comp);
}

184
Grk-Projekt/src/Scene.h Normal file
View File

@ -0,0 +1,184 @@
#pragma once
#include "Skybox.h"
#include "FreeCamera.h"
#include "PlayerCamera.h"
#include "Shader.h"
#include "GameObject.h"
#include "MovableObject.h"
#include "StaticObject.h"
#include "FishObject.h"
#include "FishObject2.h"
#include "MapObject.h"
#include "BaseParticleGenerator.h"
#include "BasePlayer.h"
#include "SubmarinePlayer.h"
#include "FreePlayer.h"
#include "PointLightDebugPlayer.h"
#include "SpotLightDebugPlayer.h"
class Scene
{
public:
Scene() {
LoadShaders();
LoadSkybox();
LoadContexts();
LoadPlayers();
SetActivePlayer(0);
LoadGameObjects();
LoadParticleGenerators();
LoadLghts();
};
Shader* shader = nullptr;
Shader* directionalShadowShader = nullptr;
Skybox* skybox = nullptr;
// ------------------------------------------------
// ------------------- LIGHTS ---------------------
// ------------------------------------------------
DirectionalLight* mainLight = nullptr;
std::vector<PointLight*> pointLights;
std::vector<SpotLight*> spotLights;
// ------------------------------------------------
// ------------------- MODELS ---------------------
// ------------------------------------------------
RenderContext* mapContext = nullptr;
RenderContext* cubeContext = nullptr;
RenderContext* coneContext = nullptr;
RenderContext* playerContext = nullptr;
RenderContext* fish_1_Context = nullptr;
RenderContext* bubbleContext = nullptr;
// ------------------------------------------------
// ------------ PARTICLEGENERATORS ----------------
// ------------------------------------------------
std::vector<BaseParticleGenerator*> particleGenerators;
// ------------------------------------------------
// ---------------- GAMEOBJECTS -------------------
// ------------------------------------------------
std::vector<BasePlayer*> players;
std::vector<GameObject*> gameObjects;
// ------------------------------------------------
// -------------- PLAYER + CAMERA -----------------
// ------------------------------------------------
Camera* activeCamera = nullptr;
int activePlayerIndex = 0;
BasePlayer* activePlayer = nullptr;
void SetActivePlayer(int index)
{
if (index >= players.size()) return;
activePlayerIndex = index;
activePlayer = players[activePlayerIndex];
activeCamera = activePlayer->GetCamera();
}
void NextPlayer() {
activePlayerIndex++;
if (activePlayerIndex >= players.size()) {
activePlayerIndex = 0;
}
activePlayer = players[activePlayerIndex];
activeCamera = activePlayer->GetCamera();
}
private:
void LoadShaders()
{
shader = new Shader();
shader->CreateFromFiles("shaders/shader.vert", "shaders/shader.frag");
shader->LinkUniforms();
directionalShadowShader = new Shader();
directionalShadowShader->CreateFromFiles("shaders/directional_shadow_map.vert", "shaders/directional_shadow_map.frag");
directionalShadowShader->LinkUniforms();
}
void LoadSkybox()
{
std::vector<std::string> skyboxFaces;
skyboxFaces.push_back("textures/Skybox/px2.png");
skyboxFaces.push_back("textures/Skybox/nx2.png");
skyboxFaces.push_back("textures/Skybox/py2.png");
skyboxFaces.push_back("textures/Skybox/ny2.png");
skyboxFaces.push_back("textures/Skybox/pz2.png");
skyboxFaces.push_back("textures/Skybox/nz2.png");
skybox = new Skybox(skyboxFaces);
}
void LoadContexts()
{
mapContext = new RenderContext("models/terrain.fbx");
playerContext = new RenderContext("models/submarine.fbx");
cubeContext = new RenderContext("models/cube.fbx");
coneContext = new RenderContext("models/cone.fbx");
bubbleContext = new RenderContext("models/bubble.fbx");
}
void LoadPlayers()
{
players.push_back(new SubmarinePlayer(playerContext));
gameObjects.push_back(players[0]);
players.push_back(new FreePlayer());
gameObjects.push_back(players[1]);
/* players.push_back(new PointLightDebugPlayer());
gameObjects.push_back(players[2]);*/
/*players.push_back(new SpotLightDebugPlayer());
gameObjects.push_back(players[3]);*/
}
void LoadGameObjects()
{
gameObjects.push_back(new MapObject(mapContext));
gameObjects.push_back(new FishObject(nullptr));
gameObjects.push_back(new FishObject2(nullptr));
}
void LoadParticleGenerators()
{
for (auto gameObject : gameObjects)
{
gameObject->SetParticleGenerators(particleGenerators);
}
}
void LoadLghts()
{
mainLight = new DirectionalLight(
1.00f, 1.00f, 1.00f,
0.1f, 0.8f,
0.0f, -12.0f, -15.0f,
2048, 2048
);
pointLights.push_back(new PointLight(
0.95f, 0.7f, 0.15f,
0.1f, 3.0f,
10.345783f, 21.152172f, -23.840828f,
1.0f, 0.007, 0.0002f
));
for (auto gameObject : gameObjects)
{
gameObject->SetSceneLights(spotLights, pointLights);
}
}
};

187
Grk-Projekt/src/Shader.cpp Normal file
View File

@ -0,0 +1,187 @@
#include "Shader.h"
void Shader::LinkUniforms()
{
uniformProjection = glGetUniformLocation(shaderID, "projection");
uniformModel = glGetUniformLocation(shaderID, "model");
uniformView = glGetUniformLocation(shaderID, "view");
uniformEyePosition = glGetUniformLocation(shaderID, "eyePosition");
uniformShowFog = glGetUniformLocation(shaderID, "showFog");
uniformFogColor = glGetUniformLocation(shaderID, "fogColor");
uniformDirectionalLight.colour = glGetUniformLocation(shaderID, "directionalLight.base.colour");
uniformDirectionalLight.ambientIntensity = glGetUniformLocation(shaderID, "directionalLight.base.ambientIntensity");
uniformDirectionalLight.direction = glGetUniformLocation(shaderID, "directionalLight.direction");
uniformDirectionalLight.diffuseIntensity = glGetUniformLocation(shaderID, "directionalLight.base.diffuseIntensity");
uniformMaterial.diffuseTexture = glGetUniformLocation(shaderID, "material.diffuseTexture");
uniformMaterial.useDiffuseTexture = glGetUniformLocation(shaderID, "material.useDiffuseTexture");
uniformMaterial.objectColor = glGetUniformLocation(shaderID, "material.objectColor");
uniformMaterial.specularIntensity = glGetUniformLocation(shaderID, "material.specularIntensity");
uniformMaterial.shininess = glGetUniformLocation(shaderID, "material.shininess");
uniformShadowMap.directionaLightTransform = glGetUniformLocation(shaderID, "directionalLightTransform");
uniformShadowMap.directionaShadowMap = glGetUniformLocation(shaderID, "directionalShadowMap");
uniformPointLightCount = glGetUniformLocation(shaderID, "pointLightCount");
for (size_t i = 0; i < MAX_POINT_LIGHTS; i++)
{
char locBuff[100] = { '\0' };
snprintf(locBuff, sizeof(locBuff), "pointLights[%d].base.colour", i);
uniformPointLight[i].colour = glGetUniformLocation(shaderID, locBuff);
snprintf(locBuff, sizeof(locBuff), "pointLights[%d].base.ambientIntensity", i);
uniformPointLight[i].ambientIntensity = glGetUniformLocation(shaderID, locBuff);
snprintf(locBuff, sizeof(locBuff), "pointLights[%d].base.diffuseIntensity", i);
uniformPointLight[i].diffuseIntensity = glGetUniformLocation(shaderID, locBuff);
snprintf(locBuff, sizeof(locBuff), "pointLights[%d].position", i);
uniformPointLight[i].position = glGetUniformLocation(shaderID, locBuff);
snprintf(locBuff, sizeof(locBuff), "pointLights[%d].constant", i);
uniformPointLight[i].constant = glGetUniformLocation(shaderID, locBuff);
snprintf(locBuff, sizeof(locBuff), "pointLights[%d].linear", i);
uniformPointLight[i].linear = glGetUniformLocation(shaderID, locBuff);
snprintf(locBuff, sizeof(locBuff), "pointLights[%d].exponent", i);
uniformPointLight[i].exponent = glGetUniformLocation(shaderID, locBuff);
}
uniformSpotLightCount = glGetUniformLocation(shaderID, "spotLightCount");
for (size_t i = 0; i < MAX_SPOT_LIGHTS; i++)
{
char locBuff[100] = { '\0' };
snprintf(locBuff, sizeof(locBuff), "spotLights[%d].base.base.colour", i);
uniformSpotLight[i].colour = glGetUniformLocation(shaderID, locBuff);
snprintf(locBuff, sizeof(locBuff), "spotLights[%d].base.base.ambientIntensity", i);
uniformSpotLight[i].ambientIntensity = glGetUniformLocation(shaderID, locBuff);
snprintf(locBuff, sizeof(locBuff), "spotLights[%d].base.base.diffuseIntensity", i);
uniformSpotLight[i].diffuseIntensity = glGetUniformLocation(shaderID, locBuff);
snprintf(locBuff, sizeof(locBuff), "spotLights[%d].base.position", i);
uniformSpotLight[i].position = glGetUniformLocation(shaderID, locBuff);
snprintf(locBuff, sizeof(locBuff), "spotLights[%d].base.constant", i);
uniformSpotLight[i].constant = glGetUniformLocation(shaderID, locBuff);
snprintf(locBuff, sizeof(locBuff), "spotLights[%d].base.linear", i);
uniformSpotLight[i].linear = glGetUniformLocation(shaderID, locBuff);
snprintf(locBuff, sizeof(locBuff), "spotLights[%d].base.exponent", i);
uniformSpotLight[i].exponent = glGetUniformLocation(shaderID, locBuff);
snprintf(locBuff, sizeof(locBuff), "spotLights[%d].direction", i);
uniformSpotLight[i].direction = glGetUniformLocation(shaderID, locBuff);
snprintf(locBuff, sizeof(locBuff), "spotLights[%d].edge", i);
uniformSpotLight[i].edge = glGetUniformLocation(shaderID, locBuff);
}
}
void Shader::SetProjectionmatrix(glm::mat4* projectionMatrix)
{
glUniformMatrix4fv(uniformProjection, 1, GL_FALSE, glm::value_ptr(*projectionMatrix));
}
void Shader::SetModelMatrix(glm::mat4* modelMatrix)
{
glUniformMatrix4fv(uniformModel, 1, GL_FALSE, glm::value_ptr(*modelMatrix));
}
void Shader::SetViewMatrix(glm::mat4* viewMatrix)
{
glUniformMatrix4fv(uniformView, 1, GL_FALSE, glm::value_ptr(*viewMatrix));
}
void Shader::SetEyePosition(glm::vec3* eyePosition)
{
glUniform3f(uniformEyePosition, eyePosition->x, eyePosition->y, eyePosition->z);
}
void Shader::SetDirectionalLight(DirectionalLight* dLight)
{
glm::vec3* color = dLight->GetColour();
glm::vec3* direction = dLight->GetDirection();
glUniform3f(uniformDirectionalLight.colour, color->x, color->y, color->z);
glUniform1f(uniformDirectionalLight.ambientIntensity, dLight->GetAmbientIntenisty());
glUniform3f(uniformDirectionalLight.direction, direction->x, direction->y, direction->z);
glUniform1f(uniformDirectionalLight.diffuseIntensity, dLight->GetDiffuseIntensity());
}
void Shader::SetPointLights(std::vector<PointLight*>& pLight, unsigned int lightCount)
{
if (lightCount > MAX_POINT_LIGHTS) lightCount = MAX_POINT_LIGHTS;
glUniform1i(uniformPointLightCount, lightCount);
for (size_t i = 0; i < lightCount; i++)
{
glm::vec3* color = pLight[i]->GetColour();
glm::vec3* position = pLight[i]->GetPosition();
glUniform3f(uniformPointLight[i].colour, color->x, color->y, color->z);
glUniform1f(uniformPointLight[i].ambientIntensity, pLight[i]->GetAmbientIntenisty());
glUniform1f(uniformPointLight[i].diffuseIntensity, pLight[i]->GetDiffuseIntensity());
glUniform3f(uniformPointLight[i].position, position->x, position->y, position->z);
glUniform1f(uniformPointLight[i].constant, pLight[i]->GetConstant());
glUniform1f(uniformPointLight[i].linear, pLight[i]->GetLinear());
glUniform1f(uniformPointLight[i].exponent, pLight[i]->GetExponent());
}
}
void Shader::SetSpotLights(std::vector<SpotLight*>& sLight, unsigned int lightCount)
{
if (lightCount > MAX_SPOT_LIGHTS) lightCount = MAX_SPOT_LIGHTS;
glUniform1i(uniformSpotLightCount, lightCount);
for (size_t i = 0; i < lightCount; i++)
{
glm::vec3* color = sLight[i]->GetColour();
glm::vec3* position = sLight[i]->GetPosition();
glm::vec3* direction = sLight[i]->GetDirection();
glUniform3f(uniformSpotLight[i].colour, color->x, color->y, color->z);
glUniform1f(uniformSpotLight[i].ambientIntensity, sLight[i]->GetAmbientIntenisty());
glUniform1f(uniformSpotLight[i].diffuseIntensity, sLight[i]->GetDiffuseIntensity());
glUniform3f(uniformSpotLight[i].position, position->x, position->y, position->z);
glUniform1f(uniformSpotLight[i].constant, sLight[i]->GetConstant());
glUniform1f(uniformSpotLight[i].linear, sLight[i]->GetLinear());
glUniform1f(uniformSpotLight[i].exponent, sLight[i]->GetExponent());
glUniform3f(uniformSpotLight[i].direction, direction->x, direction->y, direction->z);
glUniform1f(uniformSpotLight[i].edge, sLight[i]->GetProcEdge());
}
}
void Shader::SetMaterial(Material* material)
{
glUniform1i(uniformMaterial.diffuseTexture, material->diffuseTextureUnit);
glUniform1i(uniformMaterial.useDiffuseTexture, material->useDiffuseTexture);
glUniform3f(uniformMaterial.objectColor, material->objectColor.x, material->objectColor.y, material->objectColor.z);
glUniform1f(uniformMaterial.specularIntensity, material->specularIntensity);
glUniform1f(uniformMaterial.shininess, material->shininess);
}
void Shader::SetDirectionalShadowMap(GLuint textureUnit)
{
glUniform1i(uniformShadowMap.directionaShadowMap, textureUnit);
}
void Shader::SetDirectionaLightTransform(glm::mat4* lTransform)
{
glUniformMatrix4fv(uniformShadowMap.directionaLightTransform, 1, GL_FALSE, glm::value_ptr(*lTransform));
}

88
Grk-Projekt/src/Shader.h Normal file
View File

@ -0,0 +1,88 @@
#pragma once
#include "ShaderBase.h"
#include "CommonValues.h"
#include "DirectionalLight.h"
#include "PointLight.h"
#include "SpotLight.h"
#include "RenderContextMaterial.h"
class Shader : public ShaderBase
{
public:
Shader() : ShaderBase() {}
void LinkUniforms() override;
void SetProjectionmatrix(glm::mat4* projectionMatrix);
void SetModelMatrix(glm::mat4* modelMatrix);
void SetViewMatrix(glm::mat4* viewMatrix);
void SetEyePosition(glm::vec3* eyePosition);
void SetDirectionalLight(DirectionalLight* dLight);
void SetPointLights(std::vector<PointLight*>& pLight, unsigned int lightCount);
void SetSpotLights(std::vector<SpotLight*>& sLight, unsigned int lightCount);
void SetMaterial(Material* material);
void SetDirectionalShadowMap(GLuint textureUnit);
void SetDirectionaLightTransform(glm::mat4* lTransform);
private:
int pointLightCount;
int spotLightCount;
GLuint uniformProjection;
GLuint uniformModel;
GLuint uniformView;
GLuint uniformEyePosition;
struct {
GLuint directionaLightTransform;
GLuint directionaShadowMap;
} uniformShadowMap;
struct {
GLuint diffuseTexture;
GLuint useDiffuseTexture;
GLuint objectColor;
GLuint specularIntensity;
GLuint shininess;
} uniformMaterial;
struct {
GLuint colour;
GLuint ambientIntensity;
GLuint diffuseIntensity;
GLuint direction;
} uniformDirectionalLight;
GLuint uniformPointLightCount;
struct {
GLuint colour;
GLuint ambientIntensity;
GLuint diffuseIntensity;
GLuint position;
GLuint constant;
GLuint linear;
GLuint exponent;
} uniformPointLight[MAX_POINT_LIGHTS];
GLuint uniformSpotLightCount;
struct {
GLuint colour;
GLuint ambientIntensity;
GLuint diffuseIntensity;
GLuint position;
GLuint constant;
GLuint linear;
GLuint exponent;
GLuint direction;
GLuint edge;
} uniformSpotLight[MAX_SPOT_LIGHTS];
};

View File

@ -0,0 +1,151 @@
#pragma once
#include <stdio.h>
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <GL\glew.h>
#include <GLM\glm.hpp>
#include <GLM\ext.hpp>
class ShaderBase
{
public:
ShaderBase()
{
shaderID = 0;
}
virtual void LinkUniforms() = 0;
void CreateFromString(const char* vertexCode, const char* fragmentCode)
{
CompileShader(vertexCode, fragmentCode);
}
void CreateFromFiles(const char* vertexLocation, const char* fragmentLocation)
{
std::string vertexString = ReadFile(vertexLocation);
std::string fragmentString = ReadFile(fragmentLocation);
const char* vertexCode = vertexString.c_str();
const char* fragmentCode = fragmentString.c_str();
CompileShader(vertexCode, fragmentCode);
}
GLuint GetProgram() { return shaderID; }
void UseShader() { glUseProgram(shaderID); }
void SetShowFog(bool value)
{
glUniform1i(uniformShowFog, value);
}
void SetFogColor(glm::vec3* color)
{
glUniform3f(uniformFogColor, color->x, color->y, color->z);
}
~ShaderBase()
{
if (shaderID != 0)
{
glDeleteProgram(shaderID);
shaderID = 0;
}
}
protected:
GLuint shaderID;
GLuint uniformShowFog;
GLuint uniformFogColor;
private:
std::string ReadFile(const char* fileLocation)
{
std::string content;
std::ifstream fileStream(fileLocation, std::ios::in);
if (!fileStream.is_open()) {
printf("Failed to read %s! File doesn't exist.", fileLocation);
return "";
}
std::string line = "";
while (!fileStream.eof())
{
std::getline(fileStream, line);
content.append(line + "\n");
}
fileStream.close();
return content;
}
void CompileShader(const char* vertexCode, const char* fragmentCode)
{
shaderID = glCreateProgram();
if (!shaderID)
{
printf("Error creating shader program!\n");
return;
}
AddShader(shaderID, vertexCode, GL_VERTEX_SHADER);
AddShader(shaderID, fragmentCode, GL_FRAGMENT_SHADER);
GLint result = 0;
GLchar eLog[1024] = { 0 };
glLinkProgram(shaderID);
glGetProgramiv(shaderID, GL_LINK_STATUS, &result);
if (!result)
{
glGetProgramInfoLog(shaderID, sizeof(eLog), NULL, eLog);
printf("Error linking program: '%s'\n", eLog);
return;
}
glValidateProgram(shaderID);
glGetProgramiv(shaderID, GL_VALIDATE_STATUS, &result);
if (!result)
{
glGetProgramInfoLog(shaderID, sizeof(eLog), NULL, eLog);
printf("Error validating program: '%s'\n", eLog);
return;
}
}
void AddShader(GLuint theProgram, const char* shaderCode, GLenum shaderType)
{
GLuint theShader = glCreateShader(shaderType);
const GLchar* theCode[1];
theCode[0] = shaderCode;
GLint codeLength[1];
codeLength[0] = strlen(shaderCode);
glShaderSource(theShader, 1, theCode, codeLength);
glCompileShader(theShader);
GLint result = 0;
GLchar eLog[1024] = { 0 };
glGetShaderiv(theShader, GL_COMPILE_STATUS, &result);
if (!result)
{
glGetShaderInfoLog(theShader, sizeof(eLog), NULL, eLog);
printf("Error compiling the %d shader: '%s'\n", shaderType, eLog);
return;
}
glAttachShader(theProgram, theShader);
}
};

View File

@ -0,0 +1,76 @@
#pragma once
#include <stdio.h>
#include <GL\glew.h>
class ShadowMap
{
public:
ShadowMap()
{
FBO = 0;
shadowMap = 0;
}
virtual bool Init(GLuint width, GLuint height)
{
shadowWidth = width;
shadowHeight = height;
glGenFramebuffers(1, &FBO);
glGenTextures(1, &shadowMap);
glBindTexture(GL_TEXTURE_2D, shadowMap);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, shadowWidth, shadowHeight, 0, GL_DEPTH_COMPONENT, GL_FLOAT, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
float borderColor[] = { 1.0f, 1.0f, 1.0f, 1.0f };
glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, borderColor);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glBindFramebuffer(GL_FRAMEBUFFER, FBO);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, shadowMap, 0);
glDrawBuffer(GL_NONE);
glReadBuffer(GL_NONE);
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE) {
printf("Framebuffer error %i\n", status);
return false;
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
return true;
}
virtual void Write()
{
glBindFramebuffer(GL_FRAMEBUFFER, FBO);
}
virtual void Read(GLenum textureUnit)
{
glActiveTexture(textureUnit);
glBindTexture(GL_TEXTURE_2D, shadowMap);
}
GLuint GetShadowWidth() { return shadowWidth; }
GLuint GetShadowHeight() { return shadowHeight; }
~ShadowMap()
{
if (FBO) { glDeleteFramebuffers(1, &FBO); }
if (shadowMap) { glDeleteTextures(1, &shadowMap); }
}
protected:
GLuint FBO;
GLuint shadowMap;
GLuint shadowHeight;
GLuint shadowWidth;
};

View File

@ -0,0 +1,146 @@
#include "SimpleEmitter.h"
SimpleEmitter::SimpleEmitter()
{
shader = new ParticleShader();
shader->CreateFromString(VS, FS);
shader->LinkUniforms();
texture = new Texture("Textures/particle3.png");
texture->LoadTexture(TextureType::DIFFUSE);
this->particles.resize(100);
for (uint i = 0; i < this->particles.size(); ++i)
{
float x = -1.0f + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (1.0f - -1.0f)));
float y = -1.0f + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (1.0f - -1.0f)));
float z = -1.0f + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (1.0f - -1.0f)));
float l = 1.0f + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (2.0f - 1.0f)));
// give every particle a random position
this->particles[i].position.x = x;
this->particles[i].position.y = y;
this->particles[i].position.z = z;
this->particles[i].lifetime = l;
}
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &TMB);
glBindVertexArray(VAO);
GLfloat vertexBufferData[12] = {
-0.5f, -0.5f, 0.0f,
0.5f, -0.5f, 0.0f,
-0.5f, 0.5f, 0.0f,
0.5f, 0.5f, 0.0f
};
// fill the vertex buffer
std::vector< float > vertices;
vertices.push_back(0.0f);
vertices.push_back(0.0f);
vertices.push_back(0.0f);
vertices.push_back(1.0f);
vertices.push_back(0.0f);
vertices.push_back(0.0f);
vertices.push_back(0.0f);
vertices.push_back(1.0f);
vertices.push_back(0.0f);
vertices.push_back(1.0f);
vertices.push_back(1.0f);
vertices.push_back(0.0f);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(float), vertexBufferData, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, TMB);
glBufferData(GL_ARRAY_BUFFER, this->particles.size() * 4 * sizeof(float), this->positions, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
void SimpleEmitter::update(const float dt)
{
for (uint i = 0; i < this->particles.size(); ++i)
{
// subtract from the particles lifetime
this->particles[i].lifetime -= dt;
// if the lifetime is below 0 respawn the particle
if (this->particles[i].lifetime <= 0.0f)
{
float x = -1.0f + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (1.0f - -1.0f)));
float y = -1.0f + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (1.0f - -1.0f)));
float z = -1.0f + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (1.0f - -1.0f)));
float l = 1.0f + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (2.0f - 1.0f)));
this->particles[i].position.x = x;
this->particles[i].position.y = y;
this->particles[i].position.z = z;
this->particles[i].lifetime = l;
}
// move the particle down depending on the delta time
this->particles[i].position -= vec3(0.0f, dt * 2.0f, 0.0f);
// update the position buffer
this->positions[i * 4 + 0] = this->particles[i].position[0];
this->positions[i * 4 + 1] = this->particles[i].position[1];
this->positions[i * 4 + 2] = this->particles[i].position[2];
this->positions[i * 4 + 3] = this->particles[i].lifetime;
}
}
void SimpleEmitter::draw(glm::mat4 view, glm::mat4 projction)
{
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glBindVertexArray(VAO);
this->shader->UseShader();
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture->textureId);
shader->SetTextureID(0);
auto program = shader->GetProgram();
glUniformMatrix4fv(glGetUniformLocation(program, "M_v"), 1, GL_FALSE, glm::value_ptr(view));
glUniformMatrix4fv(glGetUniformLocation(program, "M_p"), 1, GL_FALSE, glm::value_ptr(projction));
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(4);
// update the position buffer
glBindBuffer(GL_ARRAY_BUFFER, this->TMB);
glBufferSubData(GL_ARRAY_BUFFER, 0, this->particles.size() * 4 * sizeof(float), this->positions);
// vertex buffer
glBindBuffer(GL_ARRAY_BUFFER, this->VBO);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
// position buffer
glBindBuffer(GL_ARRAY_BUFFER, this->TMB);
glVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE, 0, nullptr);
glVertexAttribDivisor(4, 1);
// draw triangles
glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, this->particles.size());
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(4);
}

119
Grk-Projekt/src/Skybox.h Normal file
View File

@ -0,0 +1,119 @@
#pragma once
#include <GL\glew.h>
#include "CommonValues.h"
#include "SkyboxShader.h"
#include "RenderContextMesh.h"
class Skybox
{
public:
Skybox() {};
Skybox(std::vector<std::string> faceLocations)
{
skyShader = new SkyboxShader();
skyShader->CreateFromFiles("shaders/skybox.vert", "shaders/skybox.frag");
skyShader->LinkUniforms();
glGenTextures(1, &textureId);
glBindTexture(GL_TEXTURE_CUBE_MAP, textureId);
int width, height, bitDepth;
for (size_t i = 0; i < 6; i++)
{
unsigned char* texData = stbi_load(faceLocations[i].c_str(), &width, &height, &bitDepth, 0);
if (!texData)
{
printf("Failed to find: %s\n", faceLocations[i].c_str());
return;
}
GLenum format = GL_RGB;
if (bitDepth == 1)
format = GL_RED;
else if (bitDepth == 3)
format = GL_RGB;
else if (bitDepth == 4)
format = GL_RGBA;
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, texData);
stbi_image_free(texData);
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
unsigned int skyboxIndices[] = {
// front
0, 1, 2,
2, 1, 3,
// right
2, 3, 5,
5, 3, 7,
// back
5, 7, 4,
4, 7, 6,
// left
4, 6, 0,
0, 6, 1,
// top
4, 0, 5,
5, 0, 2,
// bottom
1, 6, 3,
3, 6, 7
};
float skyboxVertices[] = {
// x y z u v nx, ny, nz
-1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
-1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
-1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
-1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f
};
skyMesh = new Mesh(skyboxVertices, skyboxIndices, 64, 36);
}
void DrawSkybox(glm::mat4* _viewMatrix, glm::mat4* projectionMatrix, glm::vec3* eyePosition, bool showFog, glm::vec3* fogColor)
{
glm::mat4 viewMatrix = glm::mat4(glm::mat3(*_viewMatrix));
glDepthMask(GL_FALSE);
skyShader->UseShader();
skyShader->SetEyePosition(eyePosition);
skyShader->SetProjectionmatrix(projectionMatrix);
skyShader->SetViewMatrix(&viewMatrix);
skyShader->SetShowFog(showFog);
skyShader->SetFogColor(fogColor);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_CUBE_MAP, textureId);
glBindVertexArray(skyMesh->VAO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, skyMesh->IBO);
glDrawElements(GL_TRIANGLES, skyMesh->indexCount, GL_UNSIGNED_INT, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindVertexArray(0);
glDepthMask(GL_TRUE);
}
private:
Mesh* skyMesh;
SkyboxShader* skyShader;
GLuint textureId;
};

View File

@ -0,0 +1,38 @@
#pragma once
#include "ShaderBase.h"
class SkyboxShader : public ShaderBase
{
public:
SkyboxShader() : ShaderBase() {}
void LinkUniforms() override
{
uniformProjection = glGetUniformLocation(shaderID, "projection");
uniformView = glGetUniformLocation(shaderID, "view");
uniformEyePosition = glGetUniformLocation(shaderID, "eyePosition");
uniformShowFog = glGetUniformLocation(shaderID, "showFog");
uniformFogColor = glGetUniformLocation(shaderID, "fogColor");
}
void SetProjectionmatrix(glm::mat4* projectionMatrix)
{
glUniformMatrix4fv(uniformProjection, 1, GL_FALSE, glm::value_ptr(*projectionMatrix));
}
void SetViewMatrix(glm::mat4* viewMatrix)
{
glUniformMatrix4fv(uniformView, 1, GL_FALSE, glm::value_ptr(*viewMatrix));
}
void SetEyePosition(glm::vec3* eyePosition)
{
glUniform3f(uniformEyePosition, eyePosition->x, eyePosition->y, eyePosition->z);
}
private:
GLuint uniformProjection;
GLuint uniformView;
GLuint uniformEyePosition;
};

View File

@ -0,0 +1,49 @@
#pragma once
#include "PointLight.h"
class SpotLight : public PointLight
{
public:
SpotLight() : PointLight()
{
direction = glm::vec3(0.0f, -1.0f, 0.0f);
edge = 0.0f;
procEdge = cosf(glm::radians(edge));
}
SpotLight(
GLfloat red, GLfloat green, GLfloat blue,
GLfloat aIntensity, GLfloat dIntensity,
GLfloat xPos, GLfloat yPos, GLfloat zPos,
GLfloat xDir, GLfloat yDir, GLfloat zDir,
GLfloat con, GLfloat lin, GLfloat exp,
GLfloat edg
) : PointLight(red, green, blue, aIntensity, dIntensity, xPos, yPos, zPos, con, lin, exp)
{
direction = glm::normalize(glm::vec3(xDir, yDir, zDir));
edge = edg;
procEdge = cosf(glm::radians(edge));
}
void SetFlash(glm::vec3* pos, glm::vec3* dir)
{
position.x = pos->x;
position.y = pos->y;
position.z = pos->z;
direction.x = dir->x;
direction.y = dir->y;
direction.z = dir->z;
}
glm::vec3* GetDirection() { return &direction; }
GLfloat GetProcEdge() { return procEdge; }
GLfloat GetEdge() { return edge; }
~SpotLight() {}
private:
glm::vec3 direction;
GLfloat edge, procEdge;
};

View File

@ -0,0 +1,111 @@
#pragma once
#include "BasePlayer.h"
#include "FreeCamera.h"
class SpotLightDebugPlayer : public BasePlayer
{
public:
SpotLightDebugPlayer() : BasePlayer(nullptr)
{
camera = new FreeCamera(
glm::vec3(0.0f, 0.0f, 0.0f),
glm::vec3(0.0f, 1.0f, 0.0f),
-90.0f, 0.0f, 5.0f, 0.1f
);
spotLight = new SpotLight(
1.0f, 0.0f, 0.0f,
0.0f, 5.0f,
0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f,
1.0f, 0.007, 0.0002f,
20.0f
);
spotLights.push_back(spotLight);
}
void Init() override {}
void Update(float dt) override
{
UpdateLights();
DebugLight(dt);
}
Camera* GetCamera() override
{
return camera;
}
void HandleControlls(Controlls* controlls, GLfloat deltaTime) override
{
camera->HandleControlls(controlls, deltaTime);
if (controlls->keys[GLFW_KEY_W])
{
playerPos += glm::vec3(0, 0, 1) * velocity * deltaTime;
}
if (controlls->keys[GLFW_KEY_S])
{
playerPos -= glm::vec3(0, 0, 1) * velocity * deltaTime;
}
if (controlls->keys[GLFW_KEY_A])
{
playerPos += glm::vec3(1, 0, 0) * velocity * deltaTime;
}
if (controlls->keys[GLFW_KEY_D])
{
playerPos -= glm::vec3(1, 0, 0) * velocity * deltaTime;
}
if (controlls->keys[GLFW_KEY_SPACE])
{
playerPos += worldUp * velocity * deltaTime;
}
if (controlls->keys[GLFW_KEY_LEFT_CONTROL])
{
playerPos -= worldUp * velocity * deltaTime;
}
}
private:
float velocity = 5.0f;
float dtSum = 0.0f;
glm::vec3 lightPos = glm::vec3(0);
glm::vec3 spotLightDir = glm::vec3(0);
FreeCamera* camera = nullptr;
SpotLight* spotLight = nullptr;
void UpdateLights() {
if (spotLight != nullptr) {
auto cameraPos = camera->GetCameraPosition();
auto cameraDir = camera->GetCameraDirection();
lightPos.x = cameraPos->x;
lightPos.y = cameraPos->y - 0.3f;
lightPos.z = cameraPos->z;
spotLightDir.x = cameraDir->x;
spotLightDir.y = cameraDir->y;
spotLightDir.z = cameraDir->z;
spotLight->SetFlash(&lightPos, &spotLightDir);
}
}
void DebugLight(float dt) {
dtSum += dt;
if (dtSum > 1.5f && spotLight != nullptr) {
printf("SpotLightPlayer {\n");
printf(" Position = %ff, %ff, %ff\n", lightPos.x, lightPos.y, lightPos.z);
printf(" Direction = %ff, %ff, %ff\n", spotLightDir.x, spotLightDir.y, spotLightDir.z);
printf("}\n");
dtSum = 0.0f;
}
}
};

View File

@ -0,0 +1,17 @@
#pragma once
#include "GameObject.h"
class StaticObject : public GameObject
{
public:
StaticObject(RenderContext* _renderContext) : GameObject(_renderContext){}
void Init() override {}
void Update(float dt) override {}
void SetMat4(glm::mat4 mat) {
modelMatrix = mat;
}
};

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