├── .gitignore ├── LICENSE ├── README.md ├── benchmark-gtx480-cuda40.log ├── benchmark-gtx480-cuda42.log ├── benchmark-gtx680-cuda42.log ├── benchmark.cmd ├── benchmark.log ├── cleanup.bat ├── create_index.bat ├── crsample.vcxproj ├── cudaraster.sln ├── cudaraster.vcxproj ├── file_index ├── framework.vcxproj └── src ├── crsample ├── App.cpp ├── App.hpp ├── Benchmark.cpp ├── Benchmark.hpp ├── Shaders.cu └── Shaders.hpp ├── cudaraster ├── CudaRaster.cpp ├── CudaRaster.hpp ├── CudaSurface.cpp ├── CudaSurface.hpp └── cuda │ ├── BinRaster.inl │ ├── CoarseRaster.inl │ ├── Constants.hpp │ ├── FineRaster.inl │ ├── PixelPipe.hpp │ ├── PixelPipe.inl │ ├── PrivateDefs.hpp │ ├── TriangleSetup.inl │ ├── Util.hpp │ └── Util.inl └── framework ├── 3d ├── CameraControls.cpp ├── CameraControls.hpp ├── ConvexPolyhedron.cpp ├── ConvexPolyhedron.hpp ├── Mesh.cpp ├── Mesh.hpp ├── Texture.cpp ├── Texture.hpp ├── TextureAtlas.cpp └── TextureAtlas.hpp ├── 3rdparty └── lodepng │ ├── lodepng.cpp │ └── lodepng.h ├── base ├── Array.cpp ├── Array.hpp ├── BinaryHeap.cpp ├── BinaryHeap.hpp ├── DLLImports.cpp ├── DLLImports.hpp ├── DLLImports.inl ├── Defs.cpp ├── Defs.hpp ├── Deque.cpp ├── Deque.hpp ├── Hash.cpp ├── Hash.hpp ├── Main.cpp ├── Main.hpp ├── Math.cpp ├── Math.hpp ├── MulticoreLauncher.cpp ├── MulticoreLauncher.hpp ├── Random.cpp ├── Random.hpp ├── Sort.cpp ├── Sort.hpp ├── String.cpp ├── String.hpp ├── Thread.cpp ├── Thread.hpp ├── Timer.cpp ├── Timer.hpp ├── UnionFind.cpp └── UnionFind.hpp ├── gpu ├── Buffer.cpp ├── Buffer.hpp ├── CudaCompiler.cpp ├── CudaCompiler.hpp ├── CudaKernel.cpp ├── CudaKernel.hpp ├── CudaModule.cpp ├── CudaModule.hpp ├── GLContext.cpp └── GLContext.hpp ├── gui ├── CommonControls.cpp ├── CommonControls.hpp ├── Image.cpp ├── Image.hpp ├── Keys.cpp ├── Keys.hpp ├── Window.cpp └── Window.hpp └── io ├── AviExporter.cpp ├── AviExporter.hpp ├── File.cpp ├── File.hpp ├── ImageBinaryIO.cpp ├── ImageBinaryIO.hpp ├── ImageBmpIO.cpp ├── ImageBmpIO.hpp ├── ImageLodePngIO.cpp ├── ImageLodePngIO.hpp ├── ImageRawPngIO.cpp ├── ImageRawPngIO.hpp ├── ImageTargaIO.cpp ├── ImageTargaIO.hpp ├── ImageTiffIO.cpp ├── ImageTiffIO.hpp ├── MeshBinaryIO.cpp ├── MeshBinaryIO.hpp ├── MeshWavefrontIO.cpp ├── MeshWavefrontIO.hpp ├── StateDump.cpp ├── StateDump.hpp ├── Stream.cpp └── Stream.hpp /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | scenes/* 3 | scenes/*/* 4 | 5 | buddha.obj 6 | 7 | *.png 8 | 9 | *.user 10 | *.sdf 11 | *.suo 12 | 13 | cudacache 14 | ipch 15 | build 16 | 17 | Debug/*.* 18 | Release/*.* 19 | 20 | 21 | screenshot_*.png 22 | 23 | crsample_Win32_Debug.exe 24 | crsample_Win32_Release.exe 25 | 26 | state_crsample_*.dat 27 | 28 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2009-2011, NVIDIA Corporation 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | * Redistributions of source code must retain the above copyright 7 | notice, this list of conditions and the following disclaimer. 8 | * Redistributions in binary form must reproduce the above copyright 9 | notice, this list of conditions and the following disclaimer in the 10 | documentation and/or other materials provided with the distribution. 11 | * Neither the name of NVIDIA Corporation nor the 12 | names of its contributors may be used to endorse or promote products 13 | derived from this software without specific prior written permission. 14 | 15 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 16 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 17 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 18 | DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 19 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 20 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 21 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 22 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 23 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 24 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | Purpose of this repository 3 | -------------------------- 4 | 5 | Research experiments using / against the CUDA rasterizer. Initial commit is the 6 | 1.1 release, downloaded from http://code.google.com/p/cudaraster/ 7 | 8 | No scenes are included. 9 | 10 | Original README follows: 11 | 12 | High-Performance GPU Software Rasterization 1.1 13 | ----------------------------------------------- 14 | Implementation by Tero Karras and Samuli Laine 15 | Copyright 2010-2012 NVIDIA Corporation 16 | 17 | This package contains full source code for the fast GPU-based software 18 | rasterizer described in the following paper: 19 | 20 | "High-Performance Software Rasterization on GPUs", 21 | Samuli Laine and Tero Karras, 22 | Proc. High-Performance Graphics 2011 23 | http://www.tml.tkk.fi/~samuli/publications/laine2011hpg_paper.pdf 24 | 25 | The source code is licensed under New BSD License (see LICENSE), and 26 | hosted by Google Code: 27 | 28 | http://code.google.com/p/cudaraster/ 29 | 30 | 31 | Abstract 32 | -------- 33 | 34 | In this paper, we implement an efficient, completely software-based graphics 35 | pipeline on a GPU. Unlike previous approaches, we obey ordering constraints 36 | imposed by current graphics APIs, guarantee hole-free rasterization, and 37 | support multisample antialiasing. Our goal is to examine the performance 38 | implications of not exploiting the fixed-function graphics pipeline, and to 39 | discern which additional hardware support would benefit software-based 40 | graphics the most. 41 | 42 | We present significant improvements over previous work in terms of 43 | scalability, performance, and capabilities. Our pipeline is malleable and 44 | easy to extend, and we demonstrate that in a wide variety of test cases its 45 | performance is within a factor of 2-8x compared to the hardware graphics 46 | pipeline on a top of the line GPU. 47 | 48 | 49 | System requirements 50 | ------------------- 51 | 52 | - Microsoft Windows XP, Vista, or 7. 53 | 54 | - At least 1GB of system memory. 55 | 56 | - NVIDIA CUDA-compatible GPU with compute capability 2.0 and at least 512 57 | megabytes of RAM. GeForce GTX 480 is recommended. 58 | 59 | - NVIDIA CUDA 4.0 or later. 60 | 61 | - Microsoft Visual Studio 2010. Required even if you do not plan to build 62 | the source code, as the runtime CUDA compilation mechanism depends on it. 63 | 64 | 65 | Instructions 66 | ------------ 67 | 68 | 1. Install Visual Studio 2010. The Express edition can be downloaded from: 69 | http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-cpp-express 70 | 71 | 2. Install the latest NVIDIA GPU drivers and CUDA Toolkit. 72 | http://developer.nvidia.com/object/cuda_archive.html 73 | 74 | 3. Run crsample.exe to start the application in interactive mode. The first 75 | run executes certain initialization tasks that may take a while to 76 | complete. 77 | 78 | 4. If you get an error during initialization, the most probable explanation 79 | is that the application is unable to launch nvcc.exe contained in the 80 | CUDA Toolkit. In this case, you should: 81 | 82 | - Set CUDA_BIN_PATH to point to the CUDA Toolkit "bin" directory, e.g. 83 | "set CUDA_BIN_PATH=C:\Program Files (x86)\NVIDIA GPU Computing Toolkit\CUDA\v4.2\bin". 84 | 85 | - Set CUDA_INC_PATH to point to the CUDA Toolkit "include" directory, e.g. 86 | "set CUDA_INC_PATH=C:\Program Files (x86)\NVIDIA GPU Computing Toolkit\CUDA\v4.2\include". 87 | 88 | - Run vcvars32.bat to setup Visual Studio paths, e.g. 89 | "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\vcvars32.bat". 90 | 91 | 5. Run benchmark.cmd to measure the performance of CudaRaster and OpenGL on 92 | both test scenes with the same settings that were used in the paper. 93 | The script may take roughly 15 minutes to complete. The results are written 94 | into "benchmark.log", and are organized according to the Table and Figure 95 | numbering in the paper. The files "benchmark-gtxXXX-cudaYY.log", included 96 | in the package, contain reference results for different GPUs and CUDA 97 | versions. 98 | 99 | 6. Optional: Build the application manually. 100 | 101 | - Open cudaraster.sln in Visual Studio 2010. 102 | - Right-click the "crsample" project and select "Set as StartUp Project". 103 | - Build and run. Release/Win32 is recommended. 104 | 105 | 106 | Package structure 107 | ----------------- 108 | 109 | /crsample.exe Pre-built binary for the sample app. 110 | /cudaraster.sln Visual Studio 2010 solution file. 111 | 112 | /benchmark.cmd Script to run the benchmarks. 113 | /benchmark.log Benchmark results. 114 | /_cam.png Result images. 115 | /benchmark-gtxXXX-cudaYY.log Reference results (GTX XXX, CUDA Y.Y). 116 | /state_crsample_.dat State files, exported with Alt-. 117 | /screenshot_crsample_.png Screenshots, exported with PrtScn. 118 | 119 | /scenes/ Test scenes in Wavefront OBJ format. 120 | /cudacache/ Temporary directory for CUDA binaries. 121 | /build/ Temporary directory for VS builds. 122 | 123 | /src/cudaraster/ Sources for the rasterizer. 124 | /src/cudaraster/CudaRaster.hpp Host-side public interface. 125 | /src/cudaraster/cuda/PixelPipe.hpp Device-side public interface. 126 | 127 | /src/crsample/ Sources for the sample application. 128 | /src/crsample/App.cpp Interactive mode. 129 | /src/crsample/Benchmark.cpp Benchmark mode. 130 | /src/crsample/Shaders.cu Device-side shader code. 131 | 132 | /src/framework/ General-purpose utility classes. 133 | 134 | 135 | Version history 136 | --------------- 137 | 138 | Version 1.1, May 22, 2012 139 | - Fix incorrect pixel coverage computation with CUDA 4.1 and above. 140 | - Fix incorrect ROP ordering with Kepler-based GPUs. 141 | - Switch to New BSD License (previously Apache License 2.0). 142 | - Upgrade to Visual Studio 2010 (previously 2008). 143 | - Support PNG textures through lodepng. 144 | - Fix a CUDA compilation issue with Visual Studio Express. 145 | - General bugfixes and improvements to framework. 146 | 147 | Version 1.0, Jul 08, 2011 148 | - Initial release. 149 | 150 | 151 | Known issues 152 | ------------ 153 | 154 | - The maximum viewport size is limited to 2048x2048, due to 32-bit fixed 155 | point math used in edge functions and plane equations. 156 | 157 | - Subpixel resolution (4 bits) is lower than in the hardware pipeline 158 | (8 bits). 159 | 160 | - Attribute precision is also lower. Upper bound for relative error is 2^-15 161 | without multisampling and 2^-12 with 8x MSAA. Depth, however, is very 162 | accurate. 163 | 164 | - The overall memory footprint of the current implementation is relatively 165 | high, roughly 90 bytes per triangle in one batch. This can be alleviated 166 | by splitting larger models into multiple batches. 167 | 168 | - The frame buffer is limited to 32-bit color and 32-bit depth. Support for 169 | other formats (e.g. float4) may be added in the future. 170 | 171 | - The support for mesh and image formats is very limited. In particular, 172 | only Wavefront OBJ meshes and truecolor PNG/TGA/TIFF/BMP textures are 173 | supported. If you have trouble importing a mesh, you may want to try 174 | enabling WAVEFRONT_DEBUG in src/framework/io/MeshWavefrontIO.cpp. 175 | 176 | 177 | Acknowledgements 178 | ---------------- 179 | 180 | University of Utah for the Fairy model. 181 | Brian Curless and Marc Levoy the Happy Buddha model. 182 | -------------------------------------------------------------------------------- /benchmark.cmd: -------------------------------------------------------------------------------- 1 | @echo off 2 | set EXE=crsample_Win32_Release.exe 3 | if not exist %EXE% set EXE=crsample.exe 4 | set LOG=benchmark.log 5 | 6 | set SCENENAME_A=FairyForest 7 | set SCENESPEC_A=--mesh=scenes/fairyforest/fairyforest.obj --camera="cIxMx/sK/Ty/EFu3z/5m9mWx/YPA5z/8///m007toC10AnAHx///Uy200" --camera="KI/Qz/zlsUy/TTy6z13BdCZy/LRxzy/8///m007toC10AnAHx///Uy200" --camera="mF5Gz1SuO1z/ZMooz11Q0bGz/CCNxx18///m007toC10AnAHx///Uy200" --camera="vH7Jy19GSHx/YN45x//P2Wpx1MkhWy18///m007toC10AnAHx///Uy200" --camera="ViGsx/KxTFz/Ypn8/05TJTmx1ljevx18///m007toC10AnAHx///Uy200" 8 | 9 | set SCENENAME_B=Buddha 10 | set SCENESPEC_B=--mesh=scenes/buddha/buddha.obj --camera="HPI2v1F8J8y/KWjMy/5obv7w15:Rax18jVXcw/sZPF10aFuns/cH0ay/0" --camera="5/1dv/wd3Hy/cxYIx/55Mifx1cH3Mx/8jVXcw/sZPF10aFuns/cH0ay/0" --camera="WXz2w/ZSfVy/Bw07x/45H26z1cBWfx18jVXcw/sZPF10aFuns/cH0ay/0" --camera="BSTSx/VdErx/ou1Yx/5fIYAz1B7WEz/8jVXcw/sZPF10aFuns/cH0ay/0" --camera="MKYVx1JieYx/TeR6y/57Tsfy/wljmy/8jVXcw/sZPF10aFuns/cH0ay/0" 11 | 12 | %EXE% bench-single %SCENESPEC_A% --image=%SCENENAME_A%.png 13 | %EXE% bench-single %SCENESPEC_B% --image=%SCENENAME_B%.png 14 | 15 | echo. >%LOG% 16 | echo Table 1: Resolutions >>%LOG% 17 | echo -------------------- >>%LOG% 18 | echo. >>%LOG% 19 | 20 | echo %SCENENAME_A% / CudaRaster: >>%LOG% & %EXE% bench-resolution --renderer=cuda %SCENESPEC_A% --log=%LOG% 21 | echo %SCENENAME_A% / OpenGL: >>%LOG% & %EXE% bench-resolution --renderer=gl %SCENESPEC_A% --log=%LOG% 22 | echo %SCENENAME_B% / CudaRaster: >>%LOG% & %EXE% bench-resolution --renderer=cuda %SCENESPEC_B% --log=%LOG% 23 | echo %SCENENAME_B% / OpenGL: >>%LOG% & %EXE% bench-resolution --renderer=gl %SCENESPEC_B% --log=%LOG% 24 | 25 | echo. >>%LOG% 26 | echo Table 2: Rendering modes >>%LOG% 27 | echo ------------------------ >>%LOG% 28 | echo. >>%LOG% 29 | 30 | echo %SCENENAME_A% / CudaRaster: >>%LOG% & %EXE% bench-rendermode --renderer=cuda %SCENESPEC_A% --log=%LOG% 31 | echo %SCENENAME_A% / OpenGL: >>%LOG% & %EXE% bench-rendermode --renderer=gl %SCENESPEC_A% --log=%LOG% 32 | echo %SCENENAME_B% / CudaRaster: >>%LOG% & %EXE% bench-rendermode --renderer=cuda %SCENESPEC_B% --log=%LOG% 33 | echo %SCENENAME_B% / OpenGL: >>%LOG% & %EXE% bench-rendermode --renderer=gl %SCENESPEC_B% --log=%LOG% 34 | 35 | echo. >>%LOG% 36 | echo Table 3: Profiling >>%LOG% 37 | echo ------------------ >>%LOG% 38 | echo. >>%LOG% 39 | 40 | echo %SCENENAME_A%: >>%LOG% & %EXE% bench-profile %SCENESPEC_A% --log=%LOG% 41 | echo %SCENENAME_B%: >>%LOG% & %EXE% bench-profile %SCENESPEC_B% --log=%LOG% 42 | 43 | echo. >>%LOG% 44 | echo Figure 5: Synthetic test >>%LOG% 45 | echo ------------------------ >>%LOG% 46 | echo. >>%LOG% 47 | 48 | echo CudaRaster: >>%LOG% & %EXE% bench-synthetic --renderer=cuda --depth=0 --lerp=0 --log=%LOG% 49 | echo OpenGL: >>%LOG% & %EXE% bench-synthetic --renderer=gl --depth=0 --lerp=0 --log=%LOG% 50 | 51 | echo. >>%LOG% 52 | echo Figure 6: Batching >>%LOG% 53 | echo ------------------ >>%LOG% 54 | echo. >>%LOG% 55 | 56 | echo %SCENENAME_A% / CudaRaster: >>%LOG% & %EXE% bench-batch --renderer=cuda %SCENESPEC_A% --log=%LOG% 57 | echo %SCENENAME_A% / OpenGL: >>%LOG% & %EXE% bench-batch --renderer=gl %SCENESPEC_A% --log=%LOG% 58 | echo %SCENENAME_B% / CudaRaster: >>%LOG% & %EXE% bench-batch --renderer=cuda %SCENESPEC_B% --log=%LOG% 59 | echo %SCENENAME_B% / OpenGL: >>%LOG% & %EXE% bench-batch --renderer=gl %SCENESPEC_B% --log=%LOG% 60 | 61 | type %LOG% 62 | -------------------------------------------------------------------------------- /cleanup.bat: -------------------------------------------------------------------------------- 1 | del *.png 2 | del *.user 3 | del *.sdf 4 | del *.suo 5 | del *.filters 6 | del crsample_Win32_Debug.exe 7 | del crsample_Win32_Release.exe 8 | del state_crsample_*.dat 9 | del *.opensdf 10 | del crsample.exe 11 | -------------------------------------------------------------------------------- /create_index.bat: -------------------------------------------------------------------------------- 1 | dir /s /b /a > file_index && gvim file_index 2 | -------------------------------------------------------------------------------- /cudaraster.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 11.00 3 | # Visual Studio 2010 4 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "framework", "framework.vcxproj", "{8E0B71BD-6F14-4F0C-AC34-45985043856F}" 5 | EndProject 6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "cudaraster", "cudaraster.vcxproj", "{8E0B71BD-6F14-4F0C-AC34-45334875453F}" 7 | EndProject 8 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "crsample", "crsample.vcxproj", "{EC32C587-08D5-4F90-8E47-453748674524}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Win32 = Debug|Win32 13 | Debug|x64 = Debug|x64 14 | Release|Win32 = Release|Win32 15 | Release|x64 = Release|x64 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {8E0B71BD-6F14-4F0C-AC34-45985043856F}.Debug|Win32.ActiveCfg = Debug|Win32 19 | {8E0B71BD-6F14-4F0C-AC34-45985043856F}.Debug|Win32.Build.0 = Debug|Win32 20 | {8E0B71BD-6F14-4F0C-AC34-45985043856F}.Debug|x64.ActiveCfg = Debug|x64 21 | {8E0B71BD-6F14-4F0C-AC34-45985043856F}.Debug|x64.Build.0 = Debug|x64 22 | {8E0B71BD-6F14-4F0C-AC34-45985043856F}.Release|Win32.ActiveCfg = Release|Win32 23 | {8E0B71BD-6F14-4F0C-AC34-45985043856F}.Release|Win32.Build.0 = Release|Win32 24 | {8E0B71BD-6F14-4F0C-AC34-45985043856F}.Release|x64.ActiveCfg = Release|x64 25 | {8E0B71BD-6F14-4F0C-AC34-45985043856F}.Release|x64.Build.0 = Release|x64 26 | {8E0B71BD-6F14-4F0C-AC34-45334875453F}.Debug|Win32.ActiveCfg = Debug|Win32 27 | {8E0B71BD-6F14-4F0C-AC34-45334875453F}.Debug|Win32.Build.0 = Debug|Win32 28 | {8E0B71BD-6F14-4F0C-AC34-45334875453F}.Debug|x64.ActiveCfg = Debug|x64 29 | {8E0B71BD-6F14-4F0C-AC34-45334875453F}.Debug|x64.Build.0 = Debug|x64 30 | {8E0B71BD-6F14-4F0C-AC34-45334875453F}.Release|Win32.ActiveCfg = Release|Win32 31 | {8E0B71BD-6F14-4F0C-AC34-45334875453F}.Release|Win32.Build.0 = Release|Win32 32 | {8E0B71BD-6F14-4F0C-AC34-45334875453F}.Release|x64.ActiveCfg = Release|x64 33 | {8E0B71BD-6F14-4F0C-AC34-45334875453F}.Release|x64.Build.0 = Release|x64 34 | {EC32C587-08D5-4F90-8E47-453748674524}.Debug|Win32.ActiveCfg = Debug|Win32 35 | {EC32C587-08D5-4F90-8E47-453748674524}.Debug|Win32.Build.0 = Debug|Win32 36 | {EC32C587-08D5-4F90-8E47-453748674524}.Debug|x64.ActiveCfg = Debug|x64 37 | {EC32C587-08D5-4F90-8E47-453748674524}.Debug|x64.Build.0 = Debug|x64 38 | {EC32C587-08D5-4F90-8E47-453748674524}.Release|Win32.ActiveCfg = Release|Win32 39 | {EC32C587-08D5-4F90-8E47-453748674524}.Release|Win32.Build.0 = Release|Win32 40 | {EC32C587-08D5-4F90-8E47-453748674524}.Release|x64.ActiveCfg = Release|x64 41 | {EC32C587-08D5-4F90-8E47-453748674524}.Release|x64.Build.0 = Release|x64 42 | EndGlobalSection 43 | GlobalSection(SolutionProperties) = preSolution 44 | HideSolutionNode = FALSE 45 | EndGlobalSection 46 | EndGlobal 47 | -------------------------------------------------------------------------------- /src/crsample/App.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #pragma once 29 | #include "Shaders.hpp" 30 | #include "gui/CommonControls.hpp" 31 | #include "3d/CameraControls.hpp" 32 | #include "3d/TextureAtlas.hpp" 33 | #include "gpu/CudaCompiler.hpp" 34 | #include "CudaRaster.hpp" 35 | 36 | namespace FW 37 | { 38 | //------------------------------------------------------------------------ 39 | 40 | class App : public Window::Listener, public CommonControls::StateObject 41 | { 42 | private: 43 | enum Action 44 | { 45 | Action_None, 46 | 47 | Action_About, 48 | Action_LoadMesh, 49 | 50 | Action_ResetCamera, 51 | Action_ExportCamera, 52 | Action_ImportCamera, 53 | }; 54 | 55 | enum Mode 56 | { 57 | Mode_CudaRaster = 0, 58 | Mode_OpenGL, 59 | }; 60 | 61 | public: 62 | App (void); 63 | virtual ~App (void); 64 | 65 | virtual bool handleEvent (const Window::Event& ev); 66 | virtual void readState (StateDump& d); 67 | virtual void writeState (StateDump& d) const; 68 | 69 | private: 70 | void loadMesh (const String& fileName); 71 | void setMesh (MeshBase* mesh); 72 | void setupTexture (TextureSpec& spec, const Texture& tex); 73 | 74 | void render (GLContext* gl); 75 | void initPipe (void); 76 | 77 | void firstTimeInit (void); 78 | 79 | private: 80 | App (const App&); // forbidden 81 | App& operator= (const App&); // forbidden 82 | 83 | private: 84 | Window m_window; 85 | CommonControls m_commonCtrl; 86 | CameraControls m_cameraCtrl; 87 | CudaCompiler m_cudaCompiler; 88 | CudaRaster m_cudaRaster; 89 | 90 | // State. 91 | 92 | Action m_action; 93 | String m_meshFileName; 94 | bool m_showHelp; 95 | bool m_showStats; 96 | Mode m_mode; 97 | bool m_enableTexPhong; 98 | bool m_enableDepth; 99 | bool m_enableBlend; 100 | bool m_enableLerp; 101 | bool m_enableQuads; 102 | S32 m_numSamples; 103 | 104 | // Mesh. 105 | 106 | MeshBase* m_mesh; 107 | S32 m_numVertices; 108 | S32 m_numMaterials; 109 | S32 m_numTriangles; 110 | Buffer m_inputVertices; 111 | Buffer m_shadedVertices; 112 | Buffer m_materials; 113 | Buffer m_vertexIndices; 114 | Buffer m_vertexMaterialIdx; 115 | Buffer m_triangleMaterialIdx; 116 | TextureAtlas m_textureAtlas; 117 | 118 | // Pipe. 119 | 120 | bool m_pipeDirty; 121 | CudaSurface* m_colorBuffer; 122 | CudaSurface* m_depthBuffer; 123 | CudaModule* m_cudaModule; 124 | CudaKernel m_vertexShaderKernel; 125 | }; 126 | 127 | //------------------------------------------------------------------------ 128 | } 129 | -------------------------------------------------------------------------------- /src/crsample/Benchmark.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #pragma once 29 | #include "3d/CameraControls.hpp" 30 | #include "gpu/CudaCompiler.hpp" 31 | #include "CudaRaster.hpp" 32 | 33 | namespace FW 34 | { 35 | //------------------------------------------------------------------------ 36 | 37 | class Benchmark 38 | { 39 | public: 40 | enum Renderer 41 | { 42 | Renderer_CudaRaster, 43 | Renderer_OpenGL 44 | }; 45 | 46 | enum Blend 47 | { 48 | Blend_Replace, 49 | Blend_SrcOver, 50 | Blend_DepthOnly, 51 | }; 52 | 53 | struct Result 54 | { 55 | F32 totalTime; 56 | F32 setupTime; 57 | F32 binTime; 58 | F32 coarseTime; 59 | F32 fineTime; 60 | String profilingInfo; 61 | 62 | Result(void) 63 | { 64 | totalTime = 0.0f, setupTime = 0.0f, binTime = 0.0f, coarseTime = 0.0f, fineTime = 0.0f; 65 | } 66 | 67 | Result& operator+=(const Result& r) 68 | { 69 | totalTime += r.totalTime, setupTime += r.setupTime, binTime += r.binTime, coarseTime += r.coarseTime, fineTime += r.fineTime; 70 | profilingInfo += r.profilingInfo; 71 | return *this; 72 | } 73 | 74 | Result& operator*=(F32 c) 75 | { 76 | totalTime *= c, setupTime *= c, binTime *= c, coarseTime *= c, fineTime *= c; 77 | return *this; 78 | } 79 | }; 80 | 81 | struct Params 82 | { 83 | Renderer renderer; 84 | Vec2i resolution; 85 | S32 numSamples; 86 | U32 renderModeFlags; 87 | Blend blend; 88 | Array cameras; 89 | String logFileName; 90 | String imageFileName; 91 | 92 | Params(void) 93 | { 94 | renderer = Renderer_CudaRaster; 95 | resolution = Vec2i(1024, 768); 96 | numSamples = 1; 97 | renderModeFlags = RenderModeFlag_EnableDepth | RenderModeFlag_EnableLerp; 98 | blend = Blend_Replace; 99 | } 100 | }; 101 | 102 | public: 103 | Benchmark (void); 104 | ~Benchmark (void); 105 | 106 | // Utilities. 107 | 108 | void log (const String& fileName, const String& msg); 109 | String appendFileName (const String& fileName, const String& postfix); 110 | 111 | // Core functionality. 112 | 113 | void loadMesh (const String& fileName); 114 | void initPipe (const Vec2i& resolution, int numSamples, U32 renderModeFlags, Blend blend, int profilingMode); 115 | void runVertexShader (const String& camera); 116 | Result runSingle (Renderer renderer, int numBatches, const String& imageFileName); 117 | Result runCameras (Renderer renderer, int numBatches, const String& imageFileName, const Array& cameras); 118 | 119 | // Benchmark types. 120 | 121 | void typeSingle (const Params& p); 122 | void typeResolution (const Params& p); // Table 1 123 | void typeRenderMode (const Params& p); // Table 2 124 | void typeProfile (const Params& p); // Table 3 125 | void typeSynthetic (const Params& p); // Figure 5 126 | void typeBatch (const Params& p); // Figure 6 127 | 128 | private: 129 | Benchmark (const Benchmark&); // forbidden 130 | Benchmark& operator= (const Benchmark&); // forbidden 131 | 132 | private: 133 | Window m_window; 134 | CameraControls m_cameraCtrl; 135 | CudaCompiler m_cudaCompiler; 136 | CudaRaster m_cudaRaster; 137 | 138 | // Mesh. 139 | 140 | S32 m_numVertices; 141 | S32 m_numMaterials; 142 | S32 m_numTriangles; 143 | Buffer m_inputVertices; 144 | Buffer m_shadedVertices; 145 | Buffer m_materials; 146 | Buffer m_vertexIndices; 147 | Buffer m_vertexMaterialIdx; 148 | 149 | // Pipe. 150 | 151 | bool m_enableLerp; 152 | CudaSurface* m_colorBuffer; 153 | CudaSurface* m_depthBuffer; 154 | CudaModule* m_cudaModule; 155 | 156 | // GL framebuffer objects. 157 | 158 | GLuint m_glDrawColorRenderbuffer; 159 | GLuint m_glDrawDepthRenderbuffer; 160 | GLuint m_glResolveColorRenderbuffer; 161 | GLuint m_glDrawFramebuffer; 162 | GLuint m_glResolveFramebuffer; 163 | }; 164 | 165 | //------------------------------------------------------------------------ 166 | } 167 | -------------------------------------------------------------------------------- /src/crsample/Shaders.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #pragma once 29 | #include "cuda/PixelPipe.hpp" 30 | 31 | namespace FW 32 | { 33 | //------------------------------------------------------------------------ 34 | // Texture specification. 35 | //------------------------------------------------------------------------ 36 | 37 | struct TextureSpec 38 | { 39 | Vec2f size; 40 | U32 pad[2]; 41 | Vec4f mipLevels[16]; // scaleX, scaleY, biasX, biasY 42 | }; 43 | 44 | //------------------------------------------------------------------------ 45 | // Material parameters. 46 | //------------------------------------------------------------------------ 47 | 48 | struct Material 49 | { 50 | Vec4f diffuseColor; 51 | Vec3f specularColor; 52 | F32 glossiness; 53 | TextureSpec diffuseTexture; 54 | TextureSpec alphaTexture; 55 | }; 56 | 57 | //------------------------------------------------------------------------ 58 | // Constants. 59 | //------------------------------------------------------------------------ 60 | 61 | struct Constants 62 | { 63 | Mat4f posToClip; 64 | Mat4f posToCamera; 65 | Mat3f normalToCamera; 66 | CUdeviceptr materials; // numMaterials * Material 67 | CUdeviceptr vertexMaterialIdx; // numVertices * S32 68 | CUdeviceptr triangleMaterialIdx; // numTriangles * S32 69 | }; 70 | 71 | //------------------------------------------------------------------------ 72 | // Vertex attributes. 73 | //------------------------------------------------------------------------ 74 | 75 | struct InputVertex 76 | { 77 | Vec3f modelPos; 78 | Vec3f modelNormal; 79 | Vec2f texCoord; 80 | }; 81 | 82 | //------------------------------------------------------------------------ 83 | // Varyings. 84 | //------------------------------------------------------------------------ 85 | 86 | typedef GouraudVertex ShadedVertex_gouraud; 87 | 88 | //------------------------------------------------------------------------ 89 | 90 | struct ShadedVertex_texPhong : ShadedVertexBase 91 | { 92 | Vec4f cameraPos; // Varying 0. 93 | Vec4f cameraNormal; // Varying 1. 94 | Vec4f texCoord; // Varying 2. 95 | }; 96 | 97 | //------------------------------------------------------------------------ 98 | // Globals. 99 | //------------------------------------------------------------------------ 100 | 101 | #if FW_CUDA 102 | 103 | extern "C" __constant__ Constants c_constants; 104 | extern "C" texture t_textureAtlas; 105 | 106 | __device__ Vec3f evaluateLighting (Vec3f cameraPos, Vec3f cameraNormal, const Material& material, Vec3f diffuseColor); 107 | extern "C" __global__ void vertexShader_gouraud (const InputVertex* inPtr, ShadedVertex_gouraud* outPtr, int numVertices); 108 | extern "C" __global__ void vertexShader_texPhong (const InputVertex* inPtr, ShadedVertex_texPhong* outPtr, int numVertices); 109 | 110 | // CR_DEFINE_PIXEL_PIPE(PixelPipe_gouraud, ...) 111 | // CR_DEFINE_PIXEL_PIPE(PixelPipe_texPhong, ...) 112 | 113 | #endif 114 | 115 | //------------------------------------------------------------------------ 116 | } 117 | -------------------------------------------------------------------------------- /src/cudaraster/CudaRaster.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #pragma once 29 | #include "CudaSurface.hpp" 30 | #include "gui/Image.hpp" 31 | #include "gpu/CudaModule.hpp" 32 | #include "cuda/PixelPipe.hpp" 33 | #include "cuda/PrivateDefs.hpp" 34 | 35 | namespace FW 36 | { 37 | //------------------------------------------------------------------------ 38 | // CudaRaster host-side public interface. 39 | //------------------------------------------------------------------------ 40 | 41 | class CudaRaster 42 | { 43 | public: 44 | struct Stats // Statistics for the previous call to drawTriangles(). 45 | { 46 | F32 setupTime; // Seconds spent in TriangleSetup. 47 | F32 binTime; // Seconds spent in BinRaster. 48 | F32 coarseTime; // Seconds spent in CoarseRaster. 49 | F32 fineTime; // Seconds spent in FineRaster. 50 | }; 51 | 52 | struct DebugParams // Host-side emulation of individual stages, for debugging purposes. 53 | { 54 | bool emulateTriangleSetup; 55 | bool emulateBinRaster; 56 | bool emulateCoarseRaster; 57 | bool emulateFineRaster; // Only supports GouraudShader, BlendReplace, and BlendSrcOver. 58 | 59 | DebugParams(void) 60 | { 61 | emulateTriangleSetup = false; 62 | emulateBinRaster = false; 63 | emulateCoarseRaster = false; 64 | emulateFineRaster = false; 65 | } 66 | }; 67 | 68 | public: 69 | CudaRaster (void); 70 | ~CudaRaster (void); 71 | 72 | void setSurfaces (CudaSurface* color, CudaSurface* depth); // Set before calling other methods. 73 | void deferredClear (const Vec4f& color = 0.0f, F32 depth = 1.0f); // Clear surfaces on the next call to drawTriangles(). 74 | 75 | void setPixelPipe (CudaModule* module, const String& name); // See CR_DEFINE_PIXEL_PIPE() in PixelPipe.hpp. 76 | void setVertexBuffer (Buffer* buf, S64 ofs); 77 | void setIndexBuffer (Buffer* buf, S64 ofs, int numTris); 78 | void drawTriangles (void); // Draw all triangles specified by the current index buffer. 79 | 80 | Stats getStats (void); 81 | String getProfilingInfo (void); // See CR_PROFILING_MODE in PixelPipe.hpp. 82 | void setDebugParams (const DebugParams& p); 83 | 84 | private: 85 | void launchStages (void); 86 | 87 | Vec3i setupPleq (const Vec3f& values, const Vec2i& v0, const Vec2i& d1, const Vec2i& d2, S32 area, int samplesLog2); 88 | 89 | bool setupTriangle (int triIdx, 90 | const Vec4f& v0, const Vec4f& v1, const Vec4f& v2, 91 | const Vec2f& b0, const Vec2f& b1, const Vec2f& b2, 92 | const Vec3i& vidx); 93 | 94 | void emulateTriangleSetup (void); 95 | void emulateBinRaster (void); 96 | void emulateCoarseRaster (void); 97 | void emulateFineRaster (void); 98 | 99 | private: 100 | CudaRaster (const CudaRaster&); // forbidden 101 | CudaRaster& operator= (const CudaRaster&); // forbidden 102 | 103 | private: 104 | // State. 105 | 106 | CudaSurface* m_colorBuffer; 107 | CudaSurface* m_depthBuffer; 108 | 109 | bool m_deferredClear; 110 | U32 m_clearColor; 111 | U32 m_clearDepth; 112 | 113 | Buffer* m_vertexBuffer; 114 | S64 m_vertexOfs; 115 | Buffer* m_indexBuffer; 116 | S64 m_indexOfs; 117 | S32 m_numTris; 118 | 119 | // Surfaces. 120 | 121 | Vec2i m_viewportSize; 122 | Vec2i m_sizePixels; 123 | Vec2i m_sizeBins; 124 | S32 m_numBins; 125 | Vec2i m_sizeTiles; 126 | S32 m_numTiles; 127 | S32 m_numSamples; 128 | S32 m_samplesLog2; 129 | 130 | // Pixel pipe. 131 | 132 | CudaModule* m_module; 133 | CudaKernel m_setupKernel; 134 | CudaKernel m_binKernel; 135 | CudaKernel m_coarseKernel; 136 | CudaKernel m_fineKernel; 137 | PixelPipeSpec m_pipeSpec; 138 | S32 m_numSMs; 139 | S32 m_numFineWarps; 140 | 141 | // Buffers. 142 | 143 | S32 m_binBatchSize; 144 | 145 | S32 m_maxSubtris; 146 | Buffer m_triSubtris; 147 | Buffer m_triHeader; 148 | Buffer m_triData; 149 | 150 | S32 m_maxBinSegs; 151 | Buffer m_binFirstSeg; 152 | Buffer m_binTotal; 153 | Buffer m_binSegData; 154 | Buffer m_binSegNext; 155 | Buffer m_binSegCount; 156 | 157 | S32 m_maxTileSegs; 158 | Buffer m_activeTiles; 159 | Buffer m_tileFirstSeg; 160 | Buffer m_tileSegData; 161 | Buffer m_tileSegNext; 162 | Buffer m_tileSegCount; 163 | 164 | // Stats, profiling, debug. 165 | 166 | CUevent m_evSetupBegin; 167 | CUevent m_evBinBegin; 168 | CUevent m_evCoarseBegin; 169 | CUevent m_evFineBegin; 170 | CUevent m_evFineEnd; 171 | Buffer m_profData; 172 | DebugParams m_debug; 173 | }; 174 | 175 | //------------------------------------------------------------------------ 176 | } 177 | -------------------------------------------------------------------------------- /src/cudaraster/CudaSurface.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #pragma once 29 | #include "gpu/GLContext.hpp" 30 | 31 | namespace FW 32 | { 33 | //------------------------------------------------------------------------ 34 | // Render target for CudaRaster, visible in OpenGL as a 2D texture. 35 | //------------------------------------------------------------------------ 36 | 37 | class CudaSurface 38 | { 39 | public: 40 | enum Format 41 | { 42 | Format_R8_G8_B8_A8 = 0, // U8 red, U8 green, U8 blue, U8 alpha 43 | Format_Depth32, // U32 depth 44 | 45 | Format_Max 46 | }; 47 | 48 | public: 49 | CudaSurface (const Vec2i& size, Format format, int numSamples = 1); 50 | ~CudaSurface (void); 51 | 52 | const Vec2i& getSize (void) const { return m_size; } // Original size specified in the constructor. 53 | const Vec2i& getRoundedSize (void) const { return m_roundedSize; } // Rounded to full 8x8 tiles. 54 | const Vec2i& getTextureSize (void) const { return m_textureSize; } // 8x8 tiles are replicated horizontally for MSAA. 55 | Format getFormat (void) const { return m_format; } 56 | int getNumSamples (void) const { return m_numSamples; } 57 | int getSamplesLog2 (void) const { return popc8(m_numSamples - 1); } // log2(numSamples) 58 | 59 | GLuint getGLTexture (void); // Invalidates the CUDA array. 60 | CUarray getCudaArray (void); // Invalidates the GL texture. 61 | 62 | void resolveToScreen (GLContext* gl); // Resolves MSAA and writes pixels into the current GL render target. 63 | 64 | private: 65 | CudaSurface (const CudaSurface&); // forbidden 66 | CudaSurface& operator= (const CudaSurface&); // forbidden 67 | 68 | private: 69 | Vec2i m_size; 70 | Vec2i m_roundedSize; 71 | Vec2i m_textureSize; 72 | Format m_format; 73 | S32 m_numSamples; 74 | 75 | GLuint m_glTexture; 76 | CUgraphicsResource m_cudaResource; 77 | bool m_isMapped; 78 | CUarray m_cudaArray; 79 | }; 80 | 81 | //------------------------------------------------------------------------ 82 | } 83 | -------------------------------------------------------------------------------- /src/cudaraster/cuda/Constants.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #pragma once 29 | 30 | //------------------------------------------------------------------------ 31 | 32 | #define CR_MAXVIEWPORT_LOG2 11 // ViewportSize / PixelSize. 33 | #define CR_SUBPIXEL_LOG2 4 // PixelSize / SubpixelSize. 34 | 35 | #define CR_MAXBINS_LOG2 4 // ViewportSize / BinSize. 36 | #define CR_BIN_LOG2 4 // BinSize / TileSize. 37 | #define CR_TILE_LOG2 3 // TileSize / PixelSize. 38 | 39 | #define CR_COVER8X8_LUT_SIZE 768 // 64-bit entries. 40 | #define CR_FLIPBIT_FLIP_Y 2 41 | #define CR_FLIPBIT_FLIP_X 3 42 | #define CR_FLIPBIT_SWAP_XY 4 43 | #define CR_FLIPBIT_COMPL 5 44 | 45 | #define CR_BIN_STREAMS_LOG2 4 46 | #define CR_BIN_SEG_LOG2 9 // 32-bit entries. 47 | #define CR_TILE_SEG_LOG2 5 // 32-bit entries. 48 | 49 | #define CR_MAXSUBTRIS_LOG2 24 // Triangle structs. Dictated by CoarseRaster. 50 | #define CR_COARSE_QUEUE_LOG2 10 // Triangles. 51 | 52 | #define CR_SETUP_WARPS 2 53 | #define CR_SETUP_OPT_BLOCKS 8 54 | #define CR_BIN_WARPS 16 55 | #define CR_COARSE_WARPS 16 // Must be a power of two. 56 | #define CR_FINE_MAX_WARPS 20 // Absolute maximum for 48KB of shared mem. 57 | #define CR_FINE_OPT_WARPS 20 // Preferred value. 58 | 59 | //------------------------------------------------------------------------ 60 | 61 | #define CR_MAXVIEWPORT_SIZE (1 << CR_MAXVIEWPORT_LOG2) 62 | #define CR_SUBPIXEL_SIZE (1 << CR_SUBPIXEL_LOG2) 63 | #define CR_SUBPIXEL_SQR (1 << (CR_SUBPIXEL_LOG2 * 2)) 64 | 65 | #define CR_MAXBINS_SIZE (1 << CR_MAXBINS_LOG2) 66 | #define CR_MAXBINS_SQR (1 << (CR_MAXBINS_LOG2 * 2)) 67 | #define CR_BIN_SIZE (1 << CR_BIN_LOG2) 68 | #define CR_BIN_SQR (1 << (CR_BIN_LOG2 * 2)) 69 | 70 | #define CR_MAXTILES_LOG2 (CR_MAXBINS_LOG2 + CR_BIN_LOG2) 71 | #define CR_MAXTILES_SIZE (1 << CR_MAXTILES_LOG2) 72 | #define CR_MAXTILES_SQR (1 << (CR_MAXTILES_LOG2 * 2)) 73 | #define CR_TILE_SIZE (1 << CR_TILE_LOG2) 74 | #define CR_TILE_SQR (1 << (CR_TILE_LOG2 * 2)) 75 | 76 | #define CR_BIN_STREAMS_SIZE (1 << CR_BIN_STREAMS_LOG2) 77 | #define CR_BIN_SEG_SIZE (1 << CR_BIN_SEG_LOG2) 78 | #define CR_TILE_SEG_SIZE (1 << CR_TILE_SEG_LOG2) 79 | 80 | #define CR_MAXSUBTRIS_SIZE (1 << CR_MAXSUBTRIS_LOG2) 81 | #define CR_COARSE_QUEUE_SIZE (1 << CR_COARSE_QUEUE_LOG2) 82 | 83 | //------------------------------------------------------------------------ 84 | // When evaluating interpolated Z/W/U/V at pixel centers, we introduce an 85 | // error of (+-CR_LERP_ERROR) ULPs. If it wasn't for integer overflows, 86 | // we could utilize the full U32 range for depth to get maximal 87 | // precision. However, to avoid overflows, we must shrink the range 88 | // slightly from both ends. With W/U/V, another difficulty is that quad 89 | // rendering can cause them to be evaluated outside the triangle, so we 90 | // need to shrink the range even more. 91 | 92 | #define CR_LERP_ERROR(SAMPLES_LOG2) (2200u << (SAMPLES_LOG2)) 93 | #define CR_DEPTH_MIN CR_LERP_ERROR(3) 94 | #define CR_DEPTH_MAX (FW_U32_MAX - CR_LERP_ERROR(3)) 95 | #define CR_BARY_MAX ((1 << (30 - CR_SUBPIXEL_LOG2)) - 1) 96 | 97 | //------------------------------------------------------------------------ 98 | -------------------------------------------------------------------------------- /src/framework/3d/CameraControls.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #pragma once 29 | #include "gui/CommonControls.hpp" 30 | #include "base/Timer.hpp" 31 | 32 | namespace FW 33 | { 34 | //------------------------------------------------------------------------ 35 | 36 | class MeshBase; 37 | 38 | //------------------------------------------------------------------------ 39 | 40 | class CameraControls : public Window::Listener, public CommonControls::StateObject 41 | { 42 | public: 43 | 44 | //------------------------------------------------------------------------ 45 | 46 | enum Feature 47 | { 48 | Feature_AlignYButton = 1 << 0, 49 | Feature_AlignZButton = 1 << 1, 50 | Feature_KeepAlignToggle = 1 << 2, 51 | Feature_SpeedSlider = 1 << 3, 52 | Feature_FOVSlider = 1 << 4, 53 | Feature_NearSlider = 1 << 5, 54 | Feature_FarSlider = 1 << 6, 55 | Feature_StereoControls = 1 << 7, 56 | 57 | Feature_None = 0, 58 | Feature_All = (1 << 8) - 1, 59 | Feature_Default = Feature_All & ~Feature_StereoControls 60 | }; 61 | 62 | //------------------------------------------------------------------------ 63 | 64 | public: 65 | CameraControls (CommonControls* commonControls = NULL, U32 features = Feature_Default); 66 | virtual ~CameraControls (void); 67 | 68 | virtual bool handleEvent (const Window::Event& ev); // must be before the listener that queries things 69 | virtual void readState (StateDump& d); 70 | virtual void writeState (StateDump& d) const; 71 | 72 | const Vec3f& getPosition (void) const { return m_position; } 73 | void setPosition (const Vec3f& v) { m_position = v; repaint(); } 74 | const Vec3f& getForward (void) const { return m_forward; } 75 | void setForward (const Vec3f& v) { m_forward = v; repaint(); } 76 | const Vec3f& getUp (void) const { return m_up; } 77 | void setUp (const Vec3f& v) { m_up = v; repaint(); } 78 | bool getKeepAligned (void) const { return m_keepAligned; } 79 | void setKeepAligned (bool v) { m_keepAligned = v; } 80 | F32 getSpeed (void) const { return m_speed; } 81 | void setSpeed (F32 v) { m_speed = v; } 82 | F32 getFOV (void) const { return m_fov; } 83 | void setFOV (F32 v) { m_fov = v; repaint(); } 84 | F32 getNear (void) const { return m_near; } 85 | void setNear (F32 v) { m_near = v; repaint(); } 86 | F32 getFar (void) const { return m_far; } 87 | void setFar (F32 v) { m_far = v; repaint(); } 88 | 89 | Mat3f getOrientation (void) const; 90 | Mat4f getCameraToWorld (void) const; 91 | Mat4f getWorldToCamera (void) const; 92 | Mat4f getCameraToClip (void) const { return Mat4f::perspective(m_fov, m_near, m_far); } 93 | Mat4f getWorldToClip (void) const { return getCameraToClip() * getWorldToCamera(); } 94 | Mat4f getCameraToLeftEye (void) const { Mat4f m; m.m02 = m_stereoConvergence; m.m03 = m_stereoSeparation; return m; } 95 | Mat4f getCameraToRightEye (void) const { return getCameraToLeftEye().inverted(); } 96 | 97 | void setCameraToWorld (const Mat4f& m); // Sets position & forward, and up if !keepAligned. 98 | void setWorldToCamera (const Mat4f& m) { setCameraToWorld(invert(m)); } 99 | 100 | void initDefaults (void); 101 | void initForMesh (const MeshBase* mesh); 102 | 103 | String encodeSignature (void) const; 104 | void decodeSignature (const String& sig); 105 | 106 | void addGUIControls (void); // done automatically on Window.addListener(this) 107 | void removeGUIControls (void); 108 | void setEnableMovement (bool enable) { m_enableMovement = enable; } 109 | 110 | private: 111 | bool hasFeature (Feature feature) { return ((m_features & feature) != 0); } 112 | void repaint (void) { if (m_window) m_window->repaint(); } 113 | 114 | static void encodeBits (String& dst, U32 v); 115 | static U32 decodeBits (const char*& src); 116 | 117 | static void encodeFloat (String& dst, F32 v); 118 | static F32 decodeFloat (const char*& src); 119 | 120 | static void encodeDirection (String& dst, const Vec3f& v); 121 | static Vec3f decodeDirection (const char*& src); 122 | 123 | private: 124 | CameraControls (const CameraControls&); // forbidden 125 | CameraControls& operator= (const CameraControls&); // forbidden 126 | 127 | private: 128 | CommonControls* m_commonControls; 129 | U32 m_features; 130 | Window* m_window; 131 | Timer m_timer; 132 | bool m_enableMovement; 133 | 134 | Vec3f m_position; 135 | Vec3f m_forward; 136 | Vec3f m_up; 137 | 138 | bool m_keepAligned; 139 | F32 m_speed; 140 | F32 m_fov; 141 | F32 m_near; 142 | F32 m_far; 143 | 144 | bool m_dragLeft; 145 | bool m_dragMiddle; 146 | bool m_dragRight; 147 | bool m_alignY; 148 | bool m_alignZ; 149 | 150 | bool m_enableStereo; 151 | F32 m_stereoSeparation; 152 | F32 m_stereoConvergence; 153 | }; 154 | 155 | //------------------------------------------------------------------------ 156 | } 157 | -------------------------------------------------------------------------------- /src/framework/3d/ConvexPolyhedron.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #pragma once 29 | #include "3d/Mesh.hpp" 30 | 31 | namespace FW 32 | { 33 | //------------------------------------------------------------------------ 34 | 35 | class ConvexPolyhedron 36 | { 37 | public: 38 | struct Vertex 39 | { 40 | Vec3f pos; 41 | union 42 | { 43 | F32 orient; 44 | S32 remap; 45 | } aux; 46 | }; 47 | 48 | struct Edge 49 | { 50 | Vec2i verts; 51 | S32 remap; 52 | }; 53 | 54 | struct Face 55 | { 56 | Vec4f planeEq; 57 | S32 planeID; 58 | S32 firstEdge; 59 | S32 numEdges; 60 | S32 newEdge; 61 | }; 62 | 63 | struct FaceEdge 64 | { 65 | S32 edge; 66 | S32 old; 67 | }; 68 | 69 | public: 70 | ConvexPolyhedron (void) {} 71 | ConvexPolyhedron (const Vec3f& lo, const Vec3f& hi) { setCube(lo, hi); } 72 | ConvexPolyhedron (const ConvexPolyhedron& other) { set(other); } 73 | ~ConvexPolyhedron (void) {} 74 | 75 | int getNumVertices (void) const { return m_vertices.getSize(); } 76 | const Vec3f& getVertex (int idx) const { return m_vertices[idx].pos; } 77 | 78 | int getNumEdges (void) const { return m_edges.getSize(); } 79 | Vec2i getEdge (int idx) const { const Vec2i& e = m_edges[idx ^ (idx >> 31)].verts; return (idx >= 0) ? e : Vec2i(e.y, e.x); } 80 | int getEdgeStartVertex (int idx) const { return (idx >= 0) ? m_edges[idx].verts.x : m_edges[~idx].verts.y; } 81 | int getEdgeEndVertex (int idx) const { return (idx >= 0) ? m_edges[idx].verts.y : m_edges[~idx].verts.x; } 82 | const Vec3f& getEdgeStartPos (int idx) const { return m_vertices[getEdgeStartVertex(idx)].pos; } 83 | const Vec3f& getEdgeEndPos (int idx) const { return m_vertices[getEdgeEndVertex(idx)].pos; } 84 | 85 | int getNumFaces (void) const { return m_faces.getSize(); } 86 | const Vec4f& getFacePlaneEq (int idx) const { return m_faces[idx].planeEq; } 87 | int getFacePlaneID (int idx) const { return m_faces[idx].planeID; } 88 | int getFaceNumEdges (int idx) const { return m_faces[idx].numEdges; } 89 | int getFaceEdge (int faceIdx, int idx) { FW_ASSERT(idx >= 0 && idx < m_faces[faceIdx].numEdges); return m_faceEdges[m_faces[faceIdx].firstEdge + idx].edge; } 90 | 91 | void set (const ConvexPolyhedron& other) { m_vertices = other.m_vertices; m_edges = other.m_edges; m_faces = other.m_faces; m_faceEdges = other.m_faceEdges; } 92 | void setEmpty (void) { m_vertices.clear(); m_edges.clear(); m_faces.clear(); m_faceEdges.clear(); } 93 | void setCube (const Vec3f& lo, const Vec3f& hi); 94 | 95 | bool intersect (const Vec4f& planeEq, int planeID = -1); 96 | bool intersect (const ConvexPolyhedron& other); 97 | bool intersectCube (const Vec3f& lo, const Vec3f& hi) { ConvexPolyhedron t; t.setCube(lo, hi); return intersect(t); } 98 | 99 | F32 computeVolume (void) const; 100 | F32 computeArea (int faceIdx) const; 101 | F32 computeArea (void) const { F32 t = 0.0f; for (int i = 0; i < m_faces.getSize(); i++) t += computeArea(i); return t; } 102 | Vec3f computeCenterOfMass (int faceIdx) const; 103 | Vec3f computeCenterOfMass (void) const; 104 | Mesh* createMesh (void) const; 105 | 106 | ConvexPolyhedron& operator= (const ConvexPolyhedron& other) { set(other); return *this; } 107 | 108 | private: 109 | Array m_vertices; 110 | Array m_edges; 111 | Array m_faces; 112 | Array m_faceEdges; 113 | }; 114 | 115 | //------------------------------------------------------------------------ 116 | } 117 | -------------------------------------------------------------------------------- /src/framework/3d/Texture.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #include "3d/Texture.hpp" 29 | #include "gpu/CudaModule.hpp" 30 | 31 | using namespace FW; 32 | 33 | //------------------------------------------------------------------------ 34 | 35 | Hash* Texture::s_hash = NULL; 36 | 37 | //------------------------------------------------------------------------ 38 | 39 | Texture::Texture(Image* image, const String& id) 40 | { 41 | m_data = createData(id); 42 | m_data->image = image; 43 | } 44 | 45 | //------------------------------------------------------------------------ 46 | 47 | Texture Texture::find(const String& id) 48 | { 49 | Texture tex; 50 | tex.m_data = findData(id); 51 | return tex; 52 | } 53 | 54 | //------------------------------------------------------------------------ 55 | 56 | Texture Texture::import(const String& fileName) 57 | { 58 | Texture tex; 59 | tex.m_data = findData(fileName); 60 | if (!tex.m_data) 61 | { 62 | tex.m_data = createData(fileName); 63 | tex.m_data->image = importImage(fileName); 64 | } 65 | return tex; 66 | } 67 | 68 | //------------------------------------------------------------------------ 69 | 70 | void Texture::set(const Texture& other) 71 | { 72 | Data* old = m_data; 73 | m_data = other.m_data; 74 | if (m_data) 75 | referData(m_data); 76 | if (old) 77 | unreferData(old); 78 | } 79 | 80 | //------------------------------------------------------------------------ 81 | 82 | GLuint Texture::getGLTexture(ImageFormat::ID desiredFormat, bool generateMipmaps) const 83 | { 84 | if (!m_data) 85 | return 0; 86 | if (m_data->glTexture == 0 && m_data->image) 87 | m_data->glTexture = m_data->image->createGLTexture(desiredFormat, generateMipmaps); 88 | return m_data->glTexture; 89 | } 90 | 91 | //------------------------------------------------------------------------ 92 | 93 | CUarray Texture::getCudaArray(const ImageFormat::ID desiredFormat) const 94 | { 95 | if (!m_data) 96 | return NULL; 97 | if (!m_data->cudaArray && m_data->image) 98 | m_data->cudaArray = m_data->image->createCudaArray(desiredFormat); 99 | return m_data->cudaArray; 100 | } 101 | 102 | //------------------------------------------------------------------------ 103 | 104 | Texture Texture::getMipLevel(int level) const 105 | { 106 | const Texture* curr = this; 107 | for (int i = 0; i < level && curr->exists(); i++) 108 | { 109 | if (!curr->m_data->nextMip) 110 | { 111 | Image* scaled = curr->m_data->image->downscale2x(); 112 | if (!scaled) 113 | break; 114 | curr->m_data->nextMip = new Texture(scaled); 115 | } 116 | curr = curr->m_data->nextMip; 117 | } 118 | return *curr; 119 | } 120 | 121 | //------------------------------------------------------------------------ 122 | 123 | Texture::Data* Texture::findData(const String& id) 124 | { 125 | Data** found = (s_hash) ? s_hash->search(id) : NULL; 126 | if (!found) 127 | return NULL; 128 | 129 | referData(*found); 130 | return *found; 131 | } 132 | 133 | //------------------------------------------------------------------------ 134 | 135 | Texture::Data* Texture::createData(const String& id) 136 | { 137 | Data* data = new Data; 138 | data->id = id; 139 | data->refCount = 1; 140 | data->isInHash = false; 141 | data->image = NULL; 142 | data->glTexture = 0; 143 | data->cudaArray = NULL; 144 | data->nextMip = NULL; 145 | 146 | // Update hash. 147 | 148 | if (id.getLength()) 149 | { 150 | if (!s_hash) 151 | s_hash = new Hash; 152 | 153 | Data** old = s_hash->search(id); 154 | if (old) 155 | { 156 | s_hash->remove(id); 157 | (*old)->isInHash = false; 158 | } 159 | 160 | s_hash->add(id, data); 161 | data->isInHash = true; 162 | } 163 | return data; 164 | } 165 | 166 | //------------------------------------------------------------------------ 167 | 168 | void Texture::referData(Data* data) 169 | { 170 | FW_ASSERT(data); 171 | data->refCountLock.enter(); 172 | data->refCount++; 173 | data->refCountLock.leave(); 174 | } 175 | 176 | //------------------------------------------------------------------------ 177 | 178 | void Texture::unreferData(Data* data) 179 | { 180 | FW_ASSERT(data); 181 | 182 | // Decrease refcount. 183 | 184 | data->refCountLock.enter(); 185 | int refCount = --data->refCount; 186 | data->refCountLock.leave(); 187 | 188 | if (refCount != 0) 189 | return; 190 | 191 | // Remove from hash. 192 | 193 | if (data->isInHash) 194 | { 195 | FW_ASSERT(s_hash); 196 | s_hash->remove(data->id); 197 | if (!s_hash->getSize()) 198 | { 199 | delete s_hash; 200 | s_hash = NULL; 201 | } 202 | } 203 | 204 | // Delete data. 205 | 206 | if (data->glTexture != 0) 207 | glDeleteTextures(1, &data->glTexture); 208 | 209 | if (data->cudaArray) 210 | CudaModule::checkError("cuArrayDestroy", cuArrayDestroy(data->cudaArray)); 211 | 212 | delete data->image; 213 | delete data->nextMip; 214 | delete data; 215 | } 216 | 217 | //------------------------------------------------------------------------ 218 | -------------------------------------------------------------------------------- /src/framework/3d/Texture.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #pragma once 29 | #include "gui/Image.hpp" 30 | #include "base/Hash.hpp" 31 | #include "base/Thread.hpp" 32 | 33 | namespace FW 34 | { 35 | //------------------------------------------------------------------------ 36 | 37 | class Texture 38 | { 39 | private: 40 | struct Data 41 | { 42 | S32 refCount; 43 | Spinlock refCountLock; 44 | 45 | String id; 46 | bool isInHash; 47 | Image* image; 48 | GLuint glTexture; 49 | CUarray cudaArray; 50 | Texture* nextMip; 51 | }; 52 | 53 | public: 54 | Texture (void) : m_data(NULL) {} 55 | Texture (const Texture& other) : m_data(NULL) { set(other); } 56 | Texture (Image* image, const String& id = ""); // takes ownership of the image 57 | ~Texture (void) { if (m_data) unreferData(m_data); } 58 | 59 | static Texture find (const String& id); 60 | static Texture import (const String& fileName); 61 | 62 | bool exists (void) const { return (m_data && m_data->image && m_data->image->getSize().min() > 0); } 63 | String getID (void) const { return (m_data) ? m_data->id : ""; } 64 | const Image* getImage (void) const { return (m_data) ? m_data->image : NULL; } 65 | Vec2i getSize (void) const { return (exists()) ? getImage()->getSize() : 0; } 66 | 67 | void clear (void) { if (m_data) unreferData(m_data); m_data = NULL; } 68 | void set (const Texture& other); 69 | 70 | GLuint getGLTexture (const ImageFormat::ID desiredFormat = ImageFormat::ID_Max, bool generateMipmaps = true) const; 71 | CUarray getCudaArray (const ImageFormat::ID desiredFormat = ImageFormat::ID_Max) const; 72 | Texture getMipLevel (int level) const; 73 | 74 | Texture& operator= (const Texture& other) { set(other); return *this; } 75 | bool operator== (const Texture& other) const { return (m_data == other.m_data); } 76 | bool operator!= (const Texture& other) const { return (m_data != other.m_data); } 77 | 78 | private: 79 | static Data* findData (const String& id); 80 | static Data* createData (const String& id); 81 | static void referData (Data* data); 82 | static void unreferData (Data* data); 83 | 84 | private: 85 | static Hash* s_hash; 86 | 87 | Data* m_data; 88 | }; 89 | 90 | //------------------------------------------------------------------------ 91 | } 92 | -------------------------------------------------------------------------------- /src/framework/3d/TextureAtlas.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #pragma once 29 | #include "3d/Texture.hpp" 30 | 31 | namespace FW 32 | { 33 | //------------------------------------------------------------------------ 34 | 35 | class TextureAtlas 36 | { 37 | private: 38 | struct Item 39 | { 40 | Texture texture; 41 | S32 border; 42 | bool wrap; 43 | Vec2i size; 44 | Vec2i pos; 45 | }; 46 | 47 | public: 48 | TextureAtlas (const ImageFormat& format = ImageFormat::ABGR_8888); 49 | ~TextureAtlas (void); 50 | 51 | void clear (void); 52 | bool addTexture (const Texture& tex, int border = 1, bool wrap = true); 53 | 54 | Vec2i getAtlasSize (void) { validate(); return m_atlasSize; } 55 | Vec2i getTexturePos (const Texture& tex); 56 | const Texture& getAtlasTexture (void) { validate(); return m_atlasTexture; } 57 | 58 | private: 59 | TextureAtlas (const TextureAtlas&); // forbidden 60 | TextureAtlas& operator= (const TextureAtlas&); // forbidden 61 | 62 | private: 63 | void validate (void); 64 | void layoutItems (void); 65 | void createAtlas (void); 66 | 67 | private: 68 | ImageFormat m_format; 69 | Array m_items; 70 | Hash m_itemHash; 71 | 72 | Vec2i m_atlasSize; 73 | Texture m_atlasTexture; 74 | }; 75 | 76 | //------------------------------------------------------------------------ 77 | } 78 | -------------------------------------------------------------------------------- /src/framework/base/Array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #include "base/Array.hpp" 29 | 30 | using namespace FW; 31 | 32 | //------------------------------------------------------------------------ 33 | -------------------------------------------------------------------------------- /src/framework/base/BinaryHeap.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #include "base/BinaryHeap.hpp" 29 | 30 | using namespace FW; 31 | 32 | //------------------------------------------------------------------------ 33 | -------------------------------------------------------------------------------- /src/framework/base/Deque.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #include "base/Deque.hpp" 29 | 30 | using namespace FW; 31 | 32 | //------------------------------------------------------------------------ 33 | -------------------------------------------------------------------------------- /src/framework/base/Hash.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #include "base/Hash.hpp" 29 | 30 | using namespace FW; 31 | 32 | //------------------------------------------------------------------------ 33 | 34 | U32 FW::hashBuffer(const void* ptr, int size) 35 | { 36 | FW_ASSERT(size >= 0); 37 | FW_ASSERT(ptr || !size); 38 | 39 | if ((((S32)(UPTR)ptr | size) & 3) == 0) 40 | return hashBufferAlign(ptr, size); 41 | 42 | const U8* src = (const U8*)ptr; 43 | U32 a = FW_HASH_MAGIC; 44 | U32 b = FW_HASH_MAGIC; 45 | U32 c = FW_HASH_MAGIC; 46 | 47 | while (size >= 12) 48 | { 49 | a += src[0] + (src[1] << 8) + (src[2] << 16) + (src[3] << 24); 50 | b += src[4] + (src[5] << 8) + (src[6] << 16) + (src[7] << 24); 51 | c += src[8] + (src[9] << 8) + (src[10] << 16) + (src[11] << 24); 52 | FW_JENKINS_MIX(a, b, c); 53 | src += 12; 54 | size -= 12; 55 | } 56 | 57 | switch (size) 58 | { 59 | case 11: c += src[10] << 16; 60 | case 10: c += src[9] << 8; 61 | case 9: c += src[8]; 62 | case 8: b += src[7] << 24; 63 | case 7: b += src[6] << 16; 64 | case 6: b += src[5] << 8; 65 | case 5: b += src[4]; 66 | case 4: a += src[3] << 24; 67 | case 3: a += src[2] << 16; 68 | case 2: a += src[1] << 8; 69 | case 1: a += src[0]; 70 | case 0: break; 71 | } 72 | 73 | c += size; 74 | FW_JENKINS_MIX(a, b, c); 75 | return c; 76 | } 77 | 78 | //------------------------------------------------------------------------ 79 | 80 | U32 FW::hashBufferAlign(const void* ptr, int size) 81 | { 82 | FW_ASSERT(size >= 0); 83 | FW_ASSERT(ptr || !size); 84 | FW_ASSERT(((UPTR)ptr & 3) == 0); 85 | FW_ASSERT((size & 3) == 0); 86 | 87 | const U32* src = (const U32*)ptr; 88 | U32 a = FW_HASH_MAGIC; 89 | U32 b = FW_HASH_MAGIC; 90 | U32 c = FW_HASH_MAGIC; 91 | 92 | while (size >= 12) 93 | { 94 | a += src[0]; 95 | b += src[1]; 96 | c += src[2]; 97 | FW_JENKINS_MIX(a, b, c); 98 | src += 3; 99 | size -= 12; 100 | } 101 | 102 | switch (size) 103 | { 104 | case 8: b += src[1]; 105 | case 4: a += src[0]; 106 | case 0: break; 107 | } 108 | 109 | c += size; 110 | FW_JENKINS_MIX(a, b, c); 111 | return c; 112 | } 113 | 114 | //------------------------------------------------------------------------ 115 | -------------------------------------------------------------------------------- /src/framework/base/Main.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #include "base/Main.hpp" 29 | #include "base/DLLImports.hpp" 30 | #include "base/Thread.hpp" 31 | #include "gui/Window.hpp" 32 | #include "gpu/GLContext.hpp" 33 | #include "gpu/CudaModule.hpp" 34 | #include "gpu/CudaCompiler.hpp" 35 | 36 | #include 37 | #include 38 | 39 | using namespace FW; 40 | 41 | //------------------------------------------------------------------------ 42 | 43 | int FW::argc = 0; 44 | char** FW::argv = NULL; 45 | int FW::exitCode = 0; 46 | 47 | static bool s_enableLeakCheck = true; 48 | 49 | //------------------------------------------------------------------------ 50 | 51 | int main(int argc, char* argv[]) 52 | { 53 | // Store arguments. 54 | 55 | FW::argc = argc; 56 | FW::argv = argv; 57 | 58 | // Force the main thread to run on a single core. 59 | 60 | SetThreadAffinityMask(GetCurrentThread(), 1); 61 | 62 | // Initialize CRTDBG. 63 | 64 | #if FW_DEBUG 65 | int flag = 0; 66 | flag |= _CRTDBG_ALLOC_MEM_DF; // use allocation guards 67 | // flag |= _CRTDBG_CHECK_ALWAYS_DF; // check whole memory on each alloc 68 | // flag |= _CRTDBG_DELAY_FREE_MEM_DF; // keep freed memory and check that it isn't written 69 | _CrtSetDbgFlag(flag); 70 | 71 | // _CrtSetBreakAlloc(64); 72 | _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); 73 | _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); 74 | #endif 75 | 76 | // Initialize the application. 77 | 78 | Thread::getCurrent(); 79 | FW::init(); 80 | failIfError(); 81 | 82 | // Message loop. 83 | 84 | while (Window::getNumOpen()) 85 | { 86 | // Wait for a message. 87 | 88 | MSG msg; 89 | if (!PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) 90 | { 91 | Window::realizeAll(); 92 | GetMessage(&msg, NULL, 0, 0); 93 | } 94 | 95 | // Process the message. 96 | 97 | TranslateMessage(&msg); 98 | DispatchMessage(&msg); 99 | 100 | // Nesting level was not restored => something fishy is going on. 101 | 102 | if (incNestingLevel(0) != 0) 103 | { 104 | fail( 105 | "Unhandled access violation detected!\n" 106 | "\n" 107 | "To get a stack trace, try the following:\n" 108 | "- Select \"Debug / Exceptions...\" in Visual Studio.\n" 109 | "- Expand the \"Win32 Exceptions\" category.\n" 110 | "- Check the \"Thrown\" box for \"Access violation\".\n" 111 | "- Re-run the application under debugger (F5)."); 112 | } 113 | } 114 | 115 | // Clean up. 116 | 117 | failIfError(); 118 | CudaCompiler::staticDeinit(); 119 | CudaModule::staticDeinit(); 120 | GLContext::staticDeinit(); 121 | Window::staticDeinit(); 122 | deinitDLLImports(); 123 | profileEnd(false); 124 | failIfError(); 125 | 126 | while (hasLogFile()) 127 | popLogFile(); 128 | 129 | delete Thread::getCurrent(); 130 | 131 | // Dump memory leaks. 132 | 133 | #if FW_DEBUG 134 | if (s_enableLeakCheck && _CrtDumpMemoryLeaks()) 135 | { 136 | printf("Press any key to continue . . . "); 137 | _getch(); 138 | printf("\n"); 139 | } 140 | #endif 141 | 142 | return exitCode; 143 | } 144 | 145 | //------------------------------------------------------------------------ 146 | 147 | int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) 148 | { 149 | FW_UNREF(hInstance); 150 | FW_UNREF(hPrevInstance); 151 | FW_UNREF(lpCmdLine); // TODO: Parse this to argc/argv. 152 | FW_UNREF(nShowCmd); 153 | return main(0, NULL); 154 | } 155 | 156 | //------------------------------------------------------------------------ 157 | 158 | void FW::disableLeakCheck(void) 159 | { 160 | s_enableLeakCheck = false; 161 | } 162 | 163 | //------------------------------------------------------------------------ 164 | -------------------------------------------------------------------------------- /src/framework/base/Main.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #pragma once 29 | #include "base/Defs.hpp" 30 | 31 | namespace FW 32 | { 33 | //------------------------------------------------------------------------ 34 | 35 | extern int argc; 36 | extern char** argv; 37 | extern int exitCode; 38 | 39 | //------------------------------------------------------------------------ 40 | 41 | void init (void); // Main entry point, defined by the application. 42 | 43 | void disableLeakCheck (void); // Call to disable memory leak check at application exit in debug build. 44 | 45 | //------------------------------------------------------------------------ 46 | } 47 | -------------------------------------------------------------------------------- /src/framework/base/Math.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #include "base/Math.hpp" 29 | 30 | using namespace FW; 31 | 32 | //------------------------------------------------------------------------ 33 | 34 | Vec4f Vec4f::fromABGR(U32 abgr) 35 | { 36 | return Vec4f( 37 | (F32)(abgr & 0xFF) * (1.0f / 255.0f), 38 | (F32)((abgr >> 8) & 0xFF) * (1.0f / 255.0f), 39 | (F32)((abgr >> 16) & 0xFF) * (1.0f / 255.0f), 40 | (F32)(abgr >> 24) * (1.0f / 255.0f)); 41 | } 42 | 43 | //------------------------------------------------------------------------ 44 | 45 | U32 Vec4f::toABGR(void) const 46 | { 47 | return 48 | ((((U32)(((U64)(FW::clamp(x, 0.0f, 1.0f) * exp2(56)) * 255) >> 55) + 1) >> 1) << 0) | 49 | ((((U32)(((U64)(FW::clamp(y, 0.0f, 1.0f) * exp2(56)) * 255) >> 55) + 1) >> 1) << 8) | 50 | ((((U32)(((U64)(FW::clamp(z, 0.0f, 1.0f) * exp2(56)) * 255) >> 55) + 1) >> 1) << 16) | 51 | ((((U32)(((U64)(FW::clamp(w, 0.0f, 1.0f) * exp2(56)) * 255) >> 55) + 1) >> 1) << 24); 52 | } 53 | 54 | //------------------------------------------------------------------------ 55 | 56 | Mat3f Mat4f::getXYZ(void) const 57 | { 58 | Mat3f r; 59 | for (int i = 0; i < 3; i++) 60 | r.col(i) = Vec4f(col(i)).getXYZ(); 61 | return r; 62 | } 63 | 64 | //------------------------------------------------------------------------ 65 | 66 | Mat4f Mat4f::fitToView(const Vec2f& pos, const Vec2f& size, const Vec2f& viewSize) 67 | { 68 | FW_ASSERT(size.x != 0.0f && size.y != 0.0f); 69 | FW_ASSERT(viewSize.x != 0.0f && viewSize.y != 0.0f); 70 | 71 | return 72 | Mat4f::scale(Vec3f(Vec2f(2.0f) / viewSize, 1.0f)) * 73 | Mat4f::scale(Vec3f((viewSize / size).min(), 1.0f)) * 74 | Mat4f::translate(Vec3f(-pos - size * 0.5f, 0.0f)); 75 | } 76 | 77 | //------------------------------------------------------------------------ 78 | 79 | Mat4f Mat4f::perspective(F32 fov, F32 nearDist, F32 farDist) 80 | { 81 | // Camera points towards -z. 0 < near < far. 82 | // Matrix maps z range [-near, -far] to [-1, 1], after homogeneous division. 83 | F32 f = rcp(tan(fov * FW_PI / 360.0f)); 84 | F32 d = rcp(nearDist - farDist); 85 | 86 | Mat4f r; 87 | r.setRow(0, Vec4f( f, 0.0f, 0.0f, 0.0f )); 88 | r.setRow(1, Vec4f( 0.0f, f, 0.0f, 0.0f )); 89 | r.setRow(2, Vec4f( 0.0f, 0.0f, (nearDist + farDist) * d, 2.0f * nearDist * farDist * d )); 90 | r.setRow(3, Vec4f( 0.0f, 0.0f, -1.0f, 0.0f )); 91 | return r; 92 | } 93 | 94 | //------------------------------------------------------------------------ 95 | 96 | Mat3f Mat3f::rotation(const Vec3f& axis, F32 angle) 97 | { 98 | Mat3f R; 99 | F32 cosa = cosf(angle); 100 | F32 sina = sinf(angle); 101 | R(0,0) = cosa + sqr(axis.x)*(1.0f-cosa); R(0,1) = axis.x*axis.y*(1.0f-cosa) - axis.z*sina; R(0,2) = axis.x*axis.z*(1.0f-cosa) + axis.y*sina; 102 | R(1,0) = axis.x*axis.y*(1.0f-cosa) + axis.z*sina; R(1,1) = cosa + sqr(axis.y)*(1.0f-cosa); R(1,2) = axis.y*axis.z*(1.0f-cosa) - axis.x*sina; 103 | R(2,0) = axis.z*axis.x*(1.0f-cosa) - axis.y*sina; R(2,1) = axis.z*axis.y*(1.0f-cosa) + axis.x*sina; R(2,2) = cosa + sqr(axis.z)*(1.0f-cosa); 104 | return R; 105 | } 106 | 107 | Mat3d Mat3d::rotation(const Vec3d& axis, F64 angle) 108 | { 109 | Mat3d R; 110 | F64 cosa = cos(angle); 111 | F64 sina = sin(angle); 112 | R(0,0) = cosa + sqr(axis.x)*(1.0-cosa); R(0,1) = axis.x*axis.y*(1.0-cosa) - axis.z*sina; R(0,2) = axis.x*axis.z*(1.0-cosa) + axis.y*sina; 113 | R(1,0) = axis.x*axis.y*(1.0-cosa) + axis.z*sina; R(1,1) = cosa + sqr(axis.y)*(1.0-cosa); R(1,2) = axis.y*axis.z*(1.0-cosa) - axis.x*sina; 114 | R(2,0) = axis.z*axis.x*(1.0-cosa) - axis.y*sina; R(2,1) = axis.z*axis.y*(1.0-cosa) + axis.x*sina; R(2,2) = cosa + sqr(axis.z)*(1.0-cosa); 115 | return R; 116 | } 117 | -------------------------------------------------------------------------------- /src/framework/base/MulticoreLauncher.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #pragma once 29 | #include "base/Thread.hpp" 30 | #include "base/Deque.hpp" 31 | 32 | namespace FW 33 | { 34 | //------------------------------------------------------------------------ 35 | // Launch a batch of tasks and wait: 36 | // MulticoreLauncher().push(myTaskFunc, &myTaskData, 0, numTasks); 37 | // 38 | // Display progress indicator: 39 | // MulticoreLauncher().push(myTaskFunc, &myTaskData, 0, numTasks).popAll("Processing..."); 40 | // 41 | // Grab results: 42 | // { 43 | // MulticoreLauncher launcher; 44 | // launcher.push(...); 45 | // while (launcher.getNumTasks()) 46 | // doSomething(launcher.pop().result); 47 | // } 48 | // 49 | // Asynchronous operation: 50 | // { 51 | // MulticoreLauncher launcher; 52 | // launcher.push(...); 53 | // while (launcher.getNumTasks()) 54 | // { 55 | // spendSomeIdleTime(); 56 | // while (launcher.getNumFinished()) 57 | // doSomething(launcher.pop().result); 58 | // } 59 | // } 60 | // 61 | // Create dependent tasks dynamically: 62 | // 63 | // void myTaskFunc(MulticoreLauncher::Task& task) 64 | // { 65 | // ... 66 | // task.launcher->push(...); 67 | // ... 68 | // } 69 | // 70 | // Per-thread temporary data: 71 | // 72 | // void myDeinitFunc(void* threadData) 73 | // { 74 | // ... 75 | // } 76 | // 77 | // void myTaskFunc(MulticoreLauncher::Task& task) 78 | // { 79 | // void* threadData = Thread::getCurrent()->getUserData("myID"); 80 | // if (!threadData) 81 | // { 82 | // threadData = ...; 83 | // Thread::getCurrent()->setUserData("myID", threadData, myDeinitFunc); 84 | // } 85 | // ... 86 | // } 87 | //------------------------------------------------------------------------ 88 | 89 | class MulticoreLauncher 90 | { 91 | public: 92 | struct Task; 93 | typedef void (*TaskFunc)(Task& task); 94 | 95 | struct Task 96 | { 97 | MulticoreLauncher* launcher; 98 | TaskFunc func; 99 | void* data; 100 | int idx; 101 | void* result; // Potentially written by TaskFunc. 102 | }; 103 | 104 | public: 105 | MulticoreLauncher (void); 106 | ~MulticoreLauncher (void); 107 | 108 | MulticoreLauncher& push (TaskFunc func, void* data, int firstIdx = 0, int numTasks = 1); 109 | Task pop (void); // Blocks until at least one task has finished. 110 | 111 | int getNumTasks (void) const; // Tasks that have been pushed but not popped. 112 | int getNumFinished (void) const; // Tasks that can be popped without blocking. 113 | 114 | void popAll (void) { while (getNumTasks()) pop(); } 115 | void popAll (const String& progressMessage); 116 | 117 | static int getNumCores (void); 118 | static void setNumThreads (int numThreads); 119 | 120 | private: 121 | static void applyNumThreads (void); 122 | static void threadFunc (void* param); 123 | 124 | private: 125 | MulticoreLauncher (const MulticoreLauncher&); // forbidden 126 | MulticoreLauncher& operator= (const MulticoreLauncher&); // forbidden 127 | 128 | private: 129 | static Spinlock s_lock; 130 | static S32 s_numInstances; 131 | static S32 s_desiredThreads; 132 | 133 | static Monitor* s_monitor; 134 | static Deque s_pending; 135 | static S32 s_numThreads; 136 | 137 | S32 m_numTasks; 138 | Deque m_finished; 139 | }; 140 | 141 | //------------------------------------------------------------------------ 142 | } 143 | -------------------------------------------------------------------------------- /src/framework/base/Random.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #include "base/Random.hpp" 29 | #include "base/DLLImports.hpp" 30 | 31 | using namespace FW; 32 | 33 | //------------------------------------------------------------------------ 34 | 35 | #define FW_USE_MERSENNE_TWISTER 0 36 | 37 | //------------------------------------------------------------------------ 38 | // Mersenne Twister 39 | //------------------------------------------------------------------------ 40 | 41 | #if FW_USE_MERSENNE_TWISTER 42 | extern "C" 43 | { 44 | #include "3rdparty/mt19937ar/mt19937ar_ctx.h" 45 | } 46 | #endif 47 | 48 | //------------------------------------------------------------------------ 49 | // RANROT-A 50 | //------------------------------------------------------------------------ 51 | 52 | class RanrotA 53 | { 54 | private: 55 | S32 p1; 56 | S32 p2; 57 | U32 buffer[11]; 58 | 59 | public: 60 | void reset(U32 seed) 61 | { 62 | if (seed == 0) 63 | seed--; 64 | 65 | for (int i = 0; i < (int)FW_ARRAY_SIZE(buffer); i++) 66 | { 67 | seed ^= seed << 13; 68 | seed ^= seed >> 17; 69 | seed ^= seed << 5; 70 | buffer[i] = seed; 71 | } 72 | 73 | p1 = 0; 74 | p2 = 7; 75 | 76 | for (int i = 0; i < (int)FW_ARRAY_SIZE(buffer); i++) 77 | get(); 78 | } 79 | 80 | U32 get(void) 81 | { 82 | U32 x = buffer[p1] + buffer[p2]; 83 | x = (x << 13) | (x >> 19); 84 | buffer[p1] = x; 85 | 86 | p1--; 87 | p1 += (p1 >> 31) & FW_ARRAY_SIZE(buffer); 88 | p2--; 89 | p2 += (p2 >> 31) & FW_ARRAY_SIZE(buffer); 90 | return x; 91 | } 92 | }; 93 | 94 | //------------------------------------------------------------------------ 95 | // Common functionality. 96 | //------------------------------------------------------------------------ 97 | 98 | void Random::reset(void) 99 | { 100 | LARGE_INTEGER ticks; 101 | if (!QueryPerformanceCounter(&ticks)) 102 | failWin32Error("QueryPerformanceCounter"); 103 | reset(ticks.LowPart); 104 | } 105 | 106 | //------------------------------------------------------------------------ 107 | 108 | void Random::reset(U32 seed) 109 | { 110 | resetImpl(seed); 111 | 112 | m_normalF32Valid = false; 113 | m_normalF32 = 0.0f; 114 | m_normalF64Valid = false; 115 | m_normalF64 = 0.0; 116 | } 117 | 118 | //------------------------------------------------------------------------ 119 | 120 | void Random::reset(const Random& other) 121 | { 122 | assignImpl(other); 123 | 124 | m_normalF32Valid = other.m_normalF32Valid; 125 | m_normalF32 = other.m_normalF32; 126 | m_normalF64Valid = other.m_normalF64Valid; 127 | m_normalF64 = other.m_normalF64; 128 | } 129 | 130 | //------------------------------------------------------------------------ 131 | 132 | int Random::read(void* ptr, int size) 133 | { 134 | for (int i = 0; i < size; i++) 135 | ((U8*)ptr)[i] = (U8)getU32(); 136 | return max(size, 0); 137 | } 138 | 139 | //------------------------------------------------------------------------ 140 | 141 | F32 Random::getF32Normal(void) 142 | { 143 | m_normalF32Valid = (!m_normalF32Valid); 144 | if (!m_normalF32Valid) 145 | return m_normalF32; 146 | 147 | F32 a, b, c; 148 | do 149 | { 150 | a = (F32)getU32() * (2.0f / 4294967296.0f) + (1.0f / 4294967296.0f - 1.0f); 151 | b = (F32)getU32() * (2.0f / 4294967296.0f) + (1.0f / 4294967296.0f - 1.0f); 152 | c = a * a + b * b; 153 | } 154 | while (c >= 1.0f); 155 | 156 | c = sqrt(-2.0f * log(c) / c); 157 | m_normalF32 = b * c; 158 | return a * c; 159 | } 160 | 161 | //------------------------------------------------------------------------ 162 | 163 | F64 Random::getF64Normal(void) 164 | { 165 | m_normalF64Valid = (!m_normalF64Valid); 166 | if (!m_normalF64Valid) 167 | return m_normalF64; 168 | 169 | F64 a, b, c; 170 | do 171 | { 172 | a = (F64)getU64() * (2.0 / 18446744073709551616.0) + (1.0 / 18446744073709551616.0 - 1.0); 173 | b = (F64)getU64() * (2.0 / 18446744073709551616.0) + (1.0 / 18446744073709551616.0 - 1.0); 174 | c = a * a + b * b; 175 | } 176 | while (c >= 1.0); 177 | 178 | c = sqrt(-2.0 * log(c) / c); 179 | m_normalF64 = b * c; 180 | return a * c; 181 | } 182 | 183 | //------------------------------------------------------------------------ 184 | // Implementation wrappers. 185 | //------------------------------------------------------------------------ 186 | 187 | void Random::initImpl(void) 188 | { 189 | #if FW_USE_MERSENNE_TWISTER 190 | m_impl = (void*)new genrand; 191 | #else 192 | m_impl = (void*)new RanrotA; 193 | #endif 194 | } 195 | 196 | //------------------------------------------------------------------------ 197 | 198 | void Random::deinitImpl(void) 199 | { 200 | #if FW_USE_MERSENNE_TWISTER 201 | delete (genrand*)m_impl; 202 | #else 203 | delete (RanrotA*)m_impl; 204 | #endif 205 | } 206 | 207 | //------------------------------------------------------------------------ 208 | 209 | void Random::resetImpl(U32 seed) 210 | { 211 | #if FW_USE_MERSENNE_TWISTER 212 | init_genrand((genrand*)m_impl, seed); 213 | #else 214 | ((RanrotA*)m_impl)->reset(seed); 215 | #endif 216 | } 217 | 218 | //------------------------------------------------------------------------ 219 | 220 | void Random::assignImpl(const Random& other) 221 | { 222 | #if FW_USE_MERSENNE_TWISTER 223 | *(genrand*)m_impl = *(const genrand*)other.m_impl; 224 | #else 225 | *(RanrotA*)m_impl = *(const RanrotA*)other.m_impl; 226 | #endif 227 | } 228 | 229 | //------------------------------------------------------------------------ 230 | 231 | U32 Random::getImpl(void) 232 | { 233 | #if FW_USE_MERSENNE_TWISTER 234 | return genrand_int32((genrand*)m_impl); 235 | #else 236 | return ((RanrotA*)m_impl)->get(); 237 | #endif 238 | } 239 | 240 | //------------------------------------------------------------------------ 241 | -------------------------------------------------------------------------------- /src/framework/base/Random.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #pragma once 29 | #include "base/Math.hpp" 30 | #include "io/Stream.hpp" 31 | 32 | namespace FW 33 | { 34 | //------------------------------------------------------------------------ 35 | 36 | class Random : public InputStream 37 | { 38 | public: 39 | Random (void) { initImpl(); reset(); } 40 | explicit Random (U32 seed) { initImpl(); reset(seed); } 41 | Random (const Random& other) { initImpl(); reset(other); } 42 | ~Random (void) { deinitImpl(); } 43 | 44 | void reset (void); 45 | void reset (U32 seed); 46 | void reset (const Random& other); 47 | 48 | virtual int read (void* ptr, int size); 49 | Random& operator= (const Random& other) { reset(other); return *this; } 50 | 51 | U32 getU32 (void) { return getImpl(); } 52 | U32 getU32 (U32 hi) { return (hi == 0) ? 0 : (getU32() % hi); } 53 | U32 getU32 (U32 lo, U32 hi) { return (hi <= lo) ? lo : (getU32() % (hi - lo) + lo); } 54 | S32 getS32 (void) { return getImpl(); } 55 | S32 getS32 (S32 hi) { return (hi <= 0) ? 0 : (getU32() % (U32)hi); } 56 | S32 getS32 (S32 lo, S32 hi) { return (hi <= lo) ? lo : (getU32() % (U32)(hi - lo) + lo); } 57 | F32 getF32 (void) { return (F32)getU32() * (1.0f / 4294967296.0f); } 58 | F32 getF32 (F32 lo, F32 hi) { return getF32() * (hi - lo) + lo; } 59 | U64 getU64 (void) { return getU32() | ((U64)getU32() << 32); } 60 | U64 getU64 (U64 hi) { return (hi == 0) ? 0 : (getU64() % hi); } 61 | U64 getU64 (U64 lo, U64 hi) { return (hi <= lo) ? lo : (getU64() % (hi - lo) + lo); } 62 | S64 getS64 (S64 hi) { return (hi <= 0) ? 0 : (getU64() % (U64)hi); } 63 | S64 getS64 (S64 lo, S64 hi) { return (hi <= lo) ? lo : (getU64() % (U64)(hi - lo) + lo); } 64 | F64 getF64 (void) { return (F64)getU64() * (1.0 / 18446744073709551616.0); } 65 | F64 getF64 (F64 lo, F64 hi) { return getF64() * (hi - lo) + lo; } 66 | 67 | F32 getF32Exp (void) { return -log(getF32() + (1.0f / 4294967296.0f)); } 68 | F32 getF32Exp (F32 deviation) { return getF32Exp() * deviation; } 69 | F32 getF32Exp (F32 mean, F32 deviation) { return getF32Exp() * deviation + mean; } 70 | F64 getF64Exp (void) { return -log(getF64() + (1.0 / 18446744073709551616.0)); } 71 | F64 getF64Exp (F64 deviation) { return getF64Exp() * deviation; } 72 | F64 getF64Exp (F64 mean, F64 deviation) { return getF64Exp() * deviation + mean; } 73 | 74 | F32 getF32Normal (void); 75 | F32 getF32Normal (F32 deviation) { return getF32Normal() * deviation; } 76 | F32 getF32Normal (F32 mean, F32 deviation) { return getF32Normal() * deviation + mean; } 77 | F64 getF64Normal (void); 78 | F64 getF64Normal (F64 deviation) { return getF64Normal() * deviation; } 79 | F64 getF64Normal (F64 mean, F64 deviation) { return getF64Normal() * deviation + mean; } 80 | 81 | Vec2f getVec2f (void) { return Vec2f(getF32(), getF32()); } 82 | Vec2f getVec2f (F32 lo, F32 hi) { return Vec2f(getF32(lo, hi), getF32(lo, hi)); } 83 | Vec3f getVec3f (void) { return Vec3f(getF32(), getF32(), getF32()); } 84 | Vec3f getVec3f (F32 lo, F32 hi) { return Vec3f(getF32(lo, hi), getF32(lo, hi), getF32(lo, hi)); } 85 | Vec4f getVec4f (void) { return Vec4f(getF32(), getF32(), getF32(), getF32()); } 86 | Vec4f getVec4f (F32 lo, F32 hi) { return Vec4f(getF32(lo, hi), getF32(lo, hi), getF32(lo, hi), getF32(lo, hi)); } 87 | 88 | Vec2d getVec2d (void) { return Vec2d(getF64(), getF64()); } 89 | Vec2d getVec2d (F64 lo, F64 hi) { return Vec2d(getF64(lo, hi), getF64(lo, hi)); } 90 | Vec3d getVec3d (void) { return Vec3d(getF64(), getF64(), getF64()); } 91 | Vec3d getVec3d (F64 lo, F64 hi) { return Vec3d(getF64(lo, hi), getF64(lo, hi), getF64(lo, hi)); } 92 | Vec4d getVec4d (void) { return Vec4d(getF64(), getF64(), getF64(), getF64()); } 93 | Vec4d getVec4d (F64 lo, F64 hi) { return Vec4d(getF64(lo, hi), getF64(lo, hi), getF64(lo, hi), getF64(lo, hi)); } 94 | 95 | private: 96 | void initImpl (void); 97 | void deinitImpl (void); 98 | void resetImpl (U32 seed); 99 | void assignImpl (const Random& other); 100 | U32 getImpl (void); 101 | 102 | private: 103 | void* m_impl; 104 | bool m_normalF32Valid; 105 | F32 m_normalF32; 106 | bool m_normalF64Valid; 107 | F64 m_normalF64; 108 | }; 109 | 110 | //------------------------------------------------------------------------ 111 | } 112 | -------------------------------------------------------------------------------- /src/framework/base/String.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #pragma once 29 | #include "base/Array.hpp" 30 | 31 | #include 32 | 33 | namespace FW 34 | { 35 | //------------------------------------------------------------------------ 36 | 37 | class String 38 | { 39 | public: 40 | String (void) {} 41 | String (char chr) { set(chr); } 42 | String (const char* chars) { set(chars); } 43 | String (const char* start, const char* end ) { set(start, end); } 44 | String (const String& other) { set(other); } 45 | String (S32 value) { setf("%d", value); } 46 | String (F64 value) { setf("%g", value); } 47 | ~String (void) {} 48 | 49 | int getLength (void) const { return max(m_chars.getSize() - 1, 0); } 50 | char getChar (int idx) const { FW_ASSERT(idx < getLength()); return m_chars[idx]; } 51 | const char* getPtr (void) const { return (m_chars.getSize()) ? m_chars.getPtr() : ""; } 52 | 53 | String& reset (void) { m_chars.reset(); return *this; } 54 | String& set (char chr); 55 | String& set (const char* chars); 56 | String& set (const char* start, const char* end); 57 | String& set (const String& other) { m_chars = other.m_chars; return *this; } 58 | String& setf (const char* fmt, ...); 59 | String& setfv (const char* fmt, va_list args); 60 | 61 | String substring (int start, int end) const; 62 | String substring (int start) const { return substring(start, getLength()); } 63 | 64 | String trimStart (void) const; 65 | String trimEnd (void) const; 66 | String trim (void) const; 67 | 68 | void split (char chr, Array& pieces, bool includeEmpty = false) const; 69 | 70 | String& clear (void) { m_chars.clear(); } 71 | String& append (char chr); 72 | String& append (const char* chars); 73 | String& append (const String& other); 74 | String& appendf (const char* fmt, ...); 75 | String& appendfv (const char* fmt, va_list args); 76 | String& compact (void) { m_chars.compact(); } 77 | 78 | int indexOf (char chr) const { return m_chars.indexOf(chr); } 79 | int indexOf (char chr, int fromIdx) const { return m_chars.indexOf(chr, fromIdx); } 80 | int lastIndexOf (char chr) const { return m_chars.lastIndexOf(chr); } 81 | int lastIndexOf (char chr, int fromIdx) const { return m_chars.lastIndexOf(chr, fromIdx); } 82 | 83 | String toUpper (void) const; 84 | String toLower (void) const; 85 | bool startsWith (const String& str) const; 86 | bool endsWith (const String& str) const; 87 | 88 | String getFileName (void) const; 89 | String getDirName (void) const; 90 | 91 | char operator[] (int idx) const { return getChar(idx); } 92 | String& operator= (const String& other) { set(other); return *this; } 93 | String& operator+= (char chr) { append(chr); return *this; } 94 | String& operator+= (const String& other) { append(other); return *this; } 95 | String operator+ (char chr) const { return String(*this).append(chr); } 96 | String operator+ (const String& other) const { return String(*this).append(other); } 97 | bool operator== (const char* chars) const { return (strcmp(getPtr(), chars) == 0); } 98 | bool operator== (const String& other) const { return (strcmp(getPtr(), other.getPtr()) == 0); } 99 | bool operator!= (const char* chars) const { return (strcmp(getPtr(), chars) != 0); } 100 | bool operator!= (const String& other) const { return (strcmp(getPtr(), other.getPtr()) != 0); } 101 | bool operator< (const char* chars) const { return (strcmp(getPtr(), chars) < 0); } 102 | bool operator< (const String& other) const { return (strcmp(getPtr(), other.getPtr()) < 0); } 103 | bool operator> (const char* chars) const { return (strcmp(getPtr(), chars) > 0); } 104 | bool operator> (const String& other) const { return (strcmp(getPtr(), other.getPtr()) > 0); } 105 | bool operator>= (const char* chars) const { return (strcmp(getPtr(), chars) <= 0); } 106 | bool operator>= (const String& other) const { return (strcmp(getPtr(), other.getPtr()) <= 0); } 107 | bool operator<= (const char* chars) const { return (strcmp(getPtr(), chars) >= 0); } 108 | bool operator<= (const String& other) const { return (strcmp(getPtr(), other.getPtr()) >= 0); } 109 | 110 | private: 111 | static int strlen (const char* chars); 112 | static int strcmp (const char* a, const char* b); 113 | 114 | private: 115 | Array m_chars; 116 | }; 117 | 118 | //------------------------------------------------------------------------ 119 | 120 | String getDateString (void); 121 | 122 | bool parseSpace (const char*& ptr); 123 | bool parseChar (const char*& ptr, char chr); 124 | bool parseLiteral (const char*& ptr, const char* str); 125 | bool parseInt (const char*& ptr, S32& value); 126 | bool parseInt (const char*& ptr, S64& value); 127 | bool parseHex (const char*& ptr, U32& value); 128 | bool parseFloat (const char*& ptr, F32& value); 129 | 130 | //------------------------------------------------------------------------ 131 | } 132 | -------------------------------------------------------------------------------- /src/framework/base/Thread.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #pragma once 29 | #include "base/Hash.hpp" 30 | #include "base/DLLImports.hpp" 31 | 32 | namespace FW 33 | { 34 | //------------------------------------------------------------------------ 35 | 36 | class Spinlock 37 | { 38 | public: 39 | Spinlock (void); 40 | ~Spinlock (void); 41 | 42 | void enter (void); 43 | void leave (void); 44 | 45 | private: 46 | Spinlock (const Spinlock&); // forbidden 47 | Spinlock& operator= (const Spinlock&); // forbidden 48 | 49 | private: 50 | CRITICAL_SECTION m_critSect; 51 | }; 52 | 53 | //------------------------------------------------------------------------ 54 | 55 | class Semaphore 56 | { 57 | public: 58 | Semaphore (int initCount = 1, int maxCount = 1); 59 | ~Semaphore (void); 60 | 61 | bool acquire (int millis = -1); 62 | void release (void); 63 | 64 | private: 65 | Semaphore (const Semaphore&); // forbidden 66 | Semaphore& operator= (const Semaphore&); // forbidden 67 | 68 | private: 69 | HANDLE m_handle; 70 | }; 71 | 72 | //------------------------------------------------------------------------ 73 | 74 | class Monitor 75 | { 76 | public: 77 | Monitor (void); 78 | ~Monitor (void); 79 | 80 | void enter (void); 81 | void leave (void); 82 | void wait (void); 83 | void notify (void); 84 | void notifyAll (void); 85 | 86 | private: 87 | Monitor (const Monitor&); // forbidden 88 | Monitor& operator= (const Monitor&); // forbidden 89 | 90 | private: 91 | // Legacy implementation, works on all Windows versions. 92 | 93 | Spinlock m_lock; 94 | Semaphore m_ownerSem; 95 | Semaphore m_waitSem; 96 | Semaphore m_notifySem; 97 | volatile U32 m_ownerThread; 98 | volatile S32 m_enterCount; 99 | volatile S32 m_waitCount; 100 | 101 | // Efficient implementation, requires Windows Vista. 102 | 103 | CRITICAL_SECTION m_mutex; 104 | CONDITION_VARIABLE m_condition; 105 | }; 106 | 107 | //------------------------------------------------------------------------ 108 | 109 | class Thread 110 | { 111 | public: 112 | typedef void (*ThreadFunc)(void* param); 113 | typedef void (*DeinitFunc)(void* data); 114 | 115 | enum 116 | { 117 | Priority_Min = -15, 118 | Priority_Normal = 0, 119 | Priority_Max = 15 120 | }; 121 | 122 | private: 123 | struct StartParams 124 | { 125 | Thread* thread; 126 | ThreadFunc userFunc; 127 | void* userParam; 128 | Semaphore ready; 129 | }; 130 | 131 | struct UserData 132 | { 133 | void* data; 134 | DeinitFunc deinitFunc; 135 | }; 136 | 137 | public: 138 | Thread (void); 139 | ~Thread (void); 140 | 141 | void start (ThreadFunc func, void* param); 142 | 143 | static Thread* getCurrent (void); 144 | static Thread* getMain (void); 145 | static bool isMain (void); 146 | static U32 getID (void); 147 | static void sleep (int millis); 148 | static void yield (void); 149 | 150 | int getPriority (void); 151 | void setPriority (int priority); 152 | bool isAlive (void); 153 | void join (void); 154 | 155 | void* getUserData (const String& id); 156 | void setUserData (const String& id, void* data, DeinitFunc deinitFunc = NULL); 157 | 158 | static void suspendAll (void); // Called by fail(). 159 | 160 | private: 161 | void refer (void); 162 | void unrefer (void); // Deferred call to exited() once m_exited == true and refCount == 0. 163 | 164 | void started (void); 165 | void exited (void); 166 | 167 | static DWORD WINAPI threadProc (LPVOID lpParameter); 168 | 169 | private: 170 | Thread (const Thread&); // forbidden 171 | Thread& operator= (const Thread&); // forbidden 172 | 173 | private: 174 | static Spinlock s_lock; 175 | static Thread* s_mainThread; 176 | static Hash s_threads; 177 | 178 | Spinlock m_lock; 179 | S32 m_refCount; 180 | bool m_exited; 181 | 182 | Spinlock m_startLock; 183 | U32 m_id; 184 | HANDLE m_handle; 185 | S32 m_priority; 186 | 187 | Hash m_userData; 188 | }; 189 | 190 | //------------------------------------------------------------------------ 191 | } 192 | -------------------------------------------------------------------------------- /src/framework/base/Timer.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #include "base/Timer.hpp" 29 | 30 | using namespace FW; 31 | 32 | //------------------------------------------------------------------------ 33 | 34 | F64 Timer::s_ticksToSecsCoef = -1.0; 35 | S64 Timer::s_prevTicks = 0; 36 | 37 | //------------------------------------------------------------------------ 38 | 39 | void Timer::staticInit(void) 40 | { 41 | LARGE_INTEGER freq; 42 | if (!QueryPerformanceFrequency(&freq)) 43 | failWin32Error("QueryPerformanceFrequency"); 44 | s_ticksToSecsCoef = max(1.0 / (F64)freq.QuadPart, 0.0); 45 | } 46 | 47 | //------------------------------------------------------------------------ 48 | -------------------------------------------------------------------------------- /src/framework/base/Timer.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #pragma once 29 | #include "base/DLLImports.hpp" 30 | 31 | namespace FW 32 | { 33 | //------------------------------------------------------------------------ 34 | 35 | class Timer 36 | { 37 | public: 38 | explicit inline Timer (bool started = false) : m_startTicks((started) ? queryTicks() : -1), m_totalTicks(0) {} 39 | inline Timer (const Timer& other) { operator=(other); } 40 | inline ~Timer (void) {} 41 | 42 | inline void start (void) { m_startTicks = queryTicks(); } 43 | inline void unstart (void) { m_startTicks = -1; } 44 | inline F32 getElapsed (void) { return ticksToSecs(getElapsedTicks()); } 45 | 46 | inline F32 end (void); // return elapsed, total += elapsed, restart 47 | inline F32 getTotal (void) const { return ticksToSecs(m_totalTicks); } 48 | inline void clearTotal (void) { m_totalTicks = 0; } 49 | 50 | inline Timer& operator= (const Timer& other); 51 | 52 | static void staticInit (void); 53 | static inline S64 queryTicks (void); 54 | static inline F32 ticksToSecs (S64 ticks); 55 | 56 | private: 57 | inline S64 getElapsedTicks (void); // return time since start, start if unstarted 58 | 59 | private: 60 | static F64 s_ticksToSecsCoef; 61 | static S64 s_prevTicks; 62 | 63 | S64 m_startTicks; 64 | S64 m_totalTicks; 65 | }; 66 | 67 | //------------------------------------------------------------------------ 68 | 69 | F32 Timer::end(void) 70 | { 71 | S64 elapsed = getElapsedTicks(); 72 | m_startTicks += elapsed; 73 | m_totalTicks += elapsed; 74 | return ticksToSecs(elapsed); 75 | } 76 | 77 | //------------------------------------------------------------------------ 78 | 79 | Timer& Timer::operator=(const Timer& other) 80 | { 81 | m_startTicks = other.m_startTicks; 82 | m_totalTicks = other.m_totalTicks; 83 | return *this; 84 | } 85 | 86 | //------------------------------------------------------------------------ 87 | 88 | S64 Timer::queryTicks(void) 89 | { 90 | LARGE_INTEGER ticks; 91 | QueryPerformanceCounter(&ticks); 92 | ticks.QuadPart = max(s_prevTicks, ticks.QuadPart); 93 | s_prevTicks = ticks.QuadPart; // increasing little endian => thread-safe 94 | return ticks.QuadPart; 95 | } 96 | 97 | //------------------------------------------------------------------------ 98 | 99 | F32 Timer::ticksToSecs(S64 ticks) 100 | { 101 | if (s_ticksToSecsCoef == -1.0) 102 | staticInit(); 103 | return (F32)((F64)ticks * s_ticksToSecsCoef); 104 | } 105 | 106 | //------------------------------------------------------------------------ 107 | 108 | S64 Timer::getElapsedTicks(void) 109 | { 110 | S64 curr = queryTicks(); 111 | if (m_startTicks == -1) 112 | m_startTicks = curr; 113 | return curr - m_startTicks; 114 | } 115 | 116 | //------------------------------------------------------------------------ 117 | } 118 | -------------------------------------------------------------------------------- /src/framework/base/UnionFind.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #include "base/UnionFind.hpp" 29 | 30 | using namespace FW; 31 | 32 | //------------------------------------------------------------------------ 33 | 34 | int UnionFind::unionSets(int idxA, int idxB) 35 | { 36 | // Grow the array. 37 | 38 | FW_ASSERT(idxA >= 0 && idxB >= 0); 39 | int oldSize = m_sets.getSize(); 40 | int newSize = max(idxA, idxB) + 1; 41 | if (newSize > oldSize) 42 | { 43 | m_sets.resize(newSize); 44 | for (int i = oldSize; i < newSize; i++) 45 | m_sets[i] = i; 46 | } 47 | 48 | // Union the sets. 49 | 50 | int root = findSet(idxA); 51 | m_sets[findSet(idxB)] = root; 52 | return root; 53 | } 54 | 55 | //------------------------------------------------------------------------ 56 | 57 | int UnionFind::findSet(int idx) const 58 | { 59 | // Out of the array => isolated. 60 | 61 | if (idx < 0 || idx >= m_sets.getSize()) 62 | return idx; 63 | 64 | // Find the root set. 65 | 66 | int root = idx; 67 | for (;;) 68 | { 69 | int parent = m_sets[root]; 70 | if (parent == root) 71 | break; 72 | root = parent; 73 | } 74 | 75 | // Update parent links to point directly to the root. 76 | 77 | for (;;) 78 | { 79 | int parent = m_sets[idx]; 80 | if (parent == root) 81 | break; 82 | m_sets[idx] = root; 83 | idx = parent; 84 | } 85 | return root; 86 | } 87 | 88 | //------------------------------------------------------------------------ 89 | -------------------------------------------------------------------------------- /src/framework/base/UnionFind.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #pragma once 29 | #include "base/Array.hpp" 30 | 31 | namespace FW 32 | { 33 | //------------------------------------------------------------------------ 34 | 35 | class UnionFind 36 | { 37 | public: 38 | explicit UnionFind (int capacity = 0) { setCapacity(capacity); } 39 | UnionFind (const UnionFind& other) { set(other); } 40 | ~UnionFind (void) {} 41 | 42 | int unionSets (int idxA, int idxB); 43 | int findSet (int idx) const; 44 | bool isSameSet (int idxA, int idxB) const { return (findSet(idxA) == findSet(idxB)); } 45 | 46 | void clear (void) { m_sets.clear(); } 47 | void reset (void) { m_sets.reset(); } 48 | void setCapacity (int capacity) { m_sets.setCapacity(capacity); } 49 | void set (const UnionFind& other) { m_sets = other.m_sets; } 50 | 51 | UnionFind& operator= (const UnionFind& other) { set(other); return *this; } 52 | int operator[] (int idx) const { return findSet(idx); } 53 | 54 | private: 55 | mutable Array m_sets; 56 | }; 57 | 58 | //------------------------------------------------------------------------ 59 | } 60 | -------------------------------------------------------------------------------- /src/framework/gpu/CudaModule.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #pragma once 29 | #include "gpu/GLContext.hpp" 30 | #include "gpu/CudaKernel.hpp" 31 | 32 | namespace FW 33 | { 34 | //------------------------------------------------------------------------ 35 | 36 | class CudaModule 37 | { 38 | public: 39 | CudaModule (const void* cubin); 40 | CudaModule (const String& cubinFile); 41 | ~CudaModule (void); 42 | 43 | CUmodule getHandle (void) { return m_module; } 44 | 45 | bool hasKernel (const String& name); 46 | CudaKernel getKernel (const String& name); 47 | 48 | Buffer& getGlobal (const String& name); 49 | void updateGlobals (bool async = false, CUstream stream = NULL); // copy to the device if modified 50 | 51 | CUtexref getTexRef (const String& name); 52 | void setTexRefMode (CUtexref texRef, bool wrap = true, bool bilinear = true, bool normalizedCoords = true, bool readAsInt = false); 53 | void setTexRef (const String& name, Buffer& buf, CUarray_format format, int numComponents); 54 | void setTexRef (const String& name, CUdeviceptr ptr, S64 size, CUarray_format format, int numComponents); 55 | void setTexRef (const String& name, CUarray cudaArray, bool wrap = true, bool bilinear = true, bool normalizedCoords = true, bool readAsInt = false); 56 | void setTexRef (const String& name, const Image& image, bool wrap = true, bool bilinear = true, bool normalizedCoords = true, bool readAsInt = false); 57 | void unsetTexRef (const String& name); 58 | void updateTexRefs (CUfunction kernel); 59 | 60 | CUsurfref getSurfRef (const String& name); 61 | void setSurfRef (const String& name, CUarray cudaArray); 62 | 63 | static void staticInit (void); 64 | static void staticDeinit (void); 65 | static bool isAvailable (void) { staticInit(); return s_available; } 66 | static S64 getMemoryUsed (void); 67 | static void sync (bool yield = true); // False = low latency but keeps the CPU busy. True = long latency but relieves the CPU. 68 | static void checkError (const char* funcName, CUresult res); 69 | static const char* decodeError (CUresult res); 70 | 71 | static CUdevice getDeviceHandle (void) { staticInit(); return s_device; } 72 | static int getDriverVersion (void); // e.g. 23 = 2.3 73 | static int getComputeCapability(void); // e.g. 13 = 1.3 74 | static int getDeviceAttribute (CUdevice_attribute attrib); 75 | static CUevent getStartEvent (void) { staticInit(); return s_startEvent; } 76 | static CUevent getEndEvent (void) { staticInit(); return s_endEvent; } 77 | 78 | private: 79 | static CUdevice selectDevice (void); 80 | static void printDeviceInfo (CUdevice device); 81 | static Vec2i selectGridSize (int numBlocks); // TODO: remove 82 | CUfunction findKernel (const String& name); 83 | 84 | private: 85 | CudaModule (const CudaModule&); // forbidden 86 | CudaModule& operator= (const CudaModule&); // forbidden 87 | 88 | private: 89 | static bool s_inited; 90 | static bool s_available; 91 | static CUdevice s_device; 92 | static CUcontext s_context; 93 | static CUevent s_startEvent; 94 | static CUevent s_endEvent; 95 | 96 | CUmodule m_module; 97 | Hash m_kernels; 98 | Array m_globals; 99 | Hash m_globalHash; 100 | Array m_texRefs; 101 | Hash m_texRefHash; 102 | }; 103 | 104 | //------------------------------------------------------------------------ 105 | } 106 | -------------------------------------------------------------------------------- /src/framework/gui/Keys.hpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ap1/cudaraster/11f6516685596af607af4b046f3001646e2ca2f0/src/framework/gui/Keys.hpp -------------------------------------------------------------------------------- /src/framework/io/AviExporter.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #pragma once 29 | #include "io/File.hpp" 30 | #include "gui/Image.hpp" 31 | 32 | namespace FW 33 | { 34 | 35 | //------------------------------------------------------------------------ 36 | 37 | class AviExporter 38 | { 39 | public: 40 | AviExporter (const String& fileName, Vec2i size, int fps); 41 | ~AviExporter (void); 42 | 43 | const Image& getFrame (void) const { return m_frame; } 44 | Image& getFrame (void) { return m_frame; } 45 | int getFPS (void) const { return m_fps; } 46 | 47 | void exportFrame (void); 48 | void flush (void); 49 | 50 | private: 51 | void setTag (int ofs, const char* tag); 52 | void setS32 (int ofs, S32 value); 53 | void writeHeader (void); 54 | 55 | private: 56 | AviExporter (const AviExporter&); // forbidden 57 | AviExporter& operator= (const AviExporter&); // forbidden 58 | 59 | private: 60 | File m_file; 61 | Vec2i m_size; 62 | Image m_frame; 63 | S32 m_fps; 64 | 65 | S32 m_lineBytes; 66 | S32 m_frameBytes; 67 | S32 m_numFrames; 68 | Array m_buffer; 69 | }; 70 | 71 | //------------------------------------------------------------------------ 72 | } 73 | -------------------------------------------------------------------------------- /src/framework/io/File.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #pragma once 29 | #include "io/Stream.hpp" 30 | #include "base/DLLImports.hpp" 31 | 32 | namespace FW 33 | { 34 | 35 | //------------------------------------------------------------------------ 36 | 37 | class File : public InputStream, public OutputStream 38 | { 39 | public: 40 | enum 41 | { 42 | MaxBytesPerSysCall = 16 << 20, 43 | MinimumExpandNum = 5, 44 | MinimumExpandDenom = 4 45 | }; 46 | 47 | enum Mode 48 | { 49 | Read, // must exist - cannot be written 50 | Create, // created or truncated - can be read or written 51 | Modify // opened or created - can be read or written 52 | }; 53 | 54 | class AsyncOp 55 | { 56 | friend class File; 57 | 58 | public: 59 | ~AsyncOp (void); 60 | 61 | bool isDone (void); 62 | bool hasFailed (void) const { return m_failed; } 63 | void wait (void); 64 | int getNumBytes (void) const { FW_ASSERT(m_done); return (m_failed) ? 0 : m_userBytes; } 65 | 66 | private: 67 | AsyncOp (HANDLE fileHandle); 68 | 69 | void done (void); 70 | void failed (void) { m_failed = true; done(); } 71 | 72 | private: 73 | AsyncOp (const AsyncOp&); // forbidden 74 | AsyncOp& operator= (const AsyncOp&); // forbidden 75 | 76 | private: 77 | S64 m_offset; 78 | S32 m_numBytes; // Number of bytes to read or write. 79 | S32 m_expectedBytes; // Number of bytes to expect. 80 | S32 m_userBytes; // Number of bytes to return to the user. 81 | void* m_readPtr; // Buffer to read to. 82 | const void* m_writePtr; // Buffer to write from. 83 | 84 | S32 m_copyBytes; // Number of bytes to copy afterwards. 85 | const void* m_copySrc; // Pointer to copy from. 86 | void* m_copyDst; // Pointer to copy to. 87 | void* m_freePtr; // Pointer to free afterwards. 88 | 89 | HANDLE m_fileHandle; 90 | OVERLAPPED m_overlapped; 91 | bool m_done; 92 | bool m_failed; 93 | }; 94 | 95 | public: 96 | File (const String& name, Mode mode, bool disableCache = false); 97 | virtual ~File (void); 98 | 99 | const String& getName (void) const { return m_name; } 100 | Mode getMode (void) const { return m_mode; } 101 | int getAlign (void) const { return m_align; } // 1 unless disableCache = true. 102 | bool checkWritable (void) const; 103 | 104 | S64 getSize (void) const { return m_size; } 105 | S64 getOffset (void) const { return m_offset; } 106 | void seek (S64 ofs); 107 | void setSize (S64 size); 108 | void allocateSpace (S64 size); 109 | 110 | virtual int read (void* ptr, int size); 111 | virtual void write (const void* ptr, int size); 112 | virtual void flush (void); 113 | 114 | AsyncOp* readAsync (void* ptr, int size); 115 | AsyncOp* writeAsync (const void* ptr, int size); 116 | 117 | private: 118 | File (const File&); // forbidden 119 | File& operator= (const File&); // forbidden 120 | 121 | void fixSize (void); 122 | void startOp (AsyncOp* op); 123 | 124 | void* allocAligned (void*& base, int size); 125 | bool readAligned (S64 ofs, void* ptr, int size); 126 | 127 | private: 128 | String m_name; 129 | Mode m_mode; 130 | bool m_disableCache; 131 | HANDLE m_handle; 132 | S32 m_align; 133 | 134 | S64 m_size; 135 | S64 m_actualSize; 136 | S64 m_offset; 137 | }; 138 | 139 | //------------------------------------------------------------------------ 140 | } 141 | -------------------------------------------------------------------------------- /src/framework/io/ImageBinaryIO.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #include "io/ImageBinaryIO.hpp" 29 | #include "gui/Image.hpp" 30 | #include "io/Stream.hpp" 31 | 32 | using namespace FW; 33 | 34 | //------------------------------------------------------------------------ 35 | 36 | Image* FW::importBinaryImage(InputStream& stream) 37 | { 38 | // ImageHeader. 39 | 40 | char formatID[9]; 41 | stream.readFully(formatID, 8); 42 | formatID[8] = '\0'; 43 | if (String(formatID) != "BinImage") 44 | { 45 | setError("Not a binary image file!"); 46 | return NULL; 47 | } 48 | 49 | S32 version; 50 | stream >> version; 51 | if (version != 1) 52 | { 53 | setError("Unsupported binary image version!"); 54 | return NULL; 55 | } 56 | 57 | S32 width, height, bpp, numChannels; 58 | stream >> width >> height >> bpp >> numChannels; 59 | if (width < 0 || height < 0 || bpp < 0 || numChannels < 0) 60 | { 61 | setError("Corrupt binary image data!"); 62 | return NULL; 63 | } 64 | 65 | // Array of ImageChannel. 66 | 67 | ImageFormat format; 68 | for (int i = 0; i < numChannels; i++) 69 | { 70 | S32 ctype, cformat; 71 | ImageFormat::Channel c; 72 | stream >> ctype >> cformat >> c.wordOfs >> c.wordSize >> c.fieldOfs >> c.fieldSize; 73 | if (ctype < 0 || cformat < 0 || cformat >= ImageFormat::ChannelFormat_Max || 74 | c.wordOfs < 0 || (c.wordSize != 1 && c.wordSize != 2 && c.wordSize != 4) || 75 | c.fieldOfs < 0 || c.fieldSize <= 0 || c.fieldOfs + c.fieldSize > c.wordSize * 8 || 76 | (cformat == ImageFormat::ChannelFormat_Float && c.fieldSize != 32)) 77 | { 78 | setError("Corrupt binary image data!"); 79 | return NULL; 80 | } 81 | 82 | c.type = (ImageFormat::ChannelType)ctype; 83 | c.format = (ImageFormat::ChannelFormat)cformat; 84 | format.addChannel(c); 85 | } 86 | 87 | if (bpp != format.getBPP()) 88 | { 89 | setError("Corrupt binary image data!"); 90 | return NULL; 91 | } 92 | 93 | // Image data. 94 | 95 | Image* image = new Image(Vec2i(width, height), format); 96 | stream.readFully(image->getMutablePtr(), width * height * bpp); 97 | 98 | // Handle errors. 99 | 100 | if (hasError()) 101 | { 102 | delete image; 103 | return NULL; 104 | } 105 | return image; 106 | } 107 | 108 | //------------------------------------------------------------------------ 109 | 110 | void FW::exportBinaryImage(OutputStream& stream, const Image* image) 111 | { 112 | FW_ASSERT(image); 113 | const Vec2i& size = image->getSize(); 114 | const ImageFormat& format = image->getFormat(); 115 | int bpp = format.getBPP(); 116 | 117 | // ImageHeader. 118 | 119 | stream.write("BinImage", 8); 120 | stream << (S32)1 << (S32)size.x << (S32)size.y << (S32)bpp << (S32)format.getNumChannels(); 121 | 122 | // Array of ImageChannel. 123 | 124 | for (int i = 0; i < format.getNumChannels(); i++) 125 | { 126 | const ImageFormat::Channel& c = format.getChannel(i); 127 | stream << (S32)c.type << (S32)c.format << (S32)c.wordOfs << (S32)c.wordSize << (S32)c.fieldOfs << (S32)c.fieldSize; 128 | } 129 | 130 | // Image data. 131 | 132 | if (image->getStride() == size.x * bpp) 133 | stream.write(image->getPtr(), size.x * size.y * bpp); 134 | else 135 | for (int y = 0; y < size.y; y++) 136 | stream.write(image->getPtr(Vec2i(0, y)), size.x * bpp); 137 | } 138 | 139 | //------------------------------------------------------------------------ 140 | -------------------------------------------------------------------------------- /src/framework/io/ImageBinaryIO.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #pragma once 29 | #include "base/Defs.hpp" 30 | 31 | namespace FW 32 | { 33 | //------------------------------------------------------------------------ 34 | 35 | class Image; 36 | class InputStream; 37 | class OutputStream; 38 | 39 | //------------------------------------------------------------------------ 40 | 41 | Image* importBinaryImage (InputStream& stream); 42 | void exportBinaryImage (OutputStream& stream, const Image* image); 43 | 44 | //------------------------------------------------------------------------ 45 | /* 46 | 47 | Binary image file format v1 48 | --------------------------- 49 | 50 | - the basic units of data are 32-bit little-endian ints and floats 51 | 52 | BinaryImage 53 | 0 7 struct ImageHeader 54 | 3 n*6 struct array of ImageChannel (ImageHeader.numChannels) 55 | ? ? struct image data (ImageHeader.width * ImageHeader.height * ImageHeader.bpp) 56 | ? 57 | 58 | ImageHeader 59 | 0 2 bytes formatID (must be "BinImage") 60 | 2 1 int formatVersion (must be 1) 61 | 3 1 int width 62 | 4 1 int height 63 | 5 1 int bpp 64 | 6 1 int numChannels 65 | 7 66 | 67 | ImageChannel 68 | 0 1 int type (see ImageFormat::ChannelType) 69 | 1 1 int format (see ImageFormat::ChannelFormat) 70 | 2 1 int wordOfs 71 | 3 1 int wordSize 72 | 4 1 int fieldOfs 73 | 5 1 int fieldSize 74 | 6 75 | 76 | */ 77 | //------------------------------------------------------------------------ 78 | } 79 | -------------------------------------------------------------------------------- /src/framework/io/ImageBmpIO.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #pragma once 29 | #include "base/Defs.hpp" 30 | 31 | namespace FW 32 | { 33 | //------------------------------------------------------------------------ 34 | 35 | class Image; 36 | class InputStream; 37 | class OutputStream; 38 | 39 | //------------------------------------------------------------------------ 40 | 41 | Image* importBmpImage (InputStream& stream); 42 | void exportBmpImage (OutputStream& stream, const Image* image); 43 | 44 | //------------------------------------------------------------------------ 45 | } 46 | -------------------------------------------------------------------------------- /src/framework/io/ImageLodePngIO.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #include "io/ImageLodePngIO.hpp" 29 | #include "io/Stream.hpp" 30 | #include "gui/Image.hpp" 31 | 32 | #include "3rdparty/lodepng/lodepng.h" 33 | 34 | using namespace FW; 35 | 36 | //------------------------------------------------------------------------ 37 | 38 | Image* FW::importLodePngImage(InputStream& stream) 39 | { 40 | // Read the entire input stream. 41 | 42 | Array dataBuffer; 43 | int blockSize = 4096; 44 | for (;;) 45 | { 46 | int pos = dataBuffer.getSize(); 47 | dataBuffer.resize(pos + blockSize); 48 | int num = stream.read(dataBuffer.getPtr(pos), blockSize); 49 | if (num < blockSize) 50 | { 51 | dataBuffer.resize(pos + num); 52 | break; 53 | } 54 | } 55 | 56 | if (hasError()) 57 | return NULL; 58 | 59 | // Decode image info. 60 | 61 | LodePNG::Decoder decoder; 62 | decoder.inspect(dataBuffer.getPtr(), dataBuffer.getSize()); 63 | Vec2i size(decoder.getWidth(), decoder.getHeight()); 64 | bool hasAlpha = (LodePNG_InfoColor_canHaveAlpha(&decoder.getInfoPng().color) != 0); 65 | 66 | if (decoder.hasError()) 67 | setError("importLodePngImage(): LodePNG error %d!", decoder.getError()); 68 | if (min(size) <= 0) 69 | setError("importLodePngImage(): Invalid image size!"); 70 | if (hasError()) 71 | return NULL; 72 | 73 | // Decode image data. 74 | 75 | int numBytes = size.x * size.y * ((hasAlpha) ? 4 : 3); 76 | std::vector pixelBuffer; 77 | pixelBuffer.reserve(numBytes); 78 | decoder.getInfoRaw().color.colorType = (hasAlpha) ? 6 : 2; 79 | decoder.decode(pixelBuffer, dataBuffer.getPtr(), dataBuffer.getSize()); 80 | 81 | if (decoder.hasError()) 82 | setError("importLodePngImage(): LodePNG error %d!", decoder.getError()); 83 | if ((int)pixelBuffer.size() != numBytes) 84 | setError("importLodePngImage(): Incorrect amount of pixel data!"); 85 | if (hasError()) 86 | return NULL; 87 | 88 | // Create image. 89 | 90 | Image* image = new Image(size, (hasAlpha) ? ImageFormat::R8_G8_B8_A8 : ImageFormat::R8_G8_B8); 91 | image->getBuffer().set(&pixelBuffer[0], numBytes); 92 | return image; 93 | } 94 | 95 | //------------------------------------------------------------------------ 96 | 97 | void FW::exportLodePngImage(OutputStream& stream, const Image* image) 98 | { 99 | // Select format and convert. 100 | 101 | FW_ASSERT(image); 102 | const Vec2i& size = image->getSize(); 103 | bool hasAlpha = image->getFormat().hasChannel(ImageFormat::ChannelType_A); 104 | ImageFormat::ID format = (hasAlpha) ? ImageFormat::R8_G8_B8_A8 : ImageFormat::R8_G8_B8; 105 | 106 | Image* converted = NULL; 107 | if (image->getFormat().getID() != format) 108 | { 109 | converted = new Image(size, format); 110 | *converted = *image; 111 | } 112 | 113 | // Encode image. 114 | 115 | LodePNG::Encoder encoder; 116 | int colorType = (hasAlpha) ? 6 : 2; 117 | encoder.getSettings().autoLeaveOutAlphaChannel = false; 118 | encoder.getInfoRaw().color.colorType = colorType; 119 | encoder.getInfoPng().color.colorType = colorType; 120 | 121 | std::vector dataBuffer; 122 | encoder.encode(dataBuffer, (U8*)((converted) ? converted : image)->getPtr(), size.x, size.y); 123 | 124 | if (encoder.hasError()) 125 | setError("exportLodePngImage(): LodePNG error %d!", encoder.getError()); 126 | 127 | // Write to the output stream. 128 | 129 | if (!hasError() && !dataBuffer.empty()) 130 | stream.write(&dataBuffer[0], (int)dataBuffer.size()); 131 | 132 | // Clean up. 133 | 134 | delete converted; 135 | } 136 | 137 | //------------------------------------------------------------------------ 138 | -------------------------------------------------------------------------------- /src/framework/io/ImageLodePngIO.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #pragma once 29 | #include "base/Defs.hpp" 30 | 31 | namespace FW 32 | { 33 | //------------------------------------------------------------------------ 34 | 35 | class Image; 36 | class InputStream; 37 | class OutputStream; 38 | 39 | //------------------------------------------------------------------------ 40 | 41 | Image* importLodePngImage (InputStream& stream); 42 | void exportLodePngImage (OutputStream& stream, const Image* image); 43 | 44 | //------------------------------------------------------------------------ 45 | } 46 | -------------------------------------------------------------------------------- /src/framework/io/ImageRawPngIO.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #include "io/ImageRawPngIO.hpp" 29 | #include "gui/Image.hpp" 30 | #include "io/Stream.hpp" 31 | 32 | using namespace FW; 33 | 34 | //------------------------------------------------------------------------ 35 | 36 | namespace FW 37 | { 38 | 39 | class Output 40 | { 41 | public: 42 | Output (OutputStream& s); 43 | ~Output (void) {} 44 | 45 | Output& operator<< (int byte) { m_stream << (U8)byte; m_crc = (m_crc >> 8) ^ m_crcTable[(m_crc ^ byte) & 0xFF]; return *this; } 46 | void writeDWord (U32 value) { *this << (value >> 24) << (value >> 16) << (value >> 8) << value; } 47 | 48 | void resetCRC (U32 value) { m_crc = value; } 49 | U32 getCRC (void) const { return m_crc; } 50 | 51 | private: 52 | Output (const Output&); // forbidden 53 | Output& operator= (const Output&); // forbidden 54 | 55 | private: 56 | OutputStream& m_stream; 57 | U32 m_crcTable[256]; 58 | U32 m_crc; 59 | }; 60 | 61 | } 62 | 63 | //------------------------------------------------------------------------ 64 | 65 | Output::Output(OutputStream& s) 66 | : m_stream (s), 67 | m_crc (0) 68 | { 69 | for (int i = 0; i < 256; i++) 70 | { 71 | U32 v = i; 72 | for (int j = 0; j < 8; j++) 73 | v = (v >> 1) ^ (0xedb88320u & (~(v & 1) + 1)); 74 | m_crcTable[i] = v; 75 | } 76 | } 77 | 78 | //------------------------------------------------------------------------ 79 | 80 | void FW::exportRawPngImage(OutputStream& stream, const Image* image) 81 | { 82 | FW_ASSERT(image); 83 | 84 | // Convert image. 85 | 86 | Vec2i size = image->getSize(); 87 | bool empty = (size.min() <= 0); 88 | bool hasAlpha = image->getFormat().hasChannel(ImageFormat::ChannelType_A); 89 | ImageFormat::ID format = (hasAlpha) ? ImageFormat::R8_G8_B8_A8 : ImageFormat::R8_G8_B8; 90 | const Image* source = image; 91 | Image* converted = NULL; 92 | 93 | if (empty || image->getFormat().getID() != format) 94 | { 95 | size = Vec2i(max(size.x, 1), max(size.y, 1)); 96 | converted = new Image(size, format); 97 | if (empty) 98 | converted->clear(); 99 | else 100 | *converted = *image; 101 | source = converted; 102 | } 103 | 104 | // Write header. 105 | 106 | Output out(stream); 107 | int bpp = (hasAlpha) ? 4 : 3; 108 | int blockLen = size.x * bpp + 1; 109 | 110 | out << 0x89 << 'P' << 'N' << 'G' << 0x0D << 0x0A << 0x1A << 0x0A; 111 | out << 0x00 << 0x00 << 0x00 << 0x0D << 'I' << 'H' << 'D' << 'R'; 112 | out.resetCRC(0x575e51f5); 113 | out.writeDWord(size.x); 114 | out.writeDWord(size.y); 115 | out << 8 << ((hasAlpha) ? 6 : 2) << 0 << 0 << 0; 116 | out.writeDWord(~out.getCRC()); 117 | out.writeDWord(size.y * (blockLen + 5) + 6); 118 | out << 'I' << 'D' << 'A' << 'T' << 0x78 << 0x01; 119 | out.resetCRC(0x13e5812d); 120 | 121 | // Write image data. 122 | 123 | int adlerA = 1; 124 | int adlerB = 0; 125 | 126 | for (int y = 0; y < size.y; y++) 127 | { 128 | out << ((y == size.y - 1) ? 1 : 0); 129 | out << blockLen << (blockLen >> 8) << ~blockLen << (~blockLen >> 8); 130 | out << 0; 131 | adlerB = (adlerA + adlerB) % 65521; 132 | 133 | const U8* scanline = (const U8*)source->getPtr(Vec2i(0, y)); 134 | for (int x = 0; x < blockLen - 1; x++) 135 | { 136 | out << scanline[x]; 137 | adlerA = (adlerA + scanline[x]) % 65521; 138 | adlerB = (adlerA + adlerB) % 65521; 139 | } 140 | } 141 | 142 | out << (adlerB >> 8) << adlerB << (adlerA >> 8) << adlerA; 143 | 144 | // Write footer. 145 | 146 | out.writeDWord(~out.getCRC()); 147 | out << 0x00 << 0x00 << 0x00 << 0x00; 148 | out << 'I' << 'E' << 'N' << 'D' << 0xAE << 0x42 << 0x60 << 0x82; 149 | delete converted; 150 | } 151 | 152 | //------------------------------------------------------------------------ 153 | -------------------------------------------------------------------------------- /src/framework/io/ImageRawPngIO.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #pragma once 29 | #include "base/Defs.hpp" 30 | 31 | namespace FW 32 | { 33 | //------------------------------------------------------------------------ 34 | 35 | class Image; 36 | class OutputStream; 37 | 38 | //------------------------------------------------------------------------ 39 | 40 | void exportRawPngImage (OutputStream& stream, const Image* image); 41 | 42 | //------------------------------------------------------------------------ 43 | } 44 | -------------------------------------------------------------------------------- /src/framework/io/ImageTargaIO.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #pragma once 29 | #include "base/Defs.hpp" 30 | 31 | namespace FW 32 | { 33 | //------------------------------------------------------------------------ 34 | 35 | class Image; 36 | class InputStream; 37 | class OutputStream; 38 | 39 | //------------------------------------------------------------------------ 40 | 41 | Image* importTargaImage (InputStream& stream); 42 | void exportTargaImage (OutputStream& stream, const Image* image); 43 | 44 | //------------------------------------------------------------------------ 45 | } 46 | -------------------------------------------------------------------------------- /src/framework/io/ImageTiffIO.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #pragma once 29 | #include "base/Defs.hpp" 30 | 31 | namespace FW 32 | { 33 | //------------------------------------------------------------------------ 34 | 35 | class Image; 36 | class InputStream; 37 | class OutputStream; 38 | 39 | //------------------------------------------------------------------------ 40 | 41 | Image* importTiffImage (InputStream& stream); 42 | void exportTiffImage (OutputStream& stream, const Image* image); 43 | 44 | //------------------------------------------------------------------------ 45 | } 46 | -------------------------------------------------------------------------------- /src/framework/io/MeshBinaryIO.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #include "io/MeshBinaryIO.hpp" 29 | #include "3d/Mesh.hpp" 30 | #include "io/Stream.hpp" 31 | #include "io/ImageBinaryIO.hpp" 32 | 33 | using namespace FW; 34 | 35 | //------------------------------------------------------------------------ 36 | 37 | MeshBase* FW::importBinaryMesh(InputStream& stream) 38 | { 39 | MeshBase* mesh = new MeshBase; 40 | 41 | // MeshHeader. 42 | 43 | char formatID[9]; 44 | stream.readFully(formatID, 8); 45 | formatID[8] = '\0'; 46 | if (String(formatID) != "BinMesh ") 47 | setError("Not a binary mesh file!"); 48 | 49 | S32 version; 50 | stream >> version; 51 | 52 | int numTex; 53 | switch (version) 54 | { 55 | case 1: numTex = 0; break; 56 | case 2: numTex = MeshBase::TextureType_Alpha + 1; break; 57 | case 3: numTex = MeshBase::TextureType_Displacement + 1; break; 58 | case 4: numTex = MeshBase::TextureType_Environment + 1; break; 59 | default: numTex = 0; setError("Unsupported binary mesh version!"); break; 60 | } 61 | 62 | S32 numAttribs, numVertices, numSubmeshes, numTextures = 0; 63 | stream >> numAttribs >> numVertices >> numSubmeshes; 64 | if (version >= 2) 65 | stream >> numTextures; 66 | if (numAttribs < 0 || numVertices < 0 || numSubmeshes < 0 || numTextures < 0) 67 | setError("Corrupt binary mesh data!"); 68 | 69 | // Array of AttribSpec. 70 | 71 | for (int i = 0; i < numAttribs && !hasError(); i++) 72 | { 73 | S32 type, format, length; 74 | stream >> type >> format >> length; 75 | if (type < 0 || format < 0 || format >= MeshBase::AttribFormat_Max || length < 1 || length > 4) 76 | setError("Corrupt binary mesh data!"); 77 | else 78 | mesh->addAttrib((MeshBase::AttribType)type, (MeshBase::AttribFormat)format, length); 79 | } 80 | 81 | // Array of Vertex. 82 | 83 | if (!hasError()) 84 | { 85 | mesh->resetVertices(numVertices); 86 | stream.readFully(mesh->getMutableVertexPtr(), numVertices * mesh->vertexStride()); 87 | } 88 | 89 | // Array of Texture. 90 | 91 | Array textures(NULL, numTextures); 92 | for (int i = 0; i < numTextures && !hasError(); i++) 93 | { 94 | String id; 95 | stream >> id; 96 | Image* image = importBinaryImage(stream); 97 | textures[i] = Texture::find(id); 98 | if (textures[i].exists()) 99 | delete image; 100 | else 101 | textures[i] = Texture(image, id); 102 | } 103 | 104 | // Array of Submesh. 105 | 106 | for (int i = 0; i < numSubmeshes && !hasError(); i++) 107 | { 108 | mesh->addSubmesh(); 109 | MeshBase::Material& mat = mesh->material(i); 110 | Vec3f ambient; 111 | stream >> ambient >> mat.diffuse >> mat.specular >> mat.glossiness; 112 | if (version >= 3) 113 | stream >> mat.displacementCoef >> mat.displacementBias; 114 | 115 | for (int j = 0; j < numTex; j++) 116 | { 117 | S32 texIdx; 118 | stream >> texIdx; 119 | if (texIdx < -1 || texIdx >= numTextures) 120 | setError("Corrupt binary mesh data!"); 121 | else if (texIdx != -1) 122 | mat.textures[j] = textures[texIdx]; 123 | } 124 | 125 | S32 numTriangles; 126 | stream >> numTriangles; 127 | if (numTriangles < 0) 128 | setError("Corrupt binary mesh data!"); 129 | else 130 | { 131 | Array& inds = mesh->mutableIndices(i); 132 | inds.reset(numTriangles); 133 | stream.readFully(inds.getPtr(), inds.getNumBytes()); 134 | } 135 | } 136 | 137 | // Handle errors. 138 | 139 | if (hasError()) 140 | { 141 | delete mesh; 142 | return NULL; 143 | } 144 | return mesh; 145 | } 146 | 147 | //------------------------------------------------------------------------ 148 | 149 | void FW::exportBinaryMesh(OutputStream& stream, const MeshBase* mesh) 150 | { 151 | FW_ASSERT(mesh); 152 | 153 | // Collapse duplicate textures. 154 | 155 | int numTex = MeshBase::TextureType_Environment + 1; 156 | Array textures; 157 | Hash texHash; 158 | texHash.add(NULL, -1); 159 | 160 | for (int i = 0; i < mesh->numSubmeshes(); i++) 161 | { 162 | const MeshBase::Material& mat = mesh->material(i); 163 | for (int j = 0; j < numTex; j++) 164 | { 165 | const Image* key = mat.textures[j].getImage(); 166 | if (texHash.contains(key)) 167 | continue; 168 | 169 | texHash.add(key, textures.getSize()); 170 | textures.add(mat.textures[j]); 171 | } 172 | } 173 | 174 | // MeshHeader. 175 | 176 | stream.write("BinMesh ", 8); 177 | stream << (S32)4 << (S32)mesh->numAttribs() << (S32)mesh->numVertices() << (S32)mesh->numSubmeshes() << (S32)textures.getSize(); 178 | 179 | // Array of AttribSpec. 180 | 181 | for (int i = 0; i < mesh->numAttribs(); i++) 182 | { 183 | const MeshBase::AttribSpec& spec = mesh->attribSpec(i); 184 | stream << (S32)spec.type << (S32)spec.format << spec.length; 185 | } 186 | 187 | // Array of Vertex. 188 | 189 | stream.write(mesh->getVertexPtr(), mesh->numVertices() * mesh->vertexStride()); 190 | 191 | // Array of Texture. 192 | 193 | for (int i = 0; i < textures.getSize(); i++) 194 | { 195 | stream << textures[i].getID(); 196 | exportBinaryImage(stream, textures[i].getImage()); 197 | } 198 | 199 | // Array of Submesh. 200 | 201 | for (int i = 0; i < mesh->numSubmeshes(); i++) 202 | { 203 | const Array& inds = mesh->indices(i); 204 | const MeshBase::Material& mat = mesh->material(i); 205 | stream << Vec3f(0.0f) << mat.diffuse << mat.specular << mat.glossiness; 206 | stream << mat.displacementCoef << mat.displacementBias; 207 | 208 | for (int j = 0; j < numTex; j++) 209 | stream << texHash[mat.textures[j].getImage()]; 210 | stream << (S32)inds.getSize(); 211 | stream.write(inds.getPtr(), inds.getNumBytes()); 212 | } 213 | } 214 | 215 | //------------------------------------------------------------------------ 216 | -------------------------------------------------------------------------------- /src/framework/io/MeshBinaryIO.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #pragma once 29 | #include "base/Defs.hpp" 30 | 31 | namespace FW 32 | { 33 | //------------------------------------------------------------------------ 34 | 35 | class MeshBase; 36 | class InputStream; 37 | class OutputStream; 38 | 39 | //------------------------------------------------------------------------ 40 | 41 | MeshBase* importBinaryMesh (InputStream& stream); 42 | void exportBinaryMesh (OutputStream& stream, const MeshBase* mesh); 43 | 44 | //------------------------------------------------------------------------ 45 | /* 46 | 47 | Binary mesh file format v4 48 | -------------------------- 49 | 50 | - the basic units of data are 32-bit little-endian ints and floats 51 | 52 | BinaryMesh 53 | 0 6 struct v1 MeshHeader 54 | 6 n*3 struct v1 array of AttribSpec (MeshHeader.numAttribs) 55 | ? n*? struct v1 array of Vertex (MeshHeader.numVertices) 56 | ? n*? struct v2 array of Texture (MeshHeader.numTextures) 57 | ? n*? struct v1 array of Submesh (MeshHeader.numSubmeshes) 58 | ? 59 | 60 | MeshHeader 61 | 0 2 bytes v1 formatID (must be "BinMesh ") 62 | 2 1 int v1 formatVersion (must be 4) 63 | 3 1 int v1 numAttribs 64 | 4 1 int v1 numVertices 65 | 5 1 int v2 numTextures 66 | 6 1 int v1 numSubmeshes 67 | 7 68 | 69 | AttribSpec 70 | 0 1 int v1 type (see MeshBase::AttribType) 71 | 1 1 int v1 format (see MeshBase::AttribFormat) 72 | 2 1 int v1 length 73 | 3 74 | 75 | Vertex 76 | 0 ? bytes v1 array of values (dictated by the set of AttribSpecs) 77 | ? 78 | 79 | Texture 80 | 0 1 int v2 idLength 81 | 1 ? bytes v2 idString 82 | ? ? struct v2 BinaryImage (see Image.hpp) 83 | ? 84 | 85 | Submesh 86 | 0 3 float v1 ambient (ignored) 87 | 3 4 float v1 diffuse 88 | 7 3 float v1 specular 89 | 10 1 float v1 glossiness 90 | 11 1 float v3 displacementCoef 91 | 12 1 float v3 displacementBias 92 | 13 1 int v2 diffuseTexture (-1 if none) 93 | 14 1 int v2 alphaTexture (-1 if none) 94 | 15 1 int v3 displacementTexture (-1 if none) 95 | 16 1 int v4 normalTexture (-1 if none) 96 | 17 1 int v4 environmentTexture (-1 if none) 97 | 18 1 int v1 numTriangles 98 | 19 n*3 int v1 indices 99 | ? 100 | 101 | */ 102 | //------------------------------------------------------------------------ 103 | } 104 | -------------------------------------------------------------------------------- /src/framework/io/MeshWavefrontIO.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #pragma once 29 | #include "3d/Mesh.hpp" 30 | 31 | namespace FW 32 | { 33 | //------------------------------------------------------------------------ 34 | 35 | class BufferedInputStream; 36 | class BufferedOutputStream; 37 | 38 | //------------------------------------------------------------------------ 39 | 40 | Mesh* importWavefrontMesh (BufferedInputStream& stream, const String& fileName); 41 | void exportWavefrontMesh (BufferedOutputStream& stream, const MeshBase* mesh, const String& fileName); 42 | 43 | //------------------------------------------------------------------------ 44 | } 45 | -------------------------------------------------------------------------------- /src/framework/io/StateDump.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #include "io/StateDump.hpp" 29 | 30 | using namespace FW; 31 | 32 | //------------------------------------------------------------------------ 33 | 34 | void StateDump::readFromStream(InputStream& s) 35 | { 36 | clear(); 37 | S32 num; 38 | s >> num; 39 | for (int i = 0; i < num; i++) 40 | { 41 | String id; 42 | Array* data = new Array; 43 | s >> id >> *data; 44 | setInternal(data, id); 45 | } 46 | } 47 | 48 | //------------------------------------------------------------------------ 49 | 50 | void StateDump::writeToStream(OutputStream& s) const 51 | { 52 | s << m_values.getSize(); 53 | for (int i = m_values.firstSlot(); i != -1; i = m_values.nextSlot(i)) 54 | s << m_values.getSlot(i).key << *m_values.getSlot(i).value; 55 | } 56 | 57 | //------------------------------------------------------------------------ 58 | 59 | void StateDump::clear(void) 60 | { 61 | for (int i = m_values.firstSlot(); i != -1; i = m_values.nextSlot(i)) 62 | delete m_values.getSlot(i).value; 63 | m_values.clear(); 64 | } 65 | 66 | //------------------------------------------------------------------------ 67 | 68 | void StateDump::add(const StateDump& other) 69 | { 70 | if (&other != this) 71 | for (int i = other.m_values.firstSlot(); i != -1; i = other.m_values.nextSlot(i)) 72 | setInternal(new Array(*other.m_values.getSlot(i).value), other.m_values.getSlot(i).key); 73 | } 74 | 75 | //------------------------------------------------------------------------ 76 | 77 | const Array* StateDump::get(const String& id) const 78 | { 79 | Array* const* data = m_values.search(xlateId(id)); 80 | return (data) ? *data : NULL; 81 | } 82 | 83 | //------------------------------------------------------------------------ 84 | 85 | bool StateDump::get(void* ptr, int size, const String& id) 86 | { 87 | FW_ASSERT(size >= 0); 88 | FW_ASSERT(ptr || !size); 89 | 90 | Array* const* data = m_values.search(xlateId(id)); 91 | if (!data) 92 | return false; 93 | 94 | FW_ASSERT((*data)->getNumBytes() == size); 95 | memcpy(ptr, (*data)->getPtr(), size); 96 | return true; 97 | } 98 | 99 | //------------------------------------------------------------------------ 100 | 101 | void StateDump::set(const void* ptr, int size, const String& id) 102 | { 103 | setInternal(new Array((const U8*)ptr, size), xlateId(id)); 104 | } 105 | 106 | //------------------------------------------------------------------------ 107 | 108 | void StateDump::setInternal(Array* data, const String& id) 109 | { 110 | if (m_values.contains(id)) 111 | delete m_values.remove(id); 112 | if (data) 113 | m_values.add(id, data); 114 | } 115 | 116 | //------------------------------------------------------------------------ 117 | -------------------------------------------------------------------------------- /src/framework/io/StateDump.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2011, NVIDIA Corporation 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions are met: 7 | * * Redistributions of source code must retain the above copyright 8 | * notice, this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of NVIDIA Corporation nor the 13 | * names of its contributors may be used to endorse or promote products 14 | * derived from this software without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #pragma once 29 | #include "base/Hash.hpp" 30 | #include "io/Stream.hpp" 31 | 32 | namespace FW 33 | { 34 | 35 | //------------------------------------------------------------------------ 36 | 37 | class StateDump : public Serializable 38 | { 39 | public: 40 | StateDump (void) {} 41 | StateDump (const StateDump& other) { add(other); } 42 | virtual ~StateDump (void) { clear(); } 43 | 44 | virtual void readFromStream (InputStream& s); 45 | virtual void writeToStream (OutputStream& s) const; 46 | 47 | void clear (void); 48 | void add (const StateDump& other); 49 | void set (const StateDump& other) { if (&other != this) { clear(); add(other); } } 50 | 51 | void pushOwner (const String& id) { m_owners.add(xlateId(id + "::")); } 52 | void popOwner (void) { m_owners.removeLast(); } 53 | 54 | bool has (const String& id) const { return m_values.contains(xlateId(id)); } 55 | const Array* get (const String& id) const; 56 | bool get (void* ptr, int size, const String& id); 57 | template bool get (T& value, const String& id) const; 58 | template bool get (T& value, const String& id, const T& defValue) const; 59 | template T get (const String& id, const T& defValue) const; 60 | 61 | void set (const void* ptr, int size, const String& id); 62 | template void set (const T& value, const String& id); 63 | void unset (const String& id) { setInternal(NULL, xlateId(id)); } 64 | 65 | StateDump& operator= (const StateDump& other) { set(other); return *this; } 66 | 67 | private: 68 | String xlateId (const String& id) const { return (m_owners.getSize()) ? m_owners.getLast() + id : id; } 69 | void setInternal (Array* data, const String& id); // takes ownership of data 70 | 71 | private: 72 | Hash* > m_values; 73 | Array m_owners; 74 | 75 | mutable MemoryInputStream m_memIn; 76 | MemoryOutputStream m_memOut; 77 | }; 78 | 79 | //------------------------------------------------------------------------ 80 | 81 | template bool StateDump::get(T& value, const String& id) const 82 | { 83 | const Array* data = get(id); 84 | if (!data) 85 | return false; 86 | 87 | m_memIn.reset(*data); 88 | m_memIn >> value; 89 | FW_ASSERT(m_memIn.getOffset() == data->getSize()); 90 | return true; 91 | } 92 | 93 | //------------------------------------------------------------------------ 94 | 95 | template bool StateDump::get(T& value, const String& id, const T& defValue) const 96 | { 97 | if (get(value, id)) 98 | return true; 99 | value = defValue; 100 | return false; 101 | } 102 | 103 | //------------------------------------------------------------------------ 104 | 105 | template T StateDump::get(const String& id, const T& defValue) const 106 | { 107 | T value; 108 | get(value, id, defValue); 109 | return value; 110 | } 111 | 112 | //------------------------------------------------------------------------ 113 | 114 | template void StateDump::set(const T& value, const String& id) 115 | { 116 | m_memOut.clear(); 117 | m_memOut << value; 118 | Array& data = m_memOut.getData(); 119 | set(data.getPtr(), data.getNumBytes(), id); 120 | } 121 | 122 | //------------------------------------------------------------------------ 123 | } 124 | --------------------------------------------------------------------------------