:27 sample.cpp Page 1

Size: px
Start display at page:

Download ":27 sample.cpp Page 1"

Transcription

1 :27 sample.cpp Page 1 // ********************************************************************************************* ******* // This is a program for teaching Vulkan // As such, it is deliberately verbose so that it is obvious (as possible, at least) what is bei ng done // // Mike Bailey, Oregon State University // mjb@cs.oregonstate.edu // // The class notes for which this program was written can be found here: // // // Keyboard commands: // i, I : Toggle using the mouse for object rotation // m, M : Toggle display mode (textures vs. colors, for now) // p, P : Pause the animation // q, Q, Esc: exit the program // // Latest update: January 9, 2018 // ********************************************************************************************* ******* // ********* // INCLUDES: // ********* #ifdef _WIN32 #include <io.h> #include <stdlib.h> #include <stdio.h> //#include <unistd.h> #include <math.h> #ifndef M_PI #define M_PI f #include <stdarg.h> #include <string.h> #include <string> #include <stdbool.h> #include <assert.h> #include <signal.h> #ifndef _WIN32 typedef int errno_t; int fopen_s( FILE**, const char *, const char * ); #define GLFW_INCLUDE_VULKAN #include "glfw3.h" #define GLM_FORCE_RADIANS #define GLM_FORCE_DEPTH_ZERO_TO_ONE #include "glm/vec2.hpp" #include "glm/vec3.hpp" #include "glm/mat4x4.hpp" #include "glm/gtc/matrix_transform.hpp" #include "glm/gtc/matrix_inverse.hpp" //#include "glm/gtc/type_ptr.hpp" #ifdef _WIN32 #pragma comment(linker, "/subsystem:windows") #define APP_NAME_STR_LEN 80 #include "vulkan.h" #include "vk_sdk_platform.h" // these are here to flag why addresses are being passed into a vulkan function -- // 1. is it because the function wants to consume the contents of that tructure or array (IN)? // or, 2. is it because that function is going to fill that staructure or array (OUT)? #define IN

2 :27 sample.cpp Page 2 #define OUT #define INOUT // ****************** // DEFINED CONSTANTS: // ****************** // useful stuff: #define DEBUGFILE "VulkanDebug.txt" #define nullptr (void *)NULL #define MILLION L #define BILLION L #define TEXTURE_COUNT 1 #define APP_SHORT_NAME "cube" #define APP_LONG_NAME "Vulkan Cube Demo Program" #define SECONDS_PER_CYCLE 3.f #define FRAME_LAG 2 #define SWAPCHAINIMAGECOUNT 2 // multiplication factors for input interaction: // // (these are known from previous experience) const float ANGFACT = M_PI/180.f ; const float SCLFACT = 0.005f ; // minimum allowable scale factor: const float MINSCALE = 0.05f ; // active mouse buttons (or them together): const int LEFT = 4 ; const int MIDDLE = 2 ; const int RIGHT = 1 ; // the allocation callbacks could look like this: //typedef struct VkAllocationCallbacks //void* puserdata; //PFN_vkAllocationFunction pfnallocation; //PFN_vkReallocationFunction pfnreallocation; //PFN_vkFreeFunction pfnfree; //PFN_vkInternalAllocationNotification pfninternalallocation; //PFN_vkInternalFreeNotification pfninternalfree; // VkAllocationCallbacks; // but we are not going to use them for now: #define PALLOCATOR (VkAllocationCallbacks *)nullptr // report on a result return: #define REPORT(s) PrintVkError( result, s ); fflush(fpdebug); #define HERE_I_AM(s) if( Verbose ) fprintf( FpDebug, "\n***** %s *****\n", s ); f flush(fpdebug); // graphics parameters: const double FOV = glm::radians(60.); // field-of-view angle const float EYEDIST = 3.; // eye distance const float OMEGA = 2.*M_PI; // angular velocity, radians/sec #define SPIRV_MAGIC 0x // if you do an od -x, the magic number looks like this: //

3 :27 sample.cpp Page 3 #define NUM_QUEUES_WANTED 1 #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0])) // these are here for convenience and readability: #define VK_FORMAT_VEC4 VK_FORMAT_R32G32B32A32_SFLOAT #define VK_FORMAT_XYZW VK_FORMAT_R32G32B32A32_SFLOAT #define VK_FORMAT_VEC3 VK_FORMAT_R32G32B32_SFLOAT #define VK_FORMAT_STP VK_FORMAT_R32G32B32_SFLOAT #define VK_FORMAT_XYZ VK_FORMAT_R32G32B32_SFLOAT #define VK_FORMAT_VEC2 VK_FORMAT_R32G32_SFLOAT #define VK_FORMAT_ST VK_FORMAT_R32G32_SFLOAT #define VK_FORMAT_XY VK_FORMAT_R32G32_SFLOAT #define VK_FORMAT_FLOAT VK_FORMAT_R32_SFLOAT #define VK_FORMAT_S VK_FORMAT_R32_SFLOAT #define VK_FORMAT_X VK_FORMAT_R32_SFLOAT // my own error codes: #define VK_FAILURE (VkResult)( ) #define VK_SHOULD_EXIT (VkResult)( ) #define VK_ERROR_SOMETHING_ELSE (VkResult)( )

4 :27 sample.cpp Page 4 // *********************************************** // MY HELPER TYPEDEFS AND STRUCTS FOR VULKAN WORK: // *********************************************** typedef VkBuffer typedef VkDevice typedef VkDeviceCreateInfo #define vkcreatelogicaldevice VkDataBuffer; VkLogicalDevice; VkLogicalDeviceCreateInfo; vkcreatedevice // holds all the information about a data buffer so it can be encapsulated in one variable: typedef struct MyBuffer VkDataBuffer VkDeviceMemory VkDeviceSize MyBuffer; buffer; vdm; size; typedef struct MyTexture uint32_t uint32_t unsigned char * VkImage VkImageView VkSampler VkDeviceMemory MyTexture; width; height; pixels; teximage; teximageview; texsampler; vdm; // bmp file headers: struct bmfh short bftype; int bfsize; short bfreserved1; short bfreserved2; int bfoffbits; FileHeader; struct bmih int bisize; int biwidth; int biheight; short biplanes; short bibitcount; int bicompression; int bisizeimage; int bixpelspermeter; int biypelspermeter; int biclrused; int biclrimportant; InfoHeader; // ***************************** // STRUCTS FOR THIS APPLICATION: // ***************************** // uniform variable block: struct matbuf glm::mat4 umodelmatrix; glm::mat4 uviewmatrix; glm::mat4 uprojectionmatrix;

5 :27 sample.cpp Page 5 ; glm::mat3 unormalmatrix; // uniform variable block: struct lightbuf glm::vec4 ulightpos; ; // uniform variable block: struct miscbuf float utime; int umode; ; // an array of this struct will hold all vertex information: struct vertex glm::vec3 glm::vec3 glm::vec3 glm::vec2 ; position; normal; color; texcoord;

6 :27 sample.cpp Page 6 // ******************************** // VULKAN-RELATED GLOBAL VARIABLES: // ******************************** VkCommandBuffer CommandBuffers[2]; // 2, because of doublebuffering VkCommandPool CommandPool; VkPipeline ComputePipeline; VkPipelineCache ComputePipelineCache; VkPipelineLayout ComputePipelineLayout; VkDataBuffer DataBuffer; VkImage DepthImage; VkImageView DepthImageView; VkDescriptorSetLayout DescriptorSetLayouts[4]; VkDescriptorSet DescriptorSets[4]; VkDebugReportCallbackEXT ErrorCallback = VK_NULL_HANDLE; VkEvent Event; VkFence Fence; VkDescriptorPool DescriptorPool; VkFramebuffer Framebuffers[2]; VkPipeline GraphicsPipeline; VkPipelineCache GraphicsPipelineCache; VkPipelineLayout GraphicsPipelineLayout; uint32_t Height; VkInstance Instance; VkExtensionProperties * InstanceExtensions; VkLayerProperties * InstanceLayers; VkLogicalDevice LogicalDevice; GLFWwindow * MainWindow; VkPhysicalDevice PhysicalDevice; VkPhysicalDeviceProperties PhysicalDeviceProperties; uint32_t PhysicalDeviceCount; VkPhysicalDeviceFeatures PhysicalDeviceFeatures; VkImage * PresentImages; VkImageView * PresentImageViews; // the swap chain image views VkQueue Queue; VkRect2D RenderArea; VkRenderPass RenderPass; VkSemaphore SemaphoreImageAvailable; VkSemaphore SemaphoreRenderFinished; VkShaderModule ShaderModuleFragment; VkShaderModule ShaderModuleVertex; VkBuffer StagingBuffer; VkDeviceMemory StagingBufferMemory; VkSurfaceKHR Surface; VkSwapchainKHR SwapChain; VkCommandBuffer TextureCommandBuffer; // used for transfering texture from sta ging buffer to actual texture buffer VkImage TextureImage; VkDeviceMemory TextureImageMemory; VkDebugReportCallbackEXT WarningCallback; uint32_t Width; #include "SampleVertexData.cpp" // ************************************* // APPLICATION-RELATED GLOBAL VARIABLES: // ************************************* int ActiveButton; // current button that is down FILE * FpDebug; // where to send debugging messa ges struct lightbuf Light; // cpu struct to hold light info rmation struct matbuf Matrices; // cpu struct to hold matrix inf ormation struct miscbuf Misc; // cpu struct to hold miscellane ous information information int Mode; // 0 = use colors, 1 = use textu res,...

7 :27 sample.cpp Page 7 MyBuffer MyLightUniformBuffer; MyTexture MyPuppyTexture; // the cute puppy texture struct MyBuffer MyMatrixUniformBuffer; MyBuffer MyMiscUniformBuffer; MyBuffer MyVertexDataBuffer; bool NeedToExit; // true means the program should exit int NumRenders; // how many times the render loo p has been called bool Paused; // true means don t animate float Scale; // scaling factor double Time; bool Verbose; // true = write messages into a file int Xmouse, Ymouse; // mouse values float Xrot, Yrot; // rotation angles in degrees bool UseMouse; // true = use mouse for interact ion, false = animate

8 :27 sample.cpp Page 8 // ******************** // FUNCTION PROTOTYPES: // ******************** VkResult DestroyAllVulkan( ); //VkBool32 ErrorCallback( VkDebugReportFlagsEXT, VkDebugReportObjectTypeEXT, uint64_t, size_t, int32_t, const char *, const char *, void * ); int FindMemoryThatIsDeviceLocal( ); int FindMemoryThatIsHostVisible( ); int FindMemoryWithTypeBits( uint32_t ); void InitGraphics( ); VkResult Init01Instance( ); VkResult Init02CreateDebugCallbacks( ); VkResult Init03PhysicalDeviceAndGetQueueFamilyProperties( ); VkResult Init04LogicalDeviceAndQueue( ); VkResult Init05DataBuffer( VkDeviceSize, VkBufferUsageFlags, OUT MyBuffer * ); VkResult Init05UniformBuffer( VkDeviceSize, OUT MyBuffer * ); VkResult Init05MyVertexDataBuffer( VkDeviceSize, OUT MyBuffer * ); VkResult Fill05DataBuffer( IN MyBuffer, IN void * ); VkResult Init06CommandPool( ); VkResult Init06CommandBuffers( ); VkResult Init07TextureSampler( OUT MyTexture * ); VkResult Init07TextureBuffer( INOUT MyTexture * ); VkResult ture * ); Init07TextureBufferAndFillFromBmpFile( IN std::string, OUT MyTex VkResult Init08Swapchain( ); VkResult Init09DepthStencilImage( ); VkResult Init10RenderPasses( ); VkResult Init11Framebuffers( ); VkResult Init12SpirvShader( std::string, OUT VkShaderModule * ); VkResult Init13DescriptorSetPool( ); VkResult Init13DescriptorSetLayouts( ); VkResult Init13DescriptorSets( ); VkResult Init14GraphicsPipelineLayout( ); VkResult Init14GraphicsVertexFragmentPipeline( VkShaderModule, VkShaderMo dule, VkPrimitiveTopology, OUT VkPipeline * ); VkResult Init14ComputePipeline( VkShaderModule, OUT VkPipeline * ); VkResult RenderScene( ); void UpdateScene( ); //VkBool32 WarningCallback( VkDebugReportFlagsEXT, VkDebugReportObjectTypeE XT, uint64_t, size_t, int32_t, const char *, const char *, void * ); void PrintVkError( VkResult, std::string = "" ); void Reset( ); void InitGLFW( ); void GLFWErrorCallback( int, const char * ); void GLFWKeyboard( GLFWwindow *, int, int, int, int ); void GLFWMouseButton( GLFWwindow *, int, int, int ); void GLFWMouseMotion( GLFWwindow *, double, double ); double GLFWGetTime( );

9 :27 sample.cpp Page 9 int ReadInt( FILE * ); short ReadShort( FILE * );

10 :27 sample.cpp Page 10 // ************* // MAIN PROGRAM: // ************* int main( int argc, char * argv[ ] ) Width = 1024; Height = 1024; //FpDebug = stderr; errno_t err = fopen_s( &FpDebug, DEBUGFILE, "w" ); if( err!= 0 ) fprintf( stderr, "Cannot open debug print file %s \n", DEBUGFILE ); FpDebug = stderr; else //int old = _dup(2); //_dup2( _fileno(fpdebug), 2 ); fprintf(stderr, "stderr: Width = %d ; Height = %d\n", Width, Height); fprintf(fpdebug, "FpDebug: Width = %d ; Height = %d\n", Width, Height); Reset( ); InitGraphics( ); // loop until the user closes the window: while( glfwwindowshouldclose( MainWindow ) == 0 ) glfwpollevents( ); Time = glfwgettime( ); // elapsed time, in double-precision seconds UpdateScene( ); RenderScene( ); if( NeedToExit ) break; fprintf(fpdebug, "Closing the GLFW window\n"); vkqueuewaitidle( Queue ); vkdevicewaitidle( LogicalDevice ); DestroyAllVulkan( ); glfwdestroywindow( MainWindow ); glfwterminate( ); return 0;

11 :27 sample.cpp Page 11 void InitGraphics( ) HERE_I_AM( "InitGraphics" ); VkResult result = VK_SUCCESS; Init01Instance( ); InitGLFW( ); Init02CreateDebugCallbacks( ); Init03PhysicalDeviceAndGetQueueFamilyProperties( ); Init04LogicalDeviceAndQueue( ); Init05UniformBuffer( sizeof(matrices), &MyMatrixUniformBuffer ); Fill05DataBuffer( MyMatrixUniformBuffer,(void *) &Matrices ); Init05UniformBuffer( sizeof(light), &MyLightUniformBuffer ); Fill05DataBuffer( MyLightUniformBuffer, (void *) &Light ); Init05UniformBuffer( sizeof(misc), &MyMiscUniformBuffer ); Fill05DataBuffer( MyMiscUniformBuffer, (void *) &Misc ); Init05MyVertexDataBuffer( sizeof(vertexdata), &MyVertexDataBuffer ); Fill05DataBuffer( MyVertexDataBuffer, (void *) VertexData ); Init06CommandPool(); Init06CommandBuffers(); Init07TextureSampler( &MyPuppyTexture ); Init07TextureBufferAndFillFromBmpFile("puppy.bmp", &MyPuppyTexture); Init08Swapchain( ); Init09DepthStencilImage( ); Init10RenderPasses( ); Init11Framebuffers( ); Init12SpirvShader( "sample-vert.spv", &ShaderModuleVertex ); Init12SpirvShader( "sample-frag.spv", &ShaderModuleFragment ); Init13DescriptorSetPool( ); Init13DescriptorSetLayouts(); Init13DescriptorSets( ); Init14GraphicsVertexFragmentPipeline( ShaderModuleVertex, ShaderModuleFragment, VK_PRIMI TIVE_TOPOLOGY_TRIANGLE_LIST, &GraphicsPipeline );

12 :27 sample.cpp Page 12 // ********************** // CREATING THE INSTANCE: // ********************** VkResult Init01Instance( ) HERE_I_AM( "Init01Instance" ); VkResult result = VK_SUCCESS; VkApplicationInfo vai; vai.stype = VK_STRUCTURE_TYPE_APPLICATION_INFO; vai.pnext = nullptr; vai.papplicationname = "Vulkan Sample"; vai.applicationversion = 100; vai.penginename = ""; vai.engineversion = 1; vai.apiversion = VK_MAKE_VERSION(1, 0, 0); // these are the layers and extensions we would like to have: const char * instancelayers[ ] = ////"VK_LAYER_LUNARG_api_dump", ////"VK_LAYER_LUNARG_core_validation", //"VK_LAYER_LUNARG_image", "VK_LAYER_LUNARG_object_tracker", "VK_LAYER_LUNARG_parameter_validation", //"VK_LAYER_NV_optimus" ; const char * instanceextensions[ ] = "VK_KHR_surface", "VK_KHR_win32_surface", "VK_EXT_debug_report" //"VK_KHR_swapchains" ; // see what layers are available: uint32_t count; vkenumerateinstancelayerproperties( &count, (VkLayerProperties *)nullptr ); InstanceLayers = new VkLayerProperties[ count ]; result = vkenumerateinstancelayerproperties( &count, InstanceLayers ); REPORT( "vkenumerateinstancelayerproperties" ); if( result!= VK_SUCCESS ) return result; fprintf( FpDebug, "\n%d instance layers enumerated:\n", count ); for( unsigned int i = 0; i < count; i++ ) fprintf( FpDebug, "0x%08x %2d %s %s \n", InstanceLayers[i].specVersion, InstanceLayers[i].implementationVersion, InstanceLayers[i].layerName, InstanceLayers[i].description ); // see what extensions are available: vkenumerateinstanceextensionproperties( (char *)nullptr, &count, (VkExtensionProperties *)nullptr ); InstanceExtensions = new VkExtensionProperties[ count ]; result = vkenumerateinstanceextensionproperties( (char *)nullptr, &count, InstanceExtens ions ); REPORT( "vkenumerateinstanceextensionproperties" ); if( result!= VK_SUCCESS )

13 :27 sample.cpp Page 13 return result; fprintf( FpDebug, "\n%d extensions enumerated:\n", count ); for( unsigned int i = 0; i < count; i++ ) fprintf( FpDebug, "0x%08x %s \n", InstanceExtensions[i].specVersion, InstanceExtensions[i].extensionName ); // create the instance, asking for the layers and extensions: VkInstanceCreateInfo vici; vici.stype = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; vici.pnext = nullptr; vici.flags = 0; vici.papplicationinfo = &vai; vici.enabledlayercount = sizeof(instancelayers) / sizeof(char *); vici.ppenabledlayernames = instancelayers; vici.enabledextensioncount = sizeof(instanceextensions) / sizeof(char *); vici.ppenabledextensionnames = instanceextensions; result = vkcreateinstance( IN &vici, PALLOCATOR, OUT &Instance ); REPORT( "vkcreateinstance" ); return result; // *************************** // CREATE THE DEBUG CALLBACKS: // *************************** VkResult Init02CreateDebugCallbacks( ) HERE_I_AM( "Init02CreateDebugCallbacks" ); VkResult result = VK_SUCCESS; PFN_vkCreateDebugReportCallbackEXT vkcreatedebugreportcallbackext = (PFN_vkCreateDebugRe portcallbackext)nullptr; *(void **) &vkcreatedebugreportcallbackext = vkgetinstanceprocaddr( Instance, "vkcreated ebugreportcallbackext" ); #ifdef NOTDEF VkDebugReportCallbackCreateInfoEXT vdrcci; vdrcci.stype = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT; vdrcci.pnext = nullptr; vdrcci.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT; vdrcci.pfncallback = (PFN_vkDebugReportCallbackEXT) &DebugReportCallback; vdrcci.puserdata = nullptr; result = vkcreatedebugreportcallbackext( Instance, IN &vdrcci, PALLOCATOR, OUT &ErrorCal lback ); REPORT( "vkcreatedebugreportcallbackext - 1" ); NING_BIT_EXT; vdrcci.flags = VK_DEBUG_REPORT_WARNING_BIT_EXT VK_DEBUG_REPORT_PERFORMANCE_WAR result = vkcreatedebugreportcallbackext( Instance, IN &vdrcci, PALLOCATOR, OUT &WarningC allback ); REPORT( "vkcreatedebugreportcallbackext - 2" ); return result; #ifdef NOTYET PFN_vkDebugReportCallbackEXT

14 :27 sample.cpp Page 14 DebugReportCallback(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objecttype, uint64_t object, size_t location, int32_t messagecode, const char * playerprefix, const char * pmessage, void * puserdata) VkBool32 ErrorCallback( VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objecttype, uint64_t object, size_t location, int32_t messagecode, const char * playerprefix, const char * pmessage, void * puserdata ) fprintf( FpDebug, "ErrorCallback: ObjectType = 0x%0x ; object = %ld ; LayerPrefix = %s ; Message = %s \n", objecttype, object, playerprefix, pmessage ); return VK_TRUE; VkBool32 WarningCallback( VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objecttype, uint64_t object, size_t location, int32_t messagecode, const char * playerprefix, const char * pmessage, void * puserdata ) fprintf( FpDebug, "WarningCallback: ObjectType = 0x%0x ; object = %ld ; LayerPrefix = % s ; Message = %s \n", objecttype, object, playerprefix, pmessage ); return VK_TRUE;

15 :27 sample.cpp Page 15 // ************************************************************* // FINDING THE PHYSICAL DEVICES AND GET QUEUE FAMILY PROPERTIES: // ************************************************************* VkResult Init03PhysicalDeviceAndGetQueueFamilyProperties( ) HERE_I_AM( "Init03PhysicalDeviceAndGetQueueFamilyProperties" ); VkResult result = VK_SUCCESS; result = vkenumeratephysicaldevices( Instance, OUT &PhysicalDeviceCount, (VkPhysicalDevi ce *)nullptr ); REPORT( "vkenumeratephysicaldevices - 1" ); if( result!= VK_SUCCESS PhysicalDeviceCount <= 0 ) fprintf( FpDebug, "Could not count the physical devices\n" ); return VK_SHOULD_EXIT; fprintf(fpdebug, "\n%d physical devices found.\n", PhysicalDeviceCount); VkPhysicalDevice * physicaldevices = new VkPhysicalDevice[ PhysicalDeviceCount ]; result = vkenumeratephysicaldevices( Instance, OUT &PhysicalDeviceCount, OUT physicaldev ices ); REPORT( "vkenumeratephysicaldevices - 2" ); if( result!= VK_SUCCESS ) fprintf( FpDebug, "Could not enumerate the %d physical devices\n", PhysicalDevic ecount ); return VK_SHOULD_EXIT; int discreteselect = -1; int integratedselect = -1; for( unsigned int i = 0; i < PhysicalDeviceCount; i++ ) VkPhysicalDeviceProperties vpdp; vkgetphysicaldeviceproperties( IN physicaldevices[i], OUT &vpdp ); if( result!= VK_SUCCESS ) fprintf( FpDebug, "Could not get the physical device properties of devic e %d\n", i ); return VK_SHOULD_EXIT; fprintf( FpDebug, " \n\ndevice %2d:\n", i ); fprintf( FpDebug, "\tapi version: %d\n", vpdp.apiversion ); fprintf( FpDebug, "\tdriver version: %d\n", vpdp.apiversion ); fprintf( FpDebug, "\tvendor ID: 0x%04x\n", vpdp.vendorid ); fprintf( FpDebug, "\tdevice ID: 0x%04x\n", vpdp.deviceid ); fprintf( FpDebug, "\tphysical Device Type: %d =", vpdp.devicetype ); if( vpdp.devicetype == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU ) fprintf( FpDebug, " (Discrete GPU)\n" ); if( vpdp.devicetype == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU ) fprintf( FpDebug, " (Integrated GPU)\n" ); if( vpdp.devicetype == VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU ) fprintf( FpDebug, " (Virtual GPU)\n" ); if( vpdp.devicetype == VK_PHYSICAL_DEVICE_TYPE_CPU ) fprintf( FpDebug, " (CPU)\n" ); fprintf( FpDebug, "\tdevice Name: %s\n", vpdp.devicename ); fprintf( FpDebug, "\tpipeline Cache Size: %d\n", vpdp.pipelinecacheuuid[0] ); //fprintf( FpDebug, "?", vpdp.limits ); //fprintf( FpDebug, "?", vpdp.sparseproperties ); // need some logical here to decide which physical device to select: if( vpdp.devicetype == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU ) discreteselect = i; if( vpdp.devicetype == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU ) integratedselect = i;

16 :27 sample.cpp Page 16 Name ); int which = -1; if( discreteselect >= 0 ) which = discreteselect; PhysicalDevice = physicaldevices[which]; else if( integratedselect >= 0 ) which = integratedselect; PhysicalDevice = physicaldevices[which]; else fprintf( FpDebug, "Could not select a Physical Device\n" ); return VK_SHOULD_EXIT; vkgetphysicaldeviceproperties( PhysicalDevice, OUT &PhysicalDeviceProperties ); fprintf( FpDebug, "Device #%d selected ( %s )\n", which, PhysicalDeviceProperties.device vkgetphysicaldevicefeatures( IN PhysicalDevice, OUT &PhysicalDeviceFeatures ); fprintf( FpDebug, "\nphysical Device Features:\n"); fprintf( FpDebug, "geometryshader = %2d\n", PhysicalDeviceFeatures.geometryShader); fprintf( FpDebug, "tessellationshader = %2d\n", PhysicalDeviceFeatures.tessellationShade r ); fprintf( FpDebug, "multidrawindirect = %2d\n", PhysicalDeviceFeatures.multiDrawIndirect ); fprintf( FpDebug, "widelines = %2d\n", PhysicalDeviceFeatures.wideLines ); fprintf( FpDebug, "largepoints = %2d\n", PhysicalDeviceFeatures.largePoints ); fprintf( FpDebug, "multiviewport = %2d\n", PhysicalDeviceFeatures.multiViewport ); fprintf( FpDebug, "occlusionqueryprecise = %2d\n", PhysicalDeviceFeatures.occlusionQuery Precise ); fprintf( FpDebug, "pipelinestatisticsquery = %2d\n", PhysicalDeviceFeatures.pipelineStat isticsquery ); fprintf( FpDebug, "shaderfloat64 = %2d\n", PhysicalDeviceFeatures.shaderFloat64 ); fprintf( FpDebug, "shaderint64 = %2d\n", PhysicalDeviceFeatures.shaderInt64 ); fprintf( FpDebug, "shaderint16 = %2d\n", PhysicalDeviceFeatures.shaderInt16 ); #ifdef COMMENT All of these VkPhysicalDeviceFeatures are VkBool32s: robustbufferaccess; fulldrawindexuint32; imagecubearray; independentblend; geometryshader; tessellationshader; samplerateshading; dualsrcblend; logicop; multidrawindirect; drawindirectfirstinstance; depthclamp; depthbiasclamp; fillmodenonsolid; depthbounds; widelines; largepoints; alphatoone; multiviewport; sampleranisotropy; texturecompressionetc2; texturecompressionastc_ldr; texturecompressionbc; occlusionqueryprecise; pipelinestatisticsquery; vertexpipelinestoresandatomics; fragmentstoresandatomics; shadertessellationandgeometrypointsize; shaderimagegatherextended; shaderstorageimageextendedformats; shaderstorageimagemultisample;

17 :27 sample.cpp Page 17 shaderstorageimagereadwithoutformat; shaderstorageimagewritewithoutformat; shaderuniformbufferarraydynamicindexing; shadersampledimagearraydynamicindexing; shaderstoragebufferarraydynamicindexing; shaderstorageimagearraydynamicindexing; shaderclipdistance; shaderculldistance; shaderfloat64; shaderint64; shaderint16; shaderresourceresidency; shaderresourceminlod; sparsebinding; sparseresidencybuffer; sparseresidencyimage2d; sparseresidencyimage3d; sparseresidency2samples; sparseresidency4samples; sparseresidency8samples; sparseresidency16samples; sparseresidencyaliased; variablemultisamplerate; inheritedqueries; VkFormatProperties vfp; #ifdef CHOICES VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT = 0x , VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT = 0x , VK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT = 0x , VK_FORMAT_FEATURE_UNIFORM_TEXEL_BUFFER_BIT = 0x , VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_BIT = 0x , VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_ATOMIC_BIT = 0x , VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT = 0x , VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT = 0x , VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT = 0x , VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT = 0x , VK_FORMAT_FEATURE_BLIT_SRC_BIT = 0x , VK_FORMAT_FEATURE_BLIT_DST_BIT = 0x , VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT = 0x , VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_IMG = 0x , fprintf( FpDebug, "\nimage Formats Checked:\n" ); vkgetphysicaldeviceformatproperties( PhysicalDevice, IN VK_FORMAT_R32G32B32A32_SFLOAT, & vfp ); fprintf( FpDebug, "Format VK_FORMAT_R32G32B32A32_SFLOAT: 0x%08x 0x%08x 0x%08x\n", vfp.lineartilingfeatures, vfp.optimaltilingfeatures, vfp.bufferf eatures ); vkgetphysicaldeviceformatproperties( PhysicalDevice, IN VK_FORMAT_R8G8B8A8_UNORM, &vfp ) ; fprintf( FpDebug, "Format VK_FORMAT_R8G8B8A8_UNORM: 0x%08x 0x%08x 0x%08x\n", vfp.lineartilingfeatures, vfp.optimaltilingfeatures, vfp.bufferf eatures ); vkgetphysicaldeviceformatproperties( PhysicalDevice, IN VK_FORMAT_B8G8R8A8_UNORM, &vfp ) ; fprintf( FpDebug, "Format VK_FORMAT_B8G8R8A8_UNORM: 0x%08x 0x%08x 0x%08x\n", vfp.lineartilingfeatures, vfp.optimaltilingfeatures, vfp.bufferf eatures ); VkPhysicalDeviceMemoryProperties vpdmp; vkgetphysicaldevicememoryproperties( PhysicalDevice, OUT &vpdmp ); fprintf( FpDebug, "\n%d Memory Types:\n", vpdmp.memorytypecount ); for( unsigned int i = 0; i < vpdmp.memorytypecount; i++ ) VkMemoryType vmt = vpdmp.memorytypes[i]; fprintf( FpDebug, "Memory %2d: ", i ); if( ( vmt.propertyflags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT )!= 0 ) fprintf( FpDebug, " DeviceLocal" ); if( ( vmt.propertyflags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT )!= 0 ) fprintf( FpDebug, " HostVisible" ); if( ( vmt.propertyflags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT )!= 0 )

18 :27 sample.cpp Page 18 fprintf( FpDebug, " HostCoherent" ); if( ( vmt.propertyflags & VK_MEMORY_PROPERTY_HOST_CACHED_BIT )!= 0 ) fprintf( FpDebug, " HostCached" ); if( ( vmt.propertyflags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT )!= 0 ) fprintf( FpDebug, " LazilyAllocated" ); fprintf(fpdebug, "\n"); fprintf( FpDebug, "\n%d Memory Heaps:\n", vpdmp.memoryheapcount ); for( unsigned int i = 0; i < vpdmp.memoryheapcount; i++ ) fprintf(fpdebug, "Heap %d: ", i); VkMemoryHeap vmh = vpdmp.memoryheaps[i]; fprintf( FpDebug, " size = 0x%08lx", (unsigned long int)vmh.size ); if( ( vmh.flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT )!= 0 ), " DeviceLocal" ); // only one in use fprintf(fpdebug, "\n"); fprintf( FpDebug uint32_t count = -1; vkgetphysicaldevicequeuefamilyproperties( IN PhysicalDevice, &count, OUT (VkQueueFamilyP roperties *)nullptr ); fprintf( FpDebug, "\nfound %d Queue Families:\n", count ); VkQueueFamilyProperties *vqfp = new VkQueueFamilyProperties[ count ]; vkgetphysicaldevicequeuefamilyproperties( IN PhysicalDevice, &count, OUT vqfp ); for( unsigned int i = 0; i < count; i++ ) fprintf( FpDebug, "\t%d: queuecount = %2d ; ", i, vqfp[i].queuecount ); if( ( vqfp[i].queueflags & VK_QUEUE_GRAPHICS_BIT )!= 0 ) fprintf( FpDebug, " Graphics" ); if( ( vqfp[i].queueflags & VK_QUEUE_COMPUTE_BIT )!= 0 ) fprintf( FpDebug, " Compute " ); if( ( vqfp[i].queueflags & VK_QUEUE_TRANSFER_BIT )!= 0 ) fprintf( FpDebug, " Transfer" ); fprintf(fpdebug, "\n"); return result;

19 :27 sample.cpp Page 19 // ************************************ // CREATE THE LOGICAL DEVICE AND QUEUE: // ************************************ VkResult Init04LogicalDeviceAndQueue( ) HERE_I_AM( "Init04LogicalDeviceAndQueue" ); VkResult result = VK_SUCCESS; float queuepriorities[num_queues_wanted] = 1. ;,1.] VkDeviceQueueCreateInfo vdqci[num_queues_wanted]; vdqci[0].stype = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; vdqci[0].pnext = nullptr; vdqci[0].flags = 0; vdqci[0].queuefamilyindex = 0; // which queue family vdqci[0].queuecount = 1; // how many queues to create vdqci[0].pqueuepriorities = queuepriorities; // array of queue priorities [0. const char * mydevicelayers[ ] = ////"VK_LAYER_LUNARG_api_dump", ////"VK_LAYER_LUNARG_core_validation", //"VK_LAYER_LUNARG_image", "VK_LAYER_LUNARG_object_tracker", "VK_LAYER_LUNARG_parameter_validation", //"VK_LAYER_NV_optimus" ; const char * mydeviceextensions[ ] = "VK_KHR_surface", "VK_KHR_win32_surface", "VK_EXT_debug_report" //"VK_KHR_swapchains" ; // see what device layers are available: tr); uint32_t layercount; vkenumeratedevicelayerproperties(physicaldevice, &layercount, (VkLayerProperties *)nullp VkLayerProperties * devicelayers = new VkLayerProperties[layerCount]; result = vkenumeratedevicelayerproperties( PhysicalDevice, &layercount, devicelayers); REPORT("vkEnumerateDeviceLayerProperties"); if (result!= VK_SUCCESS) return result; fprintf(fpdebug, "\n%d physical device layers enumerated:\n", layercount); for (unsigned int i = 0; i < layercount; i++) fprintf(fpdebug, "0x%08x %2d %s %s \n", devicelayers[i].specversion, devicelayers[i].implementationversion, devicelayers[i].layername, devicelayers[i].description); // see what device extensions are available: uint32_t extensioncount; vkenumeratedeviceextensionproperties(physicaldevice, devicelayers[i].layername, &extensioncount, (VkExtensionProperties *)nullptr);

20 :27 sample.cpp Page 20 VkExtensionProperties * deviceextensions = new VkExtensionProperties[extensionCo unt]; result = vkenumeratedeviceextensionproperties(physicaldevice, devicelayers[i].la yername, &extensioncount, deviceextensions); //REPORT("vkEnumerateDeviceExtensionProperties"); if (result!= VK_SUCCESS) return result; fprintf(fpdebug, "\t%d device extensions enumerated for %s :\n", extensioncount, devicelayers[i].layername ); for (unsigned int ii = 0; ii < extensioncount; ii++) fprintf(fpdebug, "\t0x%08x %s \n", deviceextensions[ii].specversion, deviceextensions[ii].extensionname); fprintf(fpdebug, "\n"); VkDeviceCreateInfo vdci; vdci.stype = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; vdci.pnext = nullptr; vdci.flags = 0; vdci.queuecreateinfocount = NUM_QUEUES_WANTED; // # of device queues, e ach of which can create multiple queues vdci.pqueuecreateinfos = IN vdqci; // array of VkDe vicequeuecreateinfo s vdci.enabledlayercount = sizeof(mydevicelayers) / sizeof(char *); //vdci.enabledlayercount = 0; vdci.ppenabledlayernames = mydevicelayers; vdci.enabledextensioncount = 0; vdci.ppenabledextensionnames = (const char **)nullptr; // no ex tensons //vdci.enabledextensioncount = sizeof(mydeviceextensions) / sizeof(char *); //vdci.ppenabledextensionnames = mydeviceextensions; vdci.penabledfeatures = IN &PhysicalDeviceFeatures; // already created ); result = vkcreatelogicaldevice( PhysicalDevice, IN &vdci, PALLOCATOR, OUT &LogicalDevice REPORT( "vkcreatelogicaldevice" ); // get the queue for this logical device: vkgetdevicequeue( LogicalDevice, 0, 0, OUT &Queue ); // queuefamilyindex, queueindex return result;

21 :27 sample.cpp Page 21 // ********************* // CREATE A DATA BUFFER: // ********************* // This just creates the data buffer -- filling it with data uses the Fill05DataBuffer function // Use this for vertex buffers, index buffers, uniform buffers, and textures VkResult Init05DataBuffer( VkDeviceSize size, VkBufferUsageFlags usage, OUT MyBuffer * pmybuffer ) HERE_I_AM( "Init05DataBuffer" ); VkResult result = VK_SUCCESS; VkBufferCreateInfo vbci; vbci.stype = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; vbci.pnext = nullptr; vbci.flags = 0; vbci.size = size; vbci.usage = usage; #ifdef CHOICES VK_USAGE_TRANSFER_SRC_BIT VK_USAGE_TRANSFER_DST_BIT VK_USAGE_UNIFORM_TEXEL_BUFFER_BIT VK_USAGE_STORAGE_TEXEL_BUFFER_BIT VK_USAGE_UNIFORM_BUFFER_BIT VK_USAGE_STORAGE_BUFFER_BIT VK_USAGE_INDEX_BUFFER_BIT VK_USAGE_VERTEX_BUFFER_BIT VK_USAGE_INDIRECT_BUFFER_BIT vbci.sharingmode = VK_SHARING_MODE_CONCURRENT; #ifdef CHOICES VK_SHARING_MODE_EXCLUSIVE VK_SHARING_MODE_CONCURRENT vbci.queuefamilyindexcount = 0; vbci.pqueuefamilyindices = (const uint32_t *)nullptr; ; pmybuffer->size = size; result = vkcreatebuffer ( LogicalDevice, IN &vbci, PALLOCATOR, OUT &pmybuffer->buffer ) REPORT( "vkcreatebuffer" ); VkMemoryRequirements vmr; vkgetbuffermemoryrequirements( LogicalDevice, IN pmybuffer->buffer, OUT &vmr ); // fills vmr if( Verbose ) fprintf( FpDebug, "Buffer vmr.size = %lld\n", vmr.size ); fprintf( FpDebug, "Buffer vmr.alignment = %lld\n", vmr.alignment ); fprintf( FpDebug, "Buffer vmr.memorytypebits = 0x%08x\n", vmr.memorytypebits ); fflush( FpDebug ); VkMemoryAllocateInfo vmai; vmai.stype = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; vmai.pnext = nullptr; vmai.allocationsize = vmr.size; vmai.memorytypeindex = FindMemoryThatIsHostVisible( ); VkDeviceMemory vdm; result = vkallocatememory( LogicalDevice, IN &vmai, PALLOCATOR, OUT &vdm ); REPORT( "vkallocatememory" ); pmybuffer->vdm = vdm; result = vkbindbuffermemory( LogicalDevice, pmybuffer->buffer, IN vdm, 0 ); // 0 is the offset REPORT( "vkbindbuffermemory" ); return result;

22 :27 sample.cpp Page 22 // *********************** // CREATE A VERTEX BUFFER: // *********************** // this allocates space for a data buffer, but doesn t yet fill it: VkResult Init05MyVertexDataBuffer( IN VkDeviceSize size, OUT MyBuffer * pmybuffer ) VkResult result = Init05DataBuffer( size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, pmybuffer ) ; // fills pmybuffer REPORT( "InitDataBuffer" ); return result; // ************************ // CREATE A UNIFORM BUFFER: // ************************ // this allocates space for a data buffer, but doesn t yet fill it: VkResult Init05UniformBuffer( VkDeviceSize size, MyBuffer * pmybuffer ) VkResult result = Init05DataBuffer( size, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, OUT pmybuf fer ); // fills pmybuffer return result; // ******************* // FILL A DATA BUFFER: // ******************* VkResult Fill05DataBuffer( IN MyBuffer mybuffer, IN void * data ) // the size of the data had better match the size that was used to Init the buffer! void * pgpumemory; vkmapmemory( LogicalDevice, IN mybuffer.vdm, 0, VK_WHOLE_SIZE, 0, &pgpumemory ); // 0 and 0 are offset and flags memcpy( pgpumemory, data, (size_t)mybuffer.size ); vkunmapmemory( LogicalDevice, IN mybuffer.vdm ); return VK_SUCCESS;

23 :27 sample.cpp Page 23 // ************************* // CREATE A TEXTURE SAMPLER: // ************************* VkResult Init07TextureSampler( MyTexture * pmytexture ) HERE_I_AM( "Init07TextureSampler" ); VkResult result = VK_SUCCESS; VkSamplerCreateInfo vsci; vsci.stype = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; vsci.pnext = nullptr; vsci.flags = 0; vsci.magfilter = VK_FILTER_LINEAR; vsci.minfilter = VK_FILTER_LINEAR; vsci.mipmapmode = VK_SAMPLER_MIPMAP_MODE_LINEAR; vsci.addressmodeu = VK_SAMPLER_ADDRESS_MODE_REPEAT; vsci.addressmodev = VK_SAMPLER_ADDRESS_MODE_REPEAT; vsci.addressmodew = VK_SAMPLER_ADDRESS_MODE_REPEAT; #ifdef CHOICES VK_SAMPLER_ADDRESS_MODE_REPEAT VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE vsci.miplodbias = 0.; vsci.anisotropyenable = VK_FALSE; vsci.maxanisotropy = 1.; vsci.compareenable = VK_FALSE; vsci.compareop = VK_COMPARE_OP_NEVER; #ifdef CHOICES VK_COMPARE_OP_NEVER VK_COMPARE_OP_LESS VK_COMPARE_OP_EQUAL VK_COMPARE_OP_LESS_OR_EQUAL VK_COMPARE_OP_GREATER VK_COMPARE_OP_NOT_EQUAL VK_COMPARE_OP_GREATER_OR_EQUAL VK_COMPARE_OP_ALWAYS vsci.minlod = 0.; vsci.maxlod = 0.; vsci.bordercolor = VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK; #ifdef CHOICES VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK VK_BORDER_COLOR_INT_TRANSPARENT_BLACK VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK VK_BORDER_COLOR_INT_OPAQUE_BLACK VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE VK_BORDER_COLOR_INT_OPAQUE_WHITE vsci.unnormalizedcoordinates = VK_FALSE; // VK_TRUE means we are use raw texels as the index // VK_FALSE means we are uing th e usual er ); result = vkcreatesampler( LogicalDevice, IN &vsci, PALLOCATOR, OUT &pmytexture->texsampl REPORT( "vkcreatesampler" ); return result; // ************************ // CREATE A TEXTURE BUFFER: // ************************ // assume we get to here and have in a MyTexture struct: // * an unsigned char array, holding the pixel rgba

24 :27 sample.cpp Page 24 // * width is the number of texels in s // * height is the number of texels in t VkResult Init07TextureBuffer( INOUT MyTexture * pmytexture) HERE_I_AM( "Init07TextureBuffer" ); VkResult result = VK_SUCCESS; uint32_t texwidth = pmytexture->width;; uint32_t texheight = pmytexture->height; unsigned char *texture = pmytexture->pixels; VkDeviceSize texturesize = texwidth * texheight * 4; // rgba, 1 byte each VkImage stagingimage; VkImage textureimage; // ******************************************************************************* // this first... is to create the staging image: // ******************************************************************************* VkImageCreateInfo vici; vici.stype = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; vici.pnext = nullptr; vici.flags = 0; #ifdef CHOICES VK_IMAGE_CREATE_SPARSE_BINDING_BIT VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT VK_IMAGE_CREATE_SPARSE_ALIASED_BIT VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT VK_IMAGE_CREATE_BIND_SFR_BIT_KHX VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT_KHR vici.imagetype = VK_IMAGE_TYPE_2D; vici.format = VK_FORMAT_R8G8B8A8_UNORM; vici.extent.width = texwidth; vici.extent.height = texheight; vici.extent.depth = 1; vici.miplevels = 1; vici.arraylayers = 1; vici.samples = VK_SAMPLE_COUNT_1_BIT; vici.tiling = VK_IMAGE_TILING_LINEAR; #ifdef CHOICES VK_IMAGE_TILING_OPTIMAL VK_IMAGE_TILING_LINEAR vici.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT; #ifdef CHOICES VK_IMAGE_USAGE_TRANSFER_SRC_BIT VK_IMAGE_USAGE_TRANSFER_DST_BIT VK_IMAGE_USAGE_SAMPLED_BIT VK_IMAGE_USAGE_STORAGE_BIT VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT vici.sharingmode = VK_SHARING_MODE_EXCLUSIVE; vici.initiallayout = VK_IMAGE_LAYOUT_PREINITIALIZED; #ifdef CHOICES VK_IMAGE_LAYOUT_UNDEFINED VK_IMAGE_LAYOUT_PREINITIALIZED vici.queuefamilyindexcount = 0; vici.pqueuefamilyindices = (const uint32_t *)nullptr; result = vkcreateimage(logicaldevice, IN &vici, PALLOCATOR, OUT &stagingimage); // allocated, but not filled REPORT("vkCreateImage"); VkMemoryRequirements vmr;

25 :27 sample.cpp Page 25 vkgetimagememoryrequirements(logicaldevice, IN stagingimage, OUT &vmr); ts); if (Verbose) fprintf(fpdebug, "Image vmr.size = %lld\n", vmr.size); fprintf(fpdebug, "Image vmr.alignment = %lld\n", vmr.alignment); fprintf(fpdebug, "Image vmr.memorytypebits = 0x%08x\n", vmr.memorytypebi fflush(fpdebug); nt to mmap it VkMemoryAllocateInfo vmai; vmai.stype = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; vmai.pnext = nullptr; vmai.allocationsize = vmr.size; vmai.memorytypeindex = FindMemoryThatIsHostVisible(); // because we wa VkDeviceMemory vdm; result = vkallocatememory(logicaldevice, IN &vmai, PALLOCATOR, OUT &vdm); REPORT("vkAllocateMemory"); pmytexture->vdm = vdm; ffset result = vkbindimagememory(logicaldevice, IN stagingimage, IN vdm, 0); // 0 = o REPORT("vkBindImageMemory"); // we have now created the staging image -- fill it with the pixel data: VkImageSubresource vis; vis.aspectmask = VK_IMAGE_ASPECT_COLOR_BIT; vis.miplevel = 0; vis.arraylayer = 0; VkSubresourceLayout vsl; vkgetimagesubresourcelayout(logicaldevice, stagingimage, IN &vis, OUT &vsl); if (Verbose) fprintf(fpdebug, "Subresource Layout:\n"); fprintf(fpdebug, "\toffset = %lld\n", vsl.offset); fprintf(fpdebug, "\tsize = %lld\n", vsl.size); fprintf(fpdebug, "\trowpitch = %lld\n", vsl.rowpitch); fprintf(fpdebug, "\tarraypitch = %lld\n", vsl.arraypitch); fprintf(fpdebug, "\tdepthpitch = %lld\n", vsl.depthpitch); fflush(fpdebug); void * gpumemory; vkmapmemory(logicaldevice, vdm, 0, VK_WHOLE_SIZE, 0, OUT &gpumemory); // 0 and 0 = offset and memory map flags if (vsl.rowpitch = 4 * texwidth) memcpy(gpumemory, (void *)texture, (size_t)texturesize); else unsigned char *gpubytes = (unsigned char *)gpumemory; for (unsigned int y = 0; y < texheight; y++) memcpy(&gpubytes[y * vsl.rowpitch], &texture[4 * y * texwidth], (size_t)(4*texwidth) ); vkunmapmemory(logicaldevice, vdm); // ******************************************************************************* // *******************************************************************************

26 :27 sample.cpp Page 26 T; // this second... is to create the actual texture image: // ******************************************************************************* VkImageCreateInfo vici; vici.stype = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; vici.pnext = nullptr; vici.flags = 0; vici.imagetype = VK_IMAGE_TYPE_2D; vici.format = VK_FORMAT_R8G8B8A8_UNORM; vici.extent.width = texwidth; vici.extent.height = texheight; vici.extent.depth = 1; vici.miplevels = 1; vici.arraylayers = 1; vici.samples = VK_SAMPLE_COUNT_1_BIT; vici.tiling = VK_IMAGE_TILING_OPTIMAL; vici.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT VK_IMAGE_USAGE_SAMPLED_BI sample from it // because we are transfering into it and will eventual vici.sharingmode = VK_SHARING_MODE_EXCLUSIVE; vici.initiallayout = VK_IMAGE_LAYOUT_PREINITIALIZED; vici.queuefamilyindexcount = 0; vici.pqueuefamilyindices = (const uint32_t *)nullptr; result = vkcreateimage(logicaldevice, IN &vici, PALLOCATOR, OUT &textureimage); // allocated, but not filled REPORT("vkCreateImage"); VkMemoryRequirements vmr; vkgetimagememoryrequirements(logicaldevice, IN textureimage, OUT &vmr); ebits ); if( Verbose ) fprintf( FpDebug, "Texture vmr.size = %lld\n", vmr.size ); fprintf( FpDebug, "Texture vmr.alignment = %lld\n", vmr.alignment ); fprintf( FpDebug, "Texture vmr.memorytypebits = 0x%08x\n", vmr.memorytyp fflush( FpDebug ); VkMemoryAllocateInfo vmai; vmai.stype = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; vmai.pnext = nullptr; vmai.allocationsize = vmr.size; vmai.memorytypeindex = FindMemoryThatIsDeviceLocal( ); // because we wa nt to sample from it VkDeviceMemory vdm; result = vkallocatememory(logicaldevice, IN &vmai, PALLOCATOR, OUT &vdm); REPORT("vkAllocateMemory"); result = vkbindimagememory( LogicalDevice, IN textureimage, IN vdm, 0 ); // 0 = offset REPORT( "vkbindimagememory" ); // ******************************************************************************* // copy pixels from the staging image to the texture: VkCommandBufferBeginInfo vcbbi; vcbbi.stype = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; vcbbi.pnext = nullptr; vcbbi.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; vcbbi.pinheritanceinfo = (VkCommandBufferInheritanceInfo *)nullptr; result = vkbegincommandbuffer( TextureCommandBuffer, IN &vcbbi); REPORT( "Init07TextureBuffer -- vkbegincommandbuffer" ); // ******************************************************************************* // transition the staging buffer layout: // *******************************************************************************

27 :27 sample.cpp Page 27 VkImageSubresourceRange visr; visr.aspectmask = VK_IMAGE_ASPECT_COLOR_BIT; visr.basemiplevel = 0; visr.levelcount = 1; visr.basearraylayer = 0; visr.layercount = 1; VkImageMemoryBarrier vimb; vimb.stype = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; vimb.pnext = nullptr; vimb.oldlayout = VK_IMAGE_LAYOUT_PREINITIALIZED; vimb.newlayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; vimb.srcqueuefamilyindex = VK_QUEUE_FAMILY_IGNORED; vimb.dstqueuefamilyindex = VK_QUEUE_FAMILY_IGNORED; vimb.image = stagingimage; vimb.srcaccessmask = VK_ACCESS_HOST_WRITE_BIT; vimb.dstaccessmask = VK_ACCESS_TRANSFER_READ_BIT; vimb.subresourcerange = visr; T, 0, vkcmdpipelinebarrier( TextureCommandBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BI 0, (VkMemoryBarrier *)nullptr, 0, (VkBufferMemoryBarrier *)nullptr, 1, IN &vimb ); // ******************************************************************************* // ******************************************************************************* // transition the texture buffer layout: // ******************************************************************************* VkImageSubresourceRange visr; visr.aspectmask = VK_IMAGE_ASPECT_COLOR_BIT; visr.basemiplevel = 0; visr.levelcount = 1; visr.basearraylayer = 0; visr.layercount = 1; VkImageMemoryBarrier vimb; vimb.stype = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; vimb.pnext = nullptr; vimb.oldlayout = VK_IMAGE_LAYOUT_PREINITIALIZED; vimb.newlayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; vimb.srcqueuefamilyindex = VK_QUEUE_FAMILY_IGNORED; vimb.dstqueuefamilyindex = VK_QUEUE_FAMILY_IGNORED; vimb.image = textureimage; vimb.srcaccessmask = VK_ACCESS_TRANSFER_READ_BIT; vimb.dstaccessmask = VK_ACCESS_TRANSFER_WRITE_BIT; vimb.subresourcerange = visr;, 0, vkcmdpipelinebarrier(texturecommandbuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT 0, (VkMemoryBarrier *)nullptr, 0, (VkBufferMemoryBarrier *)nullptr, 1, IN &vimb); // now do the final image transfer: VkImageSubresourceLayers visl; visl.aspectmask = VK_IMAGE_ASPECT_COLOR_BIT; visl.basearraylayer = 0; visl.miplevel = 0; visl.layercount = 1; VkOffset3D vo3.x = 0; vo3.y = 0; vo3.z = 0; vo3;

28 :27 sample.cpp Page 28 VkExtent3D ve3.width = texwidth; ve3.height = texheight; ve3.depth = 1; VkImageCopy vic.srcsubresource = visl; vic.srcoffset = vo3; vic.dstsubresource = visl; vic.dstoffset = vo3; vic.extent = ve3; ve3; vic; vkcmdcopyimage(texturecommandbuffer, stagingimage, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, textureimage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, IN &vic); // ******************************************************************************* // ******************************************************************************* // transition the texture buffer layout a second time: // ******************************************************************************* VkImageSubresourceRange visr; visr.aspectmask = VK_IMAGE_ASPECT_COLOR_BIT; visr.basemiplevel = 0; visr.levelcount = 1; visr.basearraylayer = 0; visr.layercount = 1; ENT_READ_BIT; VkImageMemoryBarrier vimb; vimb.stype = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; vimb.pnext = nullptr; vimb.oldlayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; vimb.newlayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; vimb.srcqueuefamilyindex = VK_QUEUE_FAMILY_IGNORED; vimb.dstqueuefamilyindex = VK_QUEUE_FAMILY_IGNORED; vimb.image = textureimage; vimb.srcaccessmask = VK_ACCESS_TRANSFER_READ_BIT; vimb.dstaccessmask = VK_ACCESS_SHADER_READ_BIT VK_ACCESS_INPUT_ATTACHM vimb.subresourcerange = visr;, vkcmdpipelinebarrier(texturecommandbuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0 0, (VkMemoryBarrier *)nullptr, 0, (VkBufferMemoryBarrier *)nullptr, 1, IN &vimb); // ******************************************************************************* result = vkendcommandbuffer( TextureCommandBuffer ); REPORT("Init07TextureBuffer -- vkendcommandbuffer"); VkSubmitInfo vsi; vsi.stype = VK_STRUCTURE_TYPE_SUBMIT_INFO; vsi.pnext = nullptr; vsi.commandbuffercount = 1; vsi.pcommandbuffers = &TextureCommandBuffer; vsi.waitsemaphorecount = 0; vsi.pwaitsemaphores = (VkSemaphore *)nullptr; vsi.signalsemaphorecount = 0; vsi.psignalsemaphores = (VkSemaphore *)nullptr; vsi.pwaitdststagemask = (VkPipelineStageFlags *)nullptr; result = vkqueuesubmit( Queue, 1, IN &vsi, VK_NULL_HANDLE ); if (Verbose) REPORT("vkQueueSubmit"); result = vkqueuewaitidle( Queue ); if (Verbose) REPORT("vkQueueWaitIdle");

29 :27 sample.cpp Page 29 // create an image view for the texture image: VkImageSubresourceRange visr; visr.aspectmask = VK_IMAGE_ASPECT_COLOR_BIT; visr.basemiplevel = 0; visr.levelcount = 1; visr.basearraylayer = 0; visr.layercount = 1; VkImageViewCreateInfo vivci; vivci.stype = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; vivci.pnext = nullptr; vivci.flags = 0; vivci.image = textureimage; vivci.viewtype = VK_IMAGE_VIEW_TYPE_2D; vivci.format = VK_FORMAT_R8G8B8A8_UNORM; vivci.components.r = VK_COMPONENT_SWIZZLE_R; vivci.components.g = VK_COMPONENT_SWIZZLE_G; vivci.components.b = VK_COMPONENT_SWIZZLE_B; vivci.components.a = VK_COMPONENT_SWIZZLE_A; vivci.subresourcerange = visr; result = vkcreateimageview(logicaldevice, IN &vivci, PALLOCATOR, OUT &pmytexture->texima geview); REPORT("vkCreateImageView"); return result; // *************************************** // CREATE A TEXTURE IMAGE FROM A BMP FILE: // *************************************** VkResult Init07TextureBufferAndFillFromBmpFile( IN std::string filename, OUT MyTexture * pmytexture ) HERE_I_AM( "Init07TextureBufferAndFillFromBmpFile" ); VkResult result = VK_SUCCESS; const int birgb = 0 ; FILE * fp; (void) fopen_s( &fp, filename.c_str(), "rb"); if( fp == NULL ) fprintf( FpDebug, "Cannot open Bmp file %s \n", filename.c_str() ); return VK_FAILURE; FileHeader.bfType = ReadShort( fp ); // if bftype is not 0x4d42, the file is not a bmp: if( FileHeader.bfType!= 0x4d42 ) fprintf( FpDebug, "Wrong type of file: 0x%0x\n", FileHeader.bfType ); fclose( fp ); return VK_FAILURE; FileHeader.bfSize = ReadInt( fp ); FileHeader.bfReserved1 = ReadShort( fp ); FileHeader.bfReserved2 = ReadShort( fp ); FileHeader.bfOffBits = ReadInt( fp ); InfoHeader.biSize = ReadInt( fp ); InfoHeader.biWidth = ReadInt( fp ); InfoHeader.biHeight = ReadInt( fp );

30 :27 sample.cpp Page 30 uint32_t texwidth = InfoHeader.biWidth; uint32_t texheight = InfoHeader.biHeight; InfoHeader.biPlanes = ReadShort( fp ); InfoHeader.biBitCount = ReadShort( fp ); InfoHeader.biCompression = ReadInt( fp ); InfoHeader.biSizeImage = ReadInt( fp ); InfoHeader.biXPelsPerMeter = ReadInt( fp ); InfoHeader.biYPelsPerMeter = ReadInt( fp ); InfoHeader.biClrUsed = ReadInt( fp ); InfoHeader.biClrImportant = ReadInt( fp ); fprintf( FpDebug, "Image size found: %d x %d\n", texwidth, texheight ); unsigned char * texture = new unsigned char[ 4 * texwidth * texheight ]; // extra padding bytes: int numextra = 4*(( (3*InfoHeader.biWidth)+3)/4) - 3*InfoHeader.biWidth; // we do not support compression: ion ); if( InfoHeader.biCompression!= birgb ) fprintf( FpDebug, "Wrong type of image compression: %d\n", InfoHeader.biCompress fclose( fp ); return VK_FAILURE; rewind( fp ); fseek( fp, 14+40, SEEK_SET ); if( InfoHeader.biBitCount == 24 ) unsigned char *tp = texture; for( unsigned int t = 0; t < texheight; t++ ) for( unsigned int s = 0; s < texwidth; s++, tp += 4 ) *(tp+3) = 255; // a *(tp+2) = fgetc( fp ); // b *(tp+1) = fgetc( fp ); // g *(tp+0) = fgetc( fp ); // r fclose( fp ); for( int e = 0; e < numextra; e++ ) fgetc( fp ); pmytexture->width = texwidth; pmytexture->height = texheight; pmytexture->pixels = texture; result = Init07TextureBuffer( INOUT pmytexture ); REPORT( "Init07TextureBuffer" ); return result; int ReadInt( FILE *fp ) unsigned char b3, b2, b1, b0; b0 = fgetc( fp ); b1 = fgetc( fp ); b2 = fgetc( fp ); b3 = fgetc( fp );

:27 sample.cpp Page 1

:27 sample.cpp Page 1 2018-01-09 11:27 sample.cpp Page 1 // **************************************************************************************************** // This is a program for teaching Vulkan // As such, it is deliberately

More information

:24 sample.cpp Page 1

:24 sample.cpp Page 1 2018-01-09 11:24 sample.cpp Page 1 // ************************************************************************************ **************** // This is a program for teaching Vulkan // As such, it is deliberately

More information

11/19/2018. Data Buffers. Mike Bailey. From the Quick Reference Card. Computer Graphics DataBuffers.pptx

11/19/2018. Data Buffers. Mike Bailey. From the Quick Reference Card. Computer Graphics DataBuffers.pptx 1 Data Buffers This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Mike Bailey mjb@cs.oregonstate.edu DataBuffers.pptx From the Quick Reference

More information

Physical Devices. Mike Bailey. Computer Graphics PhysicalDevices.pptx

Physical Devices. Mike Bailey. Computer Graphics PhysicalDevices.pptx 1 Physical s This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Mike Bailey mjb@cs.oregonstate.edu Physicals.pptx Vulkan: Overall Block Diagram

More information

Physical Devices. Mike Bailey. Vulkan: Overall Block Diagram. Physical Device. Physical Device. Logical Device.

Physical Devices. Mike Bailey. Vulkan: Overall Block Diagram. Physical Device. Physical Device. Logical Device. 1 s This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Mike Bailey mjb@cs.oregonstate.edu s.pptx Vulkan: Overall Block Diagram 2 Application

More information

Vulkan Sample Code. Mike Bailey. Computer Graphics SampleCode.pptx

Vulkan Sample Code. Mike Bailey. Computer Graphics SampleCode.pptx 1 Vulkan Sample Code This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Mike Bailey mjb@cs.oregonstate.edu SampleCode.pptx Sample Program Output

More information

a.k.a. glnext!! Did the future just arrive? (Spring 2006)!! Next-generation OpenGL?

a.k.a. glnext!! Did the future just arrive? (Spring 2006)!! Next-generation OpenGL? 120(134) Information Coding / Computer Graphics, ISY, LiTH a.k.a. glnext Did the future just arrive? (Spring 2006) Next-generation OpenGL? 120(134) What? When? Where? New API, development started in 2014,

More information

1 Introduction to the Vulkan Graphics API Mike Bailey Oregon State University mjb@cs.oregonstate.edu Ongoing Notes and Code 2 The notes and code presented here are constantly being updated. Go to: http://cs.oregonstate.edu/~mjb/vulkan

More information

Vertex Buffers. Mike Bailey. Computer Graphics VertexBuffers.pptx

Vertex Buffers. Mike Bailey. Computer Graphics VertexBuffers.pptx 1 Vertex Buffers This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Mike Bailey mjb@cs.oregonstate.edu VertexBuffers.pptx What is a Vertex

More information

Vertex Buffers. Mike Bailey. What is a Vertex Buffer?

Vertex Buffers. Mike Bailey. What is a Vertex Buffer? Vertex Buffers This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Mike Bailey mjb@cs.oregonstate.edu VertexBuffers.pptx What is a Vertex Buffer?

More information

Keeping your GPU fed without getting bitten

Keeping your GPU fed without getting bitten Keeping your GPU fed without getting bitten Tobias Hector May 2017 Copyright Khronos Group 2017 - Page 1 Introduction You have delicious draw calls - Yummy! Copyright Khronos Group 2017 - Page 2 Introduction

More information

Queues and Command Buffers

Queues and Command Buffers 1 s and s This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Mike Bailey mjb@cs.oregonstate.edu sandcommandbuffers.pptx Vulkan: Overall Block

More information

Keeping your GPU fed without getting bitten

Keeping your GPU fed without getting bitten Copyright Khronos Group 2016 - Page 150 Keeping your GPU fed without getting bitten Tobias Hector May 2016 Copyright Khronos Group 2016 - Page 151 Introduction You have delicious draw calls - Yummy! Copyright

More information

Queues and Command Buffers

Queues and Command Buffers 1 s and Command Buffers This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Mike Bailey mjb@cs.oregonstate.edu sandcommandbuffers.pptx Vulkan:

More information

Vulkan Debugging By Raja Petroff

Vulkan Debugging By Raja Petroff OpenGL vs. Vulkan Vulkan Debugging By Raja Petroff OpenGL Pros: Error checking built in Cons: More overhead, adds weight Vulkan Pros: Built for max performance Cons: Debugging optional, takes some work

More information

Vulkan Debug Utilities

Vulkan Debug Utilities Vulkan Debug Utilities A Vulkan Extension Tutorial Mark Young, LunarG Introduction The Vulkan API is now two years old, and as with all things it is showing areas that require improvement. Debugging is

More information

9/19/2018. Introduction. Acknowledgements. What Prompted the Move to Vulkan? Who was the original Vulcan? Why is it so important to keep the GPU Busy?

9/19/2018. Introduction. Acknowledgements. What Prompted the Move to Vulkan? Who was the original Vulcan? Why is it so important to keep the GPU Busy? 1 Acknowledgements 2 Introduction First of all, thanks to the inaugural class of 19 students who braved new, unrefined, and just-in-time course materials to take the first Vulkan class at Oregon State

More information

VULKAN-HPP. Markus Tavenrath,

VULKAN-HPP. Markus Tavenrath, VULKAN-HPP Markus Tavenrath, 2016-10-21 WHAT IS VULKAN-HPP Vulkan-Hpp is an autogenerated C++11 binding for Vulkan with the following goals 1. Improve error detection at compile time 2. Shorten source

More information

Love is not rude, is not selfish, and does not get upset with others. Reading BMP Files

Love is not rude, is not selfish, and does not get upset with others. Reading BMP Files 33 Love is not rude, is not selfish, and does not get upset with others. Reading BMP Files When you look at the BMP file format closely, you can find that BMP stores palette information in it. So in order

More information

lectures/7/src7/bmp.h /**************************************************************************** * bmp.h * Computer Science 50 * Problem Set 5

lectures/7/src7/bmp.h /**************************************************************************** * bmp.h * Computer Science 50 * Problem Set 5 lectures/7/src7/bmp.h 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47.

More information

Vulkan C++ Markus Tavenrath, Senior DevTech Software Engineer Professional Visualization

Vulkan C++ Markus Tavenrath, Senior DevTech Software Engineer Professional Visualization Vulkan C++ Markus Tavenrath, Senior DevTech Software Engineer Professional Visualization Who am I? Markus Tavenrath Senior Dev Tech Software Engineer - Professional Visualization Joined NVIDIA 8 years

More information

Vulkan Validation Layers Deep Dive Sept 27, 2016

Vulkan Validation Layers Deep Dive Sept 27, 2016 Copyright Khronos Group 2016 - Page 1 Karl Schultz LunarG, Inc Vulkan Validation Layers Deep Dive Sept 27, 2016 Copyright Khronos Group 2016 - Page 2 Agenda Basic Vulkan Application Architecture Why Use

More information

This is not yellow. Image Files - Center for Graphics and Geometric Computing, Technion 2

This is not yellow. Image Files - Center for Graphics and Geometric Computing, Technion 2 1 Image Files This is not yellow Image Files - Center for Graphics and Geometric Computing, Technion 2 Common File Formats Need a standard to store images Raster data Photos Synthetic renderings Vector

More information

Common File Formats. Need a standard to store images Raster data Photos Synthetic renderings. Vector Graphic Illustrations Fonts

Common File Formats. Need a standard to store images Raster data Photos Synthetic renderings. Vector Graphic Illustrations Fonts 1 Image Files Common File Formats Need a standard to store images Raster data Photos Synthetic renderings Vector Graphic Illustrations Fonts Bitmap Format - Center for Graphics and Geometric Computing,

More information

Lecture Coding Theory. Source Coding. Image and Video Compression. Images: Wikipedia

Lecture Coding Theory. Source Coding. Image and Video Compression. Images: Wikipedia Lecture Coding Theory Source Coding Image and Video Compression Images: Wikipedia Entropy Coding: Unary Coding Golomb Coding Static Huffman Coding Adaptive Huffman Coding Arithmetic Coding Run Length Encoding

More information

GLM. Mike Bailey. What is GLM?

GLM. Mike Bailey. What is GLM? 1 GLM This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Mike Bailey mjb@cs.oregonstate.edu GLM.pptx What is GLM? 2 GLM is a set of C++ classes

More information

11/19/2018. Shaders and SPIR-V. The Shaders View of the Basic Computer Graphics Pipeline. Mike Bailey. Vulkan: GLSL Differences from OpenGL

11/19/2018. Shaders and SPIR-V. The Shaders View of the Basic Computer Graphics Pipeline. Mike Bailey. Vulkan: GLSL Differences from OpenGL 1 The Shaders View of the Basic Pipeline 2 Shaders and SPIR-V In general, you want to have a vertex and fragment shader as a minimum. A missing stage is OK. The output from one stage becomes the input

More information

CSI 402 Lecture 2 Working with Files (Text and Binary)

CSI 402 Lecture 2 Working with Files (Text and Binary) CSI 402 Lecture 2 Working with Files (Text and Binary) 1 / 30 AQuickReviewofStandardI/O Recall that #include allows use of printf and scanf functions Example: int i; scanf("%d", &i); printf("value

More information

BMP Graphics File Formats

BMP Graphics File Formats BMP Graphics File Formats This topic describes the graphics-file formats used by the Microsoft Windows operating system. Graphics files include bitmap files, icon-resource files, and cursor-resource files.

More information

CS 261 Fall Mike Lam, Professor. Structs and I/O

CS 261 Fall Mike Lam, Professor. Structs and I/O CS 261 Fall 2018 Mike Lam, Professor Structs and I/O Typedefs A typedef is a way to create a new type name Basically a synonym for another type Useful for shortening long types or providing more meaningful

More information

Vulkan on Android: Gotchas and best practices

Vulkan on Android: Gotchas and best practices Frederic Garnier, Inae Kim Galaxy GameDev, Samsung Electronics Vulkan on Android: Gotchas and best practices f.garnier@samsung.com inae13.kim@samsung.com Vulkan on Android: Gotchas and best practices Pipeline

More information

2016 Seoul DevU Pipeline Cache Object. Bill Licea-Kane Engineer, Senior Staff Qualcomm Technologies, Inc

2016 Seoul DevU Pipeline Cache Object. Bill Licea-Kane Engineer, Senior Staff Qualcomm Technologies, Inc 2016 Seoul DevU Pipeline Cache Object Bill Licea-Kane Engineer, Senior Staff Qualcomm Technologies, Inc. 2016-10-21 Our application requires many many many Pipeline State Objects. Creation time is a huge

More information

PROGRAMMAZIONE I A.A. 2017/2018

PROGRAMMAZIONE I A.A. 2017/2018 PROGRAMMAZIONE I A.A. 2017/2018 INPUT/OUTPUT INPUT AND OUTPUT Programs must be able to write data to files or to physical output devices such as displays or printers, and to read in data from files or

More information

Introduction. Mike Bailey. Computer Graphics Intro.pptx

Introduction. Mike Bailey. Computer Graphics Intro.pptx 1 Introduction This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Mike Bailey mjb@cs.oregonstate.edu Intro.pptx Acknowledgements 2 First of

More information

Graphics File Formats

Graphics File Formats Graphics File Formats This topic describes the graphics-file formats used by the Microsoft Windows operating system. Graphics files include bitmap files, icon-resource files, and cursor-resource files.

More information

Input/Output and the Operating Systems

Input/Output and the Operating Systems Input/Output and the Operating Systems Fall 2015 Jinkyu Jeong (jinkyu@skku.edu) 1 I/O Functions Formatted I/O printf( ) and scanf( ) fprintf( ) and fscanf( ) sprintf( ) and sscanf( ) int printf(const char*

More information

The GLSL API. Mike Bailey. Oregon State University. Geometry Shader. Program. The GLSL Shader-creation Process. create. compile. Vertex.

The GLSL API. Mike Bailey. Oregon State University. Geometry Shader. Program. The GLSL Shader-creation Process. create. compile. Vertex. The GLSL API Mike Bailey Oregon State University Program The GLSL -creation Process create compile Source read Source read Program link Use create compile Source read create compile 1 Initializing the

More information

The OpenGL Mathematics (GLM) Library. What is GLM?

The OpenGL Mathematics (GLM) Library. What is GLM? 1 The OpenGL Mathematics (GLM) Library This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Mike Bailey mjb@cs.oregonstate.edu GLM.pptx What

More information

The OpenGL Mathematics (GLM) Library

The OpenGL Mathematics (GLM) Library 1 The OpenGL Mathematics (GLM) Library This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License Mike Bailey mjb@cs.oregonstate.edu GLM.pptx What

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

Lecture 8: Structs & File I/O

Lecture 8: Structs & File I/O ....... \ \ \ / / / / \ \ \ \ / \ / \ \ \ V /,----' / ^ \ \.--..--. / ^ \ `--- ----` / ^ \. ` > < / /_\ \. ` / /_\ \ / /_\ \ `--' \ /. \ `----. / \ \ '--' '--' / \ / \ \ / \ / / \ \ (_ ) \ (_ ) / / \ \

More information

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

CSC209H Lecture 3. Dan Zingaro. January 21, 2015 CSC209H Lecture 3 Dan Zingaro January 21, 2015 Streams (King 22.1) Stream: source of input or destination for output We access a stream through a file pointer (FILE *) Three streams are available without

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

Review Topics. Final Exam Review Slides

Review Topics. Final Exam Review Slides Review Topics Final Exam Review Slides!! Transistors and Gates! Combinational Logic! LC-3 Programming!! Original slides from Gregory Byrd, North Carolina State University Modified slides by Chris Wilcox,

More information

2009 S2 COMP File Operations

2009 S2 COMP File Operations 2009 S2 COMP1921 9. File Operations Oliver Diessel odiessel@cse.unsw.edu.au Last updated: 16:00 22 Sep 2009 9. File Operations Topics to be covered: Streams Text file operations Binary file operations

More information

CSE 333 Midterm Exam Sample Solution 7/28/14

CSE 333 Midterm Exam Sample Solution 7/28/14 Question 1. (20 points) C programming. For this question implement a C function contains that returns 1 (true) if a given C string appears as a substring of another C string starting at a given position.

More information

Kurt Schmidt. October 30, 2018

Kurt Schmidt. October 30, 2018 to Structs Dept. of Computer Science, Drexel University October 30, 2018 Array Objectives to Structs Intended audience: Student who has working knowledge of Python To gain some experience with a statically-typed

More information

CSci 4061 Introduction to Operating Systems. Input/Output: High-level

CSci 4061 Introduction to Operating Systems. Input/Output: High-level CSci 4061 Introduction to Operating Systems Input/Output: High-level I/O Topics First, cover high-level I/O Next, talk about low-level device I/O I/O not part of the C language! High-level I/O Hide device

More information

Detecting Errors in the Dual Port TPU RAM (DPTRAM) Module

Detecting Errors in the Dual Port TPU RAM (DPTRAM) Module Freescale Semiconductor Order this document by: AN2192/D Detecting Errors in the Dual Port TPU RAM (DPTRAM) Module by Jeff Loeliger Rev. 0, 10 September 2001 1 Overview The integrity of the data in the

More information

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community http://csc.cs.rit.edu History and Evolution of Programming Languages 1. Explain the relationship between machine

More information

Lecture 7: file I/O, more Unix

Lecture 7: file I/O, more Unix CIS 330: / / / / (_) / / / / _/_/ / / / / / \/ / /_/ / `/ \/ / / / _/_// / / / / /_ / /_/ / / / / /> < / /_/ / / / / /_/ / / / /_/ / / / / / \ /_/ /_/_/_/ _ \,_/_/ /_/\,_/ \ /_/ \ //_/ /_/ Lecture 7: file

More information

Vulkan Subpasses. or The Frame Buffer is Lava. Andrew Garrard Samsung R&D Institute UK. UK Khronos Chapter meet, May 2016

Vulkan Subpasses. or The Frame Buffer is Lava. Andrew Garrard Samsung R&D Institute UK. UK Khronos Chapter meet, May 2016 Vulkan Subpasses or The Frame Buffer is Lava Andrew Garrard Samsung R&D Institute UK Vulkan: Making use of the GPU more efficient Vulkan aims to reduce the overheads of keeping the GPU busy Vulkan subpasses

More information

. DRAFT version 0.681

. DRAFT version 0.681 . . D R ve A r F 0. sio T 68 n 1 VULKAN GRAPHICS API IN 20 MINUTES (Coffee Break Series) Kenwright Copyright c 2016 Kenwright All rights reserved. No part of this book may be used or reproduced in any

More information

Tizen 3.0 's Window System Integration Layer of OpenGLES/EGL & Vulkan Driver

Tizen 3.0 's Window System Integration Layer of OpenGLES/EGL & Vulkan Driver Tizen 3.0 's Window System Integration Layer of OpenGLES/EGL & Vulkan Driver (libtpl-egl, vulkan-wsi-tizen) Mun Gwan-gyeong Software R&D Center Samsung Electronics Agenda Tizen 3.0 Window System Architecture

More information

NVIDIA RTX: Enabling Ray Tracing in Vulkan. Nuno Subtil, Sr. Devtech Engineer / Eric Werness, Sr. System Software Engineer March 27, 2018

NVIDIA RTX: Enabling Ray Tracing in Vulkan. Nuno Subtil, Sr. Devtech Engineer / Eric Werness, Sr. System Software Engineer March 27, 2018 NVIDIA RTX: Enabling Ray Tracing in Vulkan Nuno Subtil, Sr. Devtech Engineer / Eric Werness, Sr. System Software Engineer March 27, 2018 Ray tracing vs. rasterization Overview How did we get here? Real-time

More information

File IO and command line input CSE 2451

File IO and command line input CSE 2451 File IO and command line input CSE 2451 File functions Open/Close files fopen() open a stream for a file fclose() closes a stream One character at a time: fgetc() similar to getchar() fputc() similar to

More information

File I/O. Preprocessor Macros

File I/O. Preprocessor Macros Computer Programming File I/O. Preprocessor Macros Marius Minea marius@cs.upt.ro 4 December 2017 Files and streams A file is a data resource on persistent storage (e.g. disk). File contents are typically

More information

a = ^ ^ ^ ^ ^ ^ ^ b = c = a^b =

a = ^ ^ ^ ^ ^ ^ ^ b = c = a^b = a = b = ^ ^ ^ ^ ^ ^ ^ ^ c=a^b= & a&b a b ^ a^b &= a &= b = a = b ^= a ^= b >b >>= a >>= b

More information

System Software Experiment 1 Lecture 7

System Software Experiment 1 Lecture 7 System Software Experiment 1 Lecture 7 spring 2018 Jinkyu Jeong ( jinkyu@skku.edu) Computer Systems Laboratory Sungyunkwan University http://csl.skku.edu SSE3032: System Software Experiment 1, Spring 2018

More information

CSCI 171 Chapter Outlines

CSCI 171 Chapter Outlines Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures

More information

CS1003: Intro to CS, Summer 2008

CS1003: Intro to CS, Summer 2008 CS1003: Intro to CS, Summer 2008 Lab #07 Instructor: Arezu Moghadam arezu@cs.columbia.edu 6/25/2008 Recap Pointers Structures 1 Pointer Arithmetic (exercise) What do the following return? given > char

More information

A Crash Course in C. Steven Reeves

A Crash Course in C. Steven Reeves A Crash Course in C Steven Reeves This class will rely heavily on C and C++. As a result this section will help students who are not familiar with C or who need a refresher. By the end of this section

More information

Content. Input Output Devices File access Function of File I/O Redirection Command-line arguments

Content. Input Output Devices File access Function of File I/O Redirection Command-line arguments File I/O Content Input Output Devices File access Function of File I/O Redirection Command-line arguments UNIX and C language C is a general-purpose, high-level language that was originally developed by

More information

Philip Calderon CSE 520 Lab 3 Color Shader

Philip Calderon CSE 520 Lab 3 Color Shader Philip Calderon CSE 520 Lab 3 Color Shader Summary: The purpose of lab 4 is to produce a pyramid tetrahedron that we are able to rotate it when clicked. Part 1: Color Tetrahedron Part 2: Rotation to show

More information

Input / Output Functions

Input / Output Functions CSE 2421: Systems I Low-Level Programming and Computer Organization Input / Output Functions Presentation G Read/Study: Reek Chapter 15 Gojko Babić 10-03-2018 Input and Output Functions The stdio.h contain

More information

TODO. parse float input update outfile s header info resize horizontally remember padding! resize vertically

TODO. parse float input update outfile s header info resize horizontally remember padding! resize vertically resize TODO parse float input update outfile s header info resize horizontally remember padding! resize vertically copy.c parses int input opens a file updates header info for outfile reads each scanline,

More information

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection 1 Files 1.1 File functions Opening Files : The function fopen opens a file and returns a FILE pointer. FILE *fopen( const char * filename, const char * mode ); The allowed modes for fopen are as follows

More information

UNIT-V CONSOLE I/O. This section examines in detail the console I/O functions.

UNIT-V CONSOLE I/O. This section examines in detail the console I/O functions. UNIT-V Unit-5 File Streams Formatted I/O Preprocessor Directives Printf Scanf A file represents a sequence of bytes on the disk where a group of related data is stored. File is created for permanent storage

More information

CS240: Programming in C

CS240: Programming in C CS240: Programming in C Lecture 13 si 14: Unix interface for working with files. Cristina Nita-Rotaru Lecture 13/Fall 2013 1 Working with Files (I/O) File system: specifies how the information is organized

More information

CS242: Object-Oriented Design and Programming

CS242: Object-Oriented Design and Programming CS242: Object-Oriented Design and Programming Program Assignment 5 Part 1 (Linked List Timer Queue) Due Tuesday, March 18 th ; 1997 Part 2 (Heap Timer Queue) Due Tuesday, April 1 st ; 1997) A Timer Queue

More information

Vulkan: Mark My DWORDS

Vulkan: Mark My DWORDS Vulkan: Mark My DWORDS Hai Nguyen / Google Vancouver, August 2018 Copyright 2018 The Khronos Group Inc. - Page 1 Agenda Overview Getting Started Marking Buffers Viewing Markers How Is This Useful? Practical

More information

Files and Streams Opening and Closing a File Reading/Writing Text Reading/Writing Raw Data Random Access Files. C File Processing CS 2060

Files and Streams Opening and Closing a File Reading/Writing Text Reading/Writing Raw Data Random Access Files. C File Processing CS 2060 CS 2060 Files and Streams Files are used for long-term storage of data (on a hard drive rather than in memory). Files and Streams Files are used for long-term storage of data (on a hard drive rather than

More information

UNIX System Programming

UNIX System Programming File I/O 경희대학교컴퓨터공학과 조진성 UNIX System Programming File in UNIX n Unified interface for all I/Os in UNIX ü Regular(normal) files in file system ü Special files for devices terminal, keyboard, mouse, tape,

More information

C programming basics T3-1 -

C programming basics T3-1 - C programming basics T3-1 - Outline 1. Introduction 2. Basic concepts 3. Functions 4. Data types 5. Control structures 6. Arrays and pointers 7. File management T3-2 - 3.1: Introduction T3-3 - Review of

More information

COMP26120: Algorithms and Imperative Programming. Lecture 5: Program structuring, Java vs. C, and common mistakes

COMP26120: Algorithms and Imperative Programming. Lecture 5: Program structuring, Java vs. C, and common mistakes COMP26120: Algorithms and Imperative Programming Lecture 5: Program structuring, Java vs. C, and common mistakes Lecture outline Program structuring Functions (defining a functions, passing arguments and

More information

Matlab? Chapter 3-4 Matlab and IPT Basics. Working Environment. Matlab Demo. Array. Data Type. MATLAB Desktop:

Matlab? Chapter 3-4 Matlab and IPT Basics. Working Environment. Matlab Demo. Array. Data Type. MATLAB Desktop: Matlab? Lecture Slides ME 4060 Machine Vision and Vision-based Control Chapter 3-4 Matlab and IPT Basics By Dr. Debao Zhou 1 MATric LABoratory data analysis, prototype and visualization Matrix operation

More information

Standard C Library Functions

Standard C Library Functions Demo lecture slides Although I will not usually give slides for demo lectures, the first two demo lectures involve practice with things which you should really know from G51PRG Since I covered much of

More information

#include <tobii/tobii.h> char const* tobii_error_message( tobii_error_t error );

#include <tobii/tobii.h> char const* tobii_error_message( tobii_error_t error ); tobii.h Thread safety The tobii.h header file collects the core API functions of stream engine. It contains functions to initialize the API and establish a connection to a tracker, as well as enumerating

More information

Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island Data Types Basic Types Enumerated types The type void Derived types

More information

CMPE-013/L. File I/O. File Processing. Gabriel Hugh Elkaim Winter File Processing. Files and Streams. Outline.

CMPE-013/L. File I/O. File Processing. Gabriel Hugh Elkaim Winter File Processing. Files and Streams. Outline. CMPE-013/L Outline File Processing File I/O Gabriel Hugh Elkaim Winter 2014 Files and Streams Open and Close Files Read and Write Sequential Files Read and Write Random Access Files Read and Write Random

More information

THE C STANDARD LIBRARY & MAKING YOUR OWN LIBRARY. ISA 563: Fundamentals of Systems Programming

THE C STANDARD LIBRARY & MAKING YOUR OWN LIBRARY. ISA 563: Fundamentals of Systems Programming THE C STANDARD LIBRARY & MAKING YOUR OWN LIBRARY ISA 563: Fundamentals of Systems Programming Announcements Homework 2 posted Homework 1 due in two weeks Typo on HW1 (definition of Fib. Sequence incorrect)

More information

1 MMOIMG INTRODUCTION 1

1 MMOIMG INTRODUCTION 1 1 MMOIMG INTRODUCTION 1 1*. Introduction. This program reads a binary mmo file output by the MMIXAL processor and extracts from it an image file. The image file will contain a true image of the MMIX memory

More information

Bringing Vulkan to VR. Cass Everitt, Oculus

Bringing Vulkan to VR. Cass Everitt, Oculus Bringing Vulkan to VR Cass Everitt, Oculus A Presentation in Two Acts The Graphics-API-Agnostic Design of the VrApi The Vulkan-Samples atw Sample Family as Proving Grounds Act One The Graphics-API-Agnostic

More information

Unit 6 Files. putchar(ch); ch = getc (fp); //Reads single character from file and advances position to next character

Unit 6 Files. putchar(ch); ch = getc (fp); //Reads single character from file and advances position to next character 1. What is File management? In real life, we want to store data permanently so that later on we can retrieve it and reuse it. A file is a collection of bytes stored on a secondary storage device like hard

More information

- It computes the Standard Deviation by calculating the difference of each channel (R,G,B and A) of a pixel.

- It computes the Standard Deviation by calculating the difference of each channel (R,G,B and A) of a pixel. Standard Deviation: It is common to find comparison of two bitmaps in Image Processing Development. Comparison of two bitmaps means how each pixel of image1 is different from corresponding pixel of image2

More information

ECE264 Spring 2014 Exam 2, March 11, 2014

ECE264 Spring 2014 Exam 2, March 11, 2014 ECE264 Spring 2014 Exam 2, March 11, 2014 In signing this statement, I hereby certify that the work on this exam is my own and that I have not copied the work of any other student while completing it.

More information

OpenACC. Arthur Lei, Michelle Munteanu, Michael Papadopoulos, Philip Smith

OpenACC. Arthur Lei, Michelle Munteanu, Michael Papadopoulos, Philip Smith OpenACC Arthur Lei, Michelle Munteanu, Michael Papadopoulos, Philip Smith 1 Introduction For this introduction, we are assuming you are familiar with libraries that use a pragma directive based structure,

More information

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6 1. What is File management? In real life, we want to store data permanently so that later on we can retrieve it and reuse it. A file is a collection of bytes stored on a secondary storage device like hard

More information

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files CS113: Lecture 7 Topics: The C Preprocessor I/O, Streams, Files 1 Remember the name: Pre-processor Most commonly used features: #include, #define. Think of the preprocessor as processing the file so as

More information

Mode Meaning r Opens the file for reading. If the file doesn't exist, fopen() returns NULL.

Mode Meaning r Opens the file for reading. If the file doesn't exist, fopen() returns NULL. Files Files enable permanent storage of information C performs all input and output, including disk files, by means of streams Stream oriented data files are divided into two categories Formatted data

More information

25.2 Opening and Closing a File

25.2 Opening and Closing a File Lecture 32 p.1 Faculty of Computer Science, Dalhousie University CSCI 2132 Software Development Lecture 32: Dynamically Allocated Arrays 26-Nov-2018 Location: Chemistry 125 Time: 12:35 13:25 Instructor:

More information

CSE 12 Spring 2016 Week One, Lecture Two

CSE 12 Spring 2016 Week One, Lecture Two CSE 12 Spring 2016 Week One, Lecture Two Homework One and Two: hw2: Discuss in section today - Introduction to C - Review of basic programming principles - Building from fgetc and fputc - Input and output

More information

Getting Familiar with CCN

Getting Familiar with CCN Getting Familiar with CCN 1 Project Goal In this project you will experiment with simple client/server programs in CCN to familiarize yourselves with the CCN basics. You will compile, run, and answer the

More information

Parallel Processing Neural Networks on SIMD/GPU Architectures by Derek Kern CSC7551, December 8th, 2011

Parallel Processing Neural Networks on SIMD/GPU Architectures by Derek Kern CSC7551, December 8th, 2011 Parallel Processing Neural Networks on SIMD/GPU Architectures by Derek Kern CSC7551, December 8th, 2011 Project Description Neural networks can often have hundreds, if not thousands of neurons when used

More information

211: Computer Architecture Summer 2016

211: Computer Architecture Summer 2016 211: Computer Architecture Summer 2016 Liu Liu Topic: C Programming Data Representation I/O: - (example) cprintf.c Memory: - memory address - stack / heap / constant space - basic data layout Pointer:

More information

File I/O. Arash Rafiey. November 7, 2017

File I/O. Arash Rafiey. November 7, 2017 November 7, 2017 Files File is a place on disk where a group of related data is stored. Files File is a place on disk where a group of related data is stored. C provides various functions to handle files

More information

pset 4: Forensics Zamyla Chan

pset 4: Forensics Zamyla Chan pset 4: Forensics Zamyla Chan zamyla@cs50.net Toolbox update50 File I/O copy.c bitmaps padding! JPEGs pset 4 0. A Section of Questions 1. Whodunit 2. Resize 3. Recover File I/O Toolbox fopen fread fwrite

More information

CSci 4061 Introduction to Operating Systems. Programs in C/Unix

CSci 4061 Introduction to Operating Systems. Programs in C/Unix CSci 4061 Introduction to Operating Systems Programs in C/Unix Today Basic C programming Follow on to recitation Structure of a C program A C program consists of a collection of C functions, structs, arrays,

More information

C Syntax Arrays and Loops Math Strings Structures Pointers File I/O. Final Review CS Prof. Jonathan Ventura. Prof. Jonathan Ventura Final Review

C Syntax Arrays and Loops Math Strings Structures Pointers File I/O. Final Review CS Prof. Jonathan Ventura. Prof. Jonathan Ventura Final Review CS 2060 Variables Variables are statically typed. Variables must be defined before they are used. You only specify the type name when you define the variable. int a, b, c; float d, e, f; char letter; //

More information

CS61, Fall 2012 Section 2 Notes

CS61, Fall 2012 Section 2 Notes CS61, Fall 2012 Section 2 Notes (Week of 9/24-9/28) 0. Get source code for section [optional] 1: Variable Duration 2: Memory Errors Common Errors with memory and pointers Valgrind + GDB Common Memory Errors

More information