blob: e460f9642dfe87be9c260efdfc83d3262194d513 [file] [log] [blame]
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -07001#!/usr/bin/python3 -i
2#
Mark Lobodzinski733f7f42017-01-10 11:42:22 -07003# Copyright (c) 2015-2017 The Khronos Group Inc.
4# Copyright (c) 2015-2017 Valve Corporation
5# Copyright (c) 2015-2017 LunarG, Inc.
6# Copyright (c) 2015-2017 Google Inc.
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -07007#
8# Licensed under the Apache License, Version 2.0 (the "License");
9# you may not use this file except in compliance with the License.
10# You may obtain a copy of the License at
11#
12# http://www.apache.org/licenses/LICENSE-2.0
13#
14# Unless required by applicable law or agreed to in writing, software
15# distributed under the License is distributed on an "AS IS" BASIS,
16# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17# See the License for the specific language governing permissions and
18# limitations under the License.
19#
20# Author: Mark Lobodzinski <mark@lunarg.com>
Mark Lobodzinskic67efd02017-01-04 09:16:00 -070021# Author: Tobin Ehlis <tobine@google.com>
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070022
23import os,re,sys
24import xml.etree.ElementTree as etree
25from generator import *
26from collections import namedtuple
Mark Lobodzinski62f71562017-10-24 13:41:18 -060027from common_codegen import *
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070028
29#
30# HelperFileOutputGeneratorOptions - subclass of GeneratorOptions.
31class HelperFileOutputGeneratorOptions(GeneratorOptions):
32 def __init__(self,
33 filename = None,
34 directory = '.',
35 apiname = None,
36 profile = None,
37 versions = '.*',
38 emitversions = '.*',
39 defaultExtensions = None,
40 addExtensions = None,
41 removeExtensions = None,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060042 emitExtensions = None,
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070043 sortProcedure = regSortFeatures,
44 prefixText = "",
45 genFuncPointers = True,
46 protectFile = True,
47 protectFeature = True,
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070048 apicall = '',
49 apientry = '',
50 apientryp = '',
51 alignFuncParam = 0,
52 library_name = '',
Mark Lobodzinski62f71562017-10-24 13:41:18 -060053 expandEnumerants = True,
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070054 helper_file_type = ''):
55 GeneratorOptions.__init__(self, filename, directory, apiname, profile,
56 versions, emitversions, defaultExtensions,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060057 addExtensions, removeExtensions, emitExtensions, sortProcedure)
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070058 self.prefixText = prefixText
59 self.genFuncPointers = genFuncPointers
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070060 self.protectFile = protectFile
61 self.protectFeature = protectFeature
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070062 self.apicall = apicall
63 self.apientry = apientry
64 self.apientryp = apientryp
65 self.alignFuncParam = alignFuncParam
66 self.library_name = library_name
67 self.helper_file_type = helper_file_type
68#
Mark Lobodzinski46d388f2016-12-28 10:46:26 -070069# HelperFileOutputGenerator - subclass of OutputGenerator. Outputs Vulkan helper files
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070070class HelperFileOutputGenerator(OutputGenerator):
Mark Lobodzinskia3cc3612017-01-03 13:25:10 -070071 """Generate helper file based on XML element attributes"""
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070072 def __init__(self,
73 errFile = sys.stderr,
74 warnFile = sys.stderr,
75 diagFile = sys.stdout):
76 OutputGenerator.__init__(self, errFile, warnFile, diagFile)
77 # Internal state - accumulators for different inner block text
Mark Lobodzinski5380d132016-12-28 14:45:34 -070078 self.enum_output = '' # string built up of enum string routines
79 self.struct_size_h_output = '' # string built up of struct size header output
80 self.struct_size_c_output = '' # string built up of struct size source output
Mark Lobodzinski46d388f2016-12-28 10:46:26 -070081 # Internal state - accumulators for different inner block text
Mark Lobodzinski46d388f2016-12-28 10:46:26 -070082 self.structNames = [] # List of Vulkan struct typenames
83 self.structTypes = dict() # Map of Vulkan struct typename to required VkStructureType
Mark Lobodzinski46d388f2016-12-28 10:46:26 -070084 self.structMembers = [] # List of StructMemberData records for all Vulkan structs
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -060085 self.object_types = [] # List of all handle types
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -060086 self.debug_report_object_types = [] # Handy copy of debug_report_object_type enum data
Mark Young1ded24b2017-05-30 14:53:50 -060087 self.core_object_types = [] # Handy copy of core_object_type enum data
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -060088 self.device_extension_info = dict() # Dict of device extension name defines and ifdef values
89 self.instance_extension_info = dict() # Dict of instance extension name defines and ifdef values
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -060090
Mark Lobodzinski46d388f2016-12-28 10:46:26 -070091 # Named tuples to store struct and command data
92 self.StructType = namedtuple('StructType', ['name', 'value'])
Mark Lobodzinskic67efd02017-01-04 09:16:00 -070093 self.CommandParam = namedtuple('CommandParam', ['type', 'name', 'ispointer', 'isstaticarray', 'isconst', 'iscount', 'len', 'extstructs', 'cdecl'])
Mark Lobodzinski5380d132016-12-28 14:45:34 -070094 self.StructMemberData = namedtuple('StructMemberData', ['name', 'members', 'ifdef_protect'])
Petr Krause91f7a12017-12-14 20:57:36 +010095
96 self.custom_construct_params = {
97 # safe_VkGraphicsPipelineCreateInfo needs to know if subpass has color and\or depth\stencil attachments to use its pointers
98 'VkGraphicsPipelineCreateInfo' :
99 ', const bool uses_color_attachment, const bool uses_depthstencil_attachment',
100 # safe_VkPipelineViewportStateCreateInfo needs to know if viewport and scissor is dynamic to use its pointers
101 'VkPipelineViewportStateCreateInfo' :
102 ', const bool is_dynamic_viewports, const bool is_dynamic_scissors',
103 }
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700104 #
105 # Called once at the beginning of each run
106 def beginFile(self, genOpts):
107 OutputGenerator.beginFile(self, genOpts)
108 # User-supplied prefix text, if any (list of strings)
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700109 self.helper_file_type = genOpts.helper_file_type
110 self.library_name = genOpts.library_name
111 # File Comment
112 file_comment = '// *** THIS FILE IS GENERATED - DO NOT EDIT ***\n'
113 file_comment += '// See helper_file_generator.py for modifications\n'
114 write(file_comment, file=self.outFile)
115 # Copyright Notice
116 copyright = ''
117 copyright += '\n'
118 copyright += '/***************************************************************************\n'
119 copyright += ' *\n'
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700120 copyright += ' * Copyright (c) 2015-2017 The Khronos Group Inc.\n'
121 copyright += ' * Copyright (c) 2015-2017 Valve Corporation\n'
122 copyright += ' * Copyright (c) 2015-2017 LunarG, Inc.\n'
123 copyright += ' * Copyright (c) 2015-2017 Google Inc.\n'
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700124 copyright += ' *\n'
125 copyright += ' * Licensed under the Apache License, Version 2.0 (the "License");\n'
126 copyright += ' * you may not use this file except in compliance with the License.\n'
127 copyright += ' * You may obtain a copy of the License at\n'
128 copyright += ' *\n'
129 copyright += ' * http://www.apache.org/licenses/LICENSE-2.0\n'
130 copyright += ' *\n'
131 copyright += ' * Unless required by applicable law or agreed to in writing, software\n'
132 copyright += ' * distributed under the License is distributed on an "AS IS" BASIS,\n'
133 copyright += ' * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n'
134 copyright += ' * See the License for the specific language governing permissions and\n'
135 copyright += ' * limitations under the License.\n'
136 copyright += ' *\n'
137 copyright += ' * Author: Mark Lobodzinski <mark@lunarg.com>\n'
Mark Lobodzinskia9c963d2016-12-28 07:45:35 -0700138 copyright += ' * Author: Courtney Goeltzenleuchter <courtneygo@google.com>\n'
139 copyright += ' * Author: Tobin Ehlis <tobine@google.com>\n'
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600140 copyright += ' * Author: Chris Forbes <chrisforbes@google.com>\n'
John Zulaufde972ac2017-10-26 12:07:05 -0600141 copyright += ' * Author: John Zulauf<jzulauf@lunarg.com>\n'
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700142 copyright += ' *\n'
143 copyright += ' ****************************************************************************/\n'
144 write(copyright, file=self.outFile)
145 #
Mark Lobodzinskia3cc3612017-01-03 13:25:10 -0700146 # Write generated file content to output file
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700147 def endFile(self):
148 dest_file = ''
149 dest_file += self.OutputDestFile()
Mark Lobodzinskiafe10542017-01-03 13:22:44 -0700150 # Remove blank lines at EOF
151 if dest_file.endswith('\n'):
152 dest_file = dest_file[:-1]
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700153 write(dest_file, file=self.outFile);
154 # Finish processing in superclass
155 OutputGenerator.endFile(self)
156 #
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600157 # Override parent class to be notified of the beginning of an extension
158 def beginFeature(self, interface, emit):
159 # Start processing in superclass
160 OutputGenerator.beginFeature(self, interface, emit)
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600161 self.featureExtraProtect = GetFeatureProtect(interface)
162
Mark Lobodzinski31964ca2017-09-18 14:15:09 -0600163 if self.featureName == 'VK_VERSION_1_0' or self.featureName == 'VK_VERSION_1_1':
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600164 return
165 nameElem = interface[0][1]
166 name = nameElem.get('name')
167 if 'EXTENSION_NAME' not in name:
168 print("Error in vk.xml file -- extension name is not available")
169 if interface.get('type') == 'instance':
170 self.instance_extension_info[name] = self.featureExtraProtect
171 else:
172 self.device_extension_info[name] = self.featureExtraProtect
173 #
174 # Override parent class to be notified of the end of an extension
175 def endFeature(self):
176 # Finish processing in superclass
177 OutputGenerator.endFeature(self)
178 #
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700179 # Grab group (e.g. C "enum" type) info to output for enum-string conversion helper
180 def genGroup(self, groupinfo, groupName):
181 OutputGenerator.genGroup(self, groupinfo, groupName)
182 groupElem = groupinfo.elem
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700183 # For enum_string_header
184 if self.helper_file_type == 'enum_string_header':
Mark Lobodzinski824ce642016-12-28 08:49:46 -0700185 value_list = []
186 for elem in groupElem.findall('enum'):
187 if elem.get('supported') != 'disabled':
188 item_name = elem.get('name')
Mark Lobodzinskic8d02242017-09-28 15:12:02 -0600189 # Avoid duplicates
190 if item_name not in value_list:
191 value_list.append(item_name)
Mark Lobodzinski824ce642016-12-28 08:49:46 -0700192 if value_list is not None:
193 self.enum_output += self.GenerateEnumStringConversion(groupName, value_list)
Mark Young1ded24b2017-05-30 14:53:50 -0600194 elif self.helper_file_type == 'object_types_header':
195 if groupName == 'VkDebugReportObjectTypeEXT':
196 for elem in groupElem.findall('enum'):
197 if elem.get('supported') != 'disabled':
198 item_name = elem.get('name')
199 self.debug_report_object_types.append(item_name)
200 elif groupName == 'VkObjectType':
201 for elem in groupElem.findall('enum'):
202 if elem.get('supported') != 'disabled':
203 item_name = elem.get('name')
204 self.core_object_types.append(item_name)
205
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700206 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700207 # Called for each type -- if the type is a struct/union, grab the metadata
208 def genType(self, typeinfo, name):
209 OutputGenerator.genType(self, typeinfo, name)
210 typeElem = typeinfo.elem
211 # If the type is a struct type, traverse the imbedded <member> tags generating a structure.
212 # Otherwise, emit the tag text.
213 category = typeElem.get('category')
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600214 if category == 'handle':
215 self.object_types.append(name)
216 elif (category == 'struct' or category == 'union'):
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700217 self.structNames.append(name)
218 self.genStruct(typeinfo, name)
219 #
220 # Generate a VkStructureType based on a structure typename
221 def genVkStructureType(self, typename):
222 # Add underscore between lowercase then uppercase
223 value = re.sub('([a-z0-9])([A-Z])', r'\1_\2', typename)
224 # Change to uppercase
225 value = value.upper()
226 # Add STRUCTURE_TYPE_
227 return re.sub('VK_', 'VK_STRUCTURE_TYPE_', value)
228 #
229 # Check if the parameter passed in is a pointer
230 def paramIsPointer(self, param):
231 ispointer = False
232 for elem in param:
233 if ((elem.tag is not 'type') and (elem.tail is not None)) and '*' in elem.tail:
234 ispointer = True
235 return ispointer
236 #
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700237 # Check if the parameter passed in is a static array
238 def paramIsStaticArray(self, param):
239 isstaticarray = 0
240 paramname = param.find('name')
241 if (paramname.tail is not None) and ('[' in paramname.tail):
242 isstaticarray = paramname.tail.count('[')
243 return isstaticarray
244 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700245 # Retrieve the type and name for a parameter
246 def getTypeNameTuple(self, param):
247 type = ''
248 name = ''
249 for elem in param:
250 if elem.tag == 'type':
251 type = noneStr(elem.text)
252 elif elem.tag == 'name':
253 name = noneStr(elem.text)
254 return (type, name)
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700255 # Extract length values from latexmath. Currently an inflexible solution that looks for specific
256 # patterns that are found in vk.xml. Will need to be updated when new patterns are introduced.
257 def parseLateXMath(self, source):
258 name = 'ERROR'
259 decoratedName = 'ERROR'
260 if 'mathit' in source:
Mark Lobodzinski36c33862017-02-13 10:15:53 -0700261 # Matches expressions similar to 'latexmath:[\lceil{\mathit{rasterizationSamples} \over 32}\rceil]'
262 match = re.match(r'latexmath\s*\:\s*\[\s*\\l(\w+)\s*\{\s*\\mathit\s*\{\s*(\w+)\s*\}\s*\\over\s*(\d+)\s*\}\s*\\r(\w+)\s*\]', source)
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700263 if not match or match.group(1) != match.group(4):
264 raise 'Unrecognized latexmath expression'
265 name = match.group(2)
mizhenc27f6c72017-03-31 09:08:16 -0600266 # Need to add 1 for ceiling function; otherwise, the allocated packet
267 # size will be less than needed during capture for some title which use
268 # this in VkPipelineMultisampleStateCreateInfo. based on ceiling function
269 # definition,it is '{0}%{1}?{0}/{1} + 1:{0}/{1}'.format(*match.group(2, 3)),
270 # its value <= '{}/{} + 1'.
271 if match.group(1) == 'ceil':
272 decoratedName = '{}/{} + 1'.format(*match.group(2, 3))
273 else:
274 decoratedName = '{}/{}'.format(*match.group(2, 3))
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700275 else:
Mark Lobodzinski36c33862017-02-13 10:15:53 -0700276 # Matches expressions similar to 'latexmath : [dataSize \over 4]'
Mark Young0f183a82017-02-28 09:58:04 -0700277 match = re.match(r'latexmath\s*\:\s*\[\s*(\w+)\s*\\over\s*(\d+)\s*\]', source)
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700278 name = match.group(1)
279 decoratedName = '{}/{}'.format(*match.group(1, 2))
280 return name, decoratedName
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700281 #
282 # Retrieve the value of the len tag
283 def getLen(self, param):
284 result = None
285 len = param.attrib.get('len')
286 if len and len != 'null-terminated':
287 # For string arrays, 'len' can look like 'count,null-terminated', indicating that we
288 # have a null terminated array of strings. We strip the null-terminated from the
289 # 'len' field and only return the parameter specifying the string count
290 if 'null-terminated' in len:
291 result = len.split(',')[0]
292 else:
293 result = len
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700294 if 'latexmath' in len:
295 param_type, param_name = self.getTypeNameTuple(param)
296 len_name, result = self.parseLateXMath(len)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700297 # Spec has now notation for len attributes, using :: instead of platform specific pointer symbol
298 result = str(result).replace('::', '->')
299 return result
300 #
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700301 # Check if a structure is or contains a dispatchable (dispatchable = True) or
302 # non-dispatchable (dispatchable = False) handle
303 def TypeContainsObjectHandle(self, handle_type, dispatchable):
304 if dispatchable:
305 type_key = 'VK_DEFINE_HANDLE'
306 else:
307 type_key = 'VK_DEFINE_NON_DISPATCHABLE_HANDLE'
308 handle = self.registry.tree.find("types/type/[name='" + handle_type + "'][@category='handle']")
309 if handle is not None and handle.find('type').text == type_key:
310 return True
311 # if handle_type is a struct, search its members
312 if handle_type in self.structNames:
313 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == handle_type), None)
314 if member_index is not None:
315 for item in self.structMembers[member_index].members:
316 handle = self.registry.tree.find("types/type/[name='" + item.type + "'][@category='handle']")
317 if handle is not None and handle.find('type').text == type_key:
318 return True
319 return False
320 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700321 # Generate local ready-access data describing Vulkan structures and unions from the XML metadata
322 def genStruct(self, typeinfo, typeName):
323 OutputGenerator.genStruct(self, typeinfo, typeName)
324 members = typeinfo.elem.findall('.//member')
325 # Iterate over members once to get length parameters for arrays
326 lens = set()
327 for member in members:
328 len = self.getLen(member)
329 if len:
330 lens.add(len)
331 # Generate member info
332 membersInfo = []
333 for member in members:
334 # Get the member's type and name
335 info = self.getTypeNameTuple(member)
336 type = info[0]
337 name = info[1]
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700338 cdecl = self.makeCParamDecl(member, 1)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700339 # Process VkStructureType
340 if type == 'VkStructureType':
341 # Extract the required struct type value from the comments
342 # embedded in the original text defining the 'typeinfo' element
343 rawXml = etree.tostring(typeinfo.elem).decode('ascii')
344 result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml)
345 if result:
346 value = result.group(0)
347 else:
348 value = self.genVkStructureType(typeName)
349 # Store the required type value
350 self.structTypes[typeName] = self.StructType(name=name, value=value)
351 # Store pointer/array/string info
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700352 isstaticarray = self.paramIsStaticArray(member)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700353 membersInfo.append(self.CommandParam(type=type,
354 name=name,
355 ispointer=self.paramIsPointer(member),
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700356 isstaticarray=isstaticarray,
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700357 isconst=True if 'const' in cdecl else False,
358 iscount=True if name in lens else False,
359 len=self.getLen(member),
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600360 extstructs=self.registry.validextensionstructs[typeName] if name == 'pNext' else None,
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700361 cdecl=cdecl))
Mark Lobodzinski5380d132016-12-28 14:45:34 -0700362 self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo, ifdef_protect=self.featureExtraProtect))
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700363 #
364 # Enum_string_header: Create a routine to convert an enumerated value into a string
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700365 def GenerateEnumStringConversion(self, groupName, value_list):
366 outstring = '\n'
367 outstring += 'static inline const char* string_%s(%s input_value)\n' % (groupName, groupName)
368 outstring += '{\n'
369 outstring += ' switch ((%s)input_value)\n' % groupName
370 outstring += ' {\n'
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700371 for item in value_list:
372 outstring += ' case %s:\n' % item
373 outstring += ' return "%s";\n' % item
374 outstring += ' default:\n'
375 outstring += ' return "Unhandled %s";\n' % groupName
376 outstring += ' }\n'
377 outstring += '}\n'
378 return outstring
379 #
Mark Lobodzinski64b432f2017-07-24 16:14:16 -0600380 # Tack on a helper which, given an index into a VkPhysicalDeviceFeatures structure, will print the corresponding feature name
381 def DeIndexPhysDevFeatures(self):
382 pdev_members = None
383 for name, members, ifdef in self.structMembers:
384 if name == 'VkPhysicalDeviceFeatures':
385 pdev_members = members
386 break
387 deindex = '\n'
388 deindex += 'static const char * GetPhysDevFeatureString(uint32_t index) {\n'
389 deindex += ' const char * IndexToPhysDevFeatureString[] = {\n'
390 for feature in pdev_members:
391 deindex += ' "%s",\n' % feature.name
392 deindex += ' };\n\n'
393 deindex += ' return IndexToPhysDevFeatureString[index];\n'
394 deindex += '}\n'
395 return deindex
396 #
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700397 # Combine enum string helper header file preamble with body text and return
398 def GenerateEnumStringHelperHeader(self):
399 enum_string_helper_header = '\n'
400 enum_string_helper_header += '#pragma once\n'
401 enum_string_helper_header += '#ifdef _WIN32\n'
402 enum_string_helper_header += '#pragma warning( disable : 4065 )\n'
403 enum_string_helper_header += '#endif\n'
404 enum_string_helper_header += '\n'
405 enum_string_helper_header += '#include <vulkan/vulkan.h>\n'
406 enum_string_helper_header += '\n'
407 enum_string_helper_header += self.enum_output
Mark Lobodzinski64b432f2017-07-24 16:14:16 -0600408 enum_string_helper_header += self.DeIndexPhysDevFeatures()
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700409 return enum_string_helper_header
410 #
Mark Lobodzinski5380d132016-12-28 14:45:34 -0700411 # struct_size_header: build function prototypes for header file
412 def GenerateStructSizeHeader(self):
413 outstring = ''
414 outstring += 'size_t get_struct_chain_size(const void* struct_ptr);\n'
David Pinedob95caa02017-10-05 10:30:02 -0600415 outstring += 'size_t get_struct_size(const void* struct_ptr);\n'
Mark Lobodzinski5380d132016-12-28 14:45:34 -0700416 for item in self.structMembers:
417 lower_case_name = item.name.lower()
418 if item.ifdef_protect != None:
419 outstring += '#ifdef %s\n' % item.ifdef_protect
420 outstring += 'size_t vk_size_%s(const %s* struct_ptr);\n' % (item.name.lower(), item.name)
421 if item.ifdef_protect != None:
422 outstring += '#endif // %s\n' % item.ifdef_protect
423 outstring += '#ifdef __cplusplus\n'
424 outstring += '}\n'
425 outstring += '#endif'
426 return outstring
427 #
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700428 # Combine struct size helper header file preamble with body text and return
429 def GenerateStructSizeHelperHeader(self):
430 struct_size_helper_header = '\n'
431 struct_size_helper_header += '#ifdef __cplusplus\n'
432 struct_size_helper_header += 'extern "C" {\n'
433 struct_size_helper_header += '#endif\n'
434 struct_size_helper_header += '\n'
435 struct_size_helper_header += '#include <stdio.h>\n'
436 struct_size_helper_header += '#include <stdlib.h>\n'
437 struct_size_helper_header += '#include <vulkan/vulkan.h>\n'
438 struct_size_helper_header += '\n'
439 struct_size_helper_header += '// Function Prototypes\n'
440 struct_size_helper_header += self.GenerateStructSizeHeader()
441 return struct_size_helper_header
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -0700442 #
443 # Helper function for declaring a counter variable only once
444 def DeclareCounter(self, string_var, declare_flag):
445 if declare_flag == False:
446 string_var += ' uint32_t i = 0;\n'
447 declare_flag = True
448 return string_var, declare_flag
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700449 #
Mark Lobodzinskif36e58b2016-12-29 14:04:15 -0700450 # Build the header of the get_struct_chain_size function
451 def GenerateChainSizePreamble(self):
David Pinedob95caa02017-10-05 10:30:02 -0600452 preamble = '\nsize_t get_struct_chain_size(const void* struct_ptr) {\n'
453 preamble += ' // Use VkApplicationInfo as struct until actual type is resolved\n'
454 preamble += ' VkApplicationInfo* pNext = (VkApplicationInfo*)struct_ptr;\n'
455 preamble += ' size_t struct_size = 0;\n'
456 preamble += ' while (pNext) {\n'
457 preamble += ' switch (pNext->sType) {\n'
458 return preamble
Mark Lobodzinskif36e58b2016-12-29 14:04:15 -0700459 #
460 # Build the footer of the get_struct_chain_size function
461 def GenerateChainSizePostamble(self):
462 postamble = ' default:\n'
Mark Lobodzinskif36e58b2016-12-29 14:04:15 -0700463 postamble += ' struct_size += 0;\n'
Joey Bzdekb6875332017-10-19 14:24:05 -0600464 postamble += ' break;'
Mark Lobodzinskif36e58b2016-12-29 14:04:15 -0700465 postamble += ' }\n'
466 postamble += ' pNext = (VkApplicationInfo*)pNext->pNext;\n'
467 postamble += ' }\n'
468 postamble += ' return struct_size;\n'
David Pinedob95caa02017-10-05 10:30:02 -0600469 postamble += '}\n'
470 return postamble
471 #
472 # Build the header of the get_struct_size function
473 def GenerateStructSizePreamble(self):
474 preamble = '\nsize_t get_struct_size(const void* struct_ptr) {\n'
475 preamble += ' switch (((VkApplicationInfo*)struct_ptr)->sType) {\n'
476 return preamble
477 #
478 # Build the footer of the get_struct_size function
479 def GenerateStructSizePostamble(self):
480 postamble = ' default:\n'
David Pinedob95caa02017-10-05 10:30:02 -0600481 postamble += ' return(0);\n'
482 postamble += ' }\n'
Mark Lobodzinskif36e58b2016-12-29 14:04:15 -0700483 postamble += '}'
484 return postamble
485 #
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700486 # struct_size_helper source -- create bodies of struct size helper functions
487 def GenerateStructSizeSource(self):
David Pinedob95caa02017-10-05 10:30:02 -0600488 # Construct the bodies of the struct size functions, get_struct_chain_size(),
489 # and get_struct_size() simultaneously
490 struct_size_funcs = ''
Mark Lobodzinskif36e58b2016-12-29 14:04:15 -0700491 chain_size = self.GenerateChainSizePreamble()
David Pinedob95caa02017-10-05 10:30:02 -0600492 struct_size = self.GenerateStructSizePreamble()
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700493 for item in self.structMembers:
David Pinedob95caa02017-10-05 10:30:02 -0600494 struct_size_funcs += '\n'
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700495 lower_case_name = item.name.lower()
496 if item.ifdef_protect != None:
David Pinedob95caa02017-10-05 10:30:02 -0600497 struct_size_funcs += '#ifdef %s\n' % item.ifdef_protect
498 struct_size += '#ifdef %s\n' % item.ifdef_protect
Mark Lobodzinskif36e58b2016-12-29 14:04:15 -0700499 chain_size += '#ifdef %s\n' % item.ifdef_protect
500 if item.name in self.structTypes:
501 chain_size += ' case %s: {\n' % self.structTypes[item.name].value
502 chain_size += ' struct_size += vk_size_%s((%s*)pNext);\n' % (item.name.lower(), item.name)
503 chain_size += ' break;\n'
504 chain_size += ' }\n'
David Pinedob95caa02017-10-05 10:30:02 -0600505 struct_size += ' case %s: \n' % self.structTypes[item.name].value
506 struct_size += ' return vk_size_%s((%s*)struct_ptr);\n' % (item.name.lower(), item.name)
507 struct_size_funcs += 'size_t vk_size_%s(const %s* struct_ptr) { \n' % (item.name.lower(), item.name)
508 struct_size_funcs += ' size_t struct_size = 0;\n'
509 struct_size_funcs += ' if (struct_ptr) {\n'
510 struct_size_funcs += ' struct_size = sizeof(%s);\n' % item.name
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -0700511 counter_declared = False
512 for member in item.members:
513 vulkan_type = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
514 if member.ispointer == True:
515 if vulkan_type is not None:
516 # If this is another Vulkan structure call generated size function
517 if member.len is not None:
David Pinedob95caa02017-10-05 10:30:02 -0600518 struct_size_funcs, counter_declared = self.DeclareCounter(struct_size_funcs, counter_declared)
519 struct_size_funcs += ' for (i = 0; i < struct_ptr->%s; i++) {\n' % member.len
520 struct_size_funcs += ' struct_size += vk_size_%s(&struct_ptr->%s[i]);\n' % (member.type.lower(), member.name)
521 struct_size_funcs += ' }\n'
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -0700522 else:
David Pinedob95caa02017-10-05 10:30:02 -0600523 struct_size_funcs += ' struct_size += vk_size_%s(struct_ptr->%s);\n' % (member.type.lower(), member.name)
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -0700524 else:
525 if member.type == 'char':
526 # Deal with sizes of character strings
527 if member.len is not None:
David Pinedob95caa02017-10-05 10:30:02 -0600528 struct_size_funcs, counter_declared = self.DeclareCounter(struct_size_funcs, counter_declared)
529 struct_size_funcs += ' for (i = 0; i < struct_ptr->%s; i++) {\n' % member.len
530 struct_size_funcs += ' struct_size += (sizeof(char*) + (sizeof(char) * (1 + strlen(struct_ptr->%s[i]))));\n' % (member.name)
531 struct_size_funcs += ' }\n'
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -0700532 else:
David Pinedob95caa02017-10-05 10:30:02 -0600533 struct_size_funcs += ' struct_size += (struct_ptr->%s != NULL) ? sizeof(char)*(1+strlen(struct_ptr->%s)) : 0;\n' % (member.name, member.name)
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -0700534 else:
535 if member.len is not None:
Mark Lobodzinskif36e58b2016-12-29 14:04:15 -0700536 # Avoid using 'sizeof(void)', which generates compile-time warnings/errors
537 checked_type = member.type
538 if checked_type == 'void':
539 checked_type = 'void*'
David Pinedob95caa02017-10-05 10:30:02 -0600540 struct_size_funcs += ' struct_size += (struct_ptr->%s ) * sizeof(%s);\n' % (member.len, checked_type)
541 struct_size_funcs += ' }\n'
542 struct_size_funcs += ' return struct_size;\n'
543 struct_size_funcs += '}\n'
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700544 if item.ifdef_protect != None:
David Pinedob95caa02017-10-05 10:30:02 -0600545 struct_size_funcs += '#endif // %s\n' % item.ifdef_protect
546 struct_size += '#endif // %s\n' % item.ifdef_protect
Mark Lobodzinskif36e58b2016-12-29 14:04:15 -0700547 chain_size += '#endif // %s\n' % item.ifdef_protect
548 chain_size += self.GenerateChainSizePostamble()
David Pinedob95caa02017-10-05 10:30:02 -0600549 struct_size += self.GenerateStructSizePostamble()
550 return_value = struct_size_funcs + chain_size + struct_size;
551 return return_value
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700552 #
553 # Combine struct size helper source file preamble with body text and return
554 def GenerateStructSizeHelperSource(self):
555 struct_size_helper_source = '\n'
556 struct_size_helper_source += '#include "vk_struct_size_helper.h"\n'
557 struct_size_helper_source += '#include <string.h>\n'
558 struct_size_helper_source += '#include <assert.h>\n'
559 struct_size_helper_source += '\n'
560 struct_size_helper_source += '// Function Definitions\n'
561 struct_size_helper_source += self.GenerateStructSizeSource()
562 return struct_size_helper_source
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700563 #
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700564 # Combine safe struct helper header file preamble with body text and return
565 def GenerateSafeStructHelperHeader(self):
566 safe_struct_helper_header = '\n'
567 safe_struct_helper_header += '#pragma once\n'
568 safe_struct_helper_header += '#include <vulkan/vulkan.h>\n'
569 safe_struct_helper_header += '\n'
570 safe_struct_helper_header += self.GenerateSafeStructHeader()
571 return safe_struct_helper_header
572 #
573 # safe_struct header: build function prototypes for header file
574 def GenerateSafeStructHeader(self):
575 safe_struct_header = ''
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700576 for item in self.structMembers:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700577 if self.NeedSafeStruct(item) == True:
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700578 safe_struct_header += '\n'
579 if item.ifdef_protect != None:
580 safe_struct_header += '#ifdef %s\n' % item.ifdef_protect
581 safe_struct_header += 'struct safe_%s {\n' % (item.name)
582 for member in item.members:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700583 if member.type in self.structNames:
584 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
585 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
586 if member.ispointer:
587 safe_struct_header += ' safe_%s* %s;\n' % (member.type, member.name)
588 else:
589 safe_struct_header += ' safe_%s %s;\n' % (member.type, member.name)
590 continue
591 if member.len is not None and (self.TypeContainsObjectHandle(member.type, True) or self.TypeContainsObjectHandle(member.type, False)):
592 safe_struct_header += ' %s* %s;\n' % (member.type, member.name)
593 else:
594 safe_struct_header += '%s;\n' % member.cdecl
Petr Krause91f7a12017-12-14 20:57:36 +0100595 safe_struct_header += ' safe_%s(const %s* in_struct%s);\n' % (item.name, item.name, self.custom_construct_params.get(item.name, ''))
Mark Lobodzinski5cd08512017-09-12 09:50:25 -0600596 safe_struct_header += ' safe_%s(const safe_%s& src);\n' % (item.name, item.name)
Chris Forbesfb633832017-10-03 18:11:54 -0700597 safe_struct_header += ' safe_%s& operator=(const safe_%s& src);\n' % (item.name, item.name)
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700598 safe_struct_header += ' safe_%s();\n' % item.name
599 safe_struct_header += ' ~safe_%s();\n' % item.name
Petr Krause91f7a12017-12-14 20:57:36 +0100600 safe_struct_header += ' void initialize(const %s* in_struct%s);\n' % (item.name, self.custom_construct_params.get(item.name, ''))
601 safe_struct_header += ' void initialize(const safe_%s* src);\n' % (item.name)
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700602 safe_struct_header += ' %s *ptr() { return reinterpret_cast<%s *>(this); }\n' % (item.name, item.name)
603 safe_struct_header += ' %s const *ptr() const { return reinterpret_cast<%s const *>(this); }\n' % (item.name, item.name)
604 safe_struct_header += '};\n'
605 if item.ifdef_protect != None:
606 safe_struct_header += '#endif // %s\n' % item.ifdef_protect
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700607 return safe_struct_header
608 #
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600609 # Generate extension helper header file
610 def GenerateExtensionHelperHeader(self):
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600611
612 V_1_0_instance_extensions_promoted_to_core = [
613 'vk_khr_device_group_creation',
614 'vk_khr_external_memory_capabilities',
615 'vk_khr_external_fence_capabilities',
616 'vk_khr_external_semaphore_capabilities',
617 'vk_khr_get_physical_device_properties_2',
618 ]
619
620 V_1_0_device_extensions_promoted_to_core = [
621 'vk_khr_bind_memory_2',
622 'vk_khr_device_group',
623 'vk_khr_descriptor_update_template',
624 'vk_khr_sampler_ycbcr_conversion',
625 'vk_khr_get_memory_requirements_2',
626 'vk_khr_maintenance3',
627 'vk_khr_maintenance1',
628 'vk_khr_multiview',
629 'vk_khr_external_memory',
630 'vk_khr_external_semaphore',
631 'vk_khr_16bit_storage',
632 'vk_khr_external_fence',
633 'vk_khr_maintenance2',
634 'vk_khr_variable_pointers',
635 'vk_khr_dedicated_allocation',
636 ]
637
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600638 extension_helper_header = '\n'
639 extension_helper_header += '#ifndef VK_EXTENSION_HELPER_H_\n'
640 extension_helper_header += '#define VK_EXTENSION_HELPER_H_\n'
641 struct = '\n'
Tobin Ehlis84154d32017-06-09 15:46:14 -0600642 extension_helper_header += '#include <vulkan/vulkan.h>\n'
Tobin Ehlisd922d4c2017-06-14 09:43:04 -0600643 extension_helper_header += '#include <string.h>\n'
Tobin Ehlis84154d32017-06-09 15:46:14 -0600644 extension_helper_header += '#include <utility>\n'
645 extension_helper_header += '\n'
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600646 extension_helper_header += '\n'
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600647 extension_dict = dict()
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600648 promoted_ext_list = []
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600649 for type in ['Instance', 'Device']:
650 if type == 'Instance':
651 extension_dict = self.instance_extension_info
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600652 promoted_ext_list = V_1_0_instance_extensions_promoted_to_core
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600653 struct += 'struct InstanceExtensions { \n'
654 else:
655 extension_dict = self.device_extension_info
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600656 promoted_ext_list = V_1_0_device_extensions_promoted_to_core
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600657 struct += 'struct DeviceExtensions : public InstanceExtensions { \n'
658 for ext_name, ifdef in extension_dict.items():
659 bool_name = ext_name.lower()
660 bool_name = re.sub('_extension_name', '', bool_name)
661 struct += ' bool %s{false};\n' % bool_name
662 struct += '\n'
663 if type == 'Instance':
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600664 struct += ' uint32_t NormalizeApiVersion(uint32_t specified_version) {\n'
665 struct += ' uint32_t api_version = specified_version & ~VK_VERSION_PATCH(~0);\n'
666 struct += ' if (!(api_version == VK_API_VERSION_1_0) && !(api_version == VK_API_VERSION_1_1)) {\n'
667 struct += ' api_version = VK_API_VERSION_1_1;\n'
668 struct += ' }\n'
669 struct += ' return api_version;\n'
670 struct += ' }\n'
671 struct += '\n'
672
673 struct += ' uint32_t InitFromInstanceCreateInfo(uint32_t requested_api_version, const VkInstanceCreateInfo *pCreateInfo) {\n'
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600674 else:
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600675 struct += ' uint32_t InitFromDeviceCreateInfo(const InstanceExtensions *instance_extensions, uint32_t requested_api_version, const VkDeviceCreateInfo *pCreateInfo) {\n'
676 struct += '\n'
677
678 struct += ' static const std::vector<const char *> V_1_0_promoted_%s_extensions = {\n' % type.lower()
679 for ext_name in promoted_ext_list:
680 struct += ' %s_EXTENSION_NAME,\n' % ext_name.upper()
681 struct += ' };\n'
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600682 struct += '\n'
683 struct += ' static const std::pair<char const *, bool %sExtensions::*> known_extensions[]{\n' % type
684 for ext_name, ifdef in extension_dict.items():
685 if ifdef is not None:
686 struct += '#ifdef %s\n' % ifdef
687 bool_name = ext_name.lower()
688 bool_name = re.sub('_extension_name', '', bool_name)
689 struct += ' {%s, &%sExtensions::%s},\n' % (ext_name, type, bool_name)
690 if ifdef is not None:
691 struct += '#endif\n'
692 struct += ' };\n'
693 struct += '\n'
694 struct += ' // Initialize struct data\n'
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600695
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600696 for ext_name, ifdef in self.instance_extension_info.items():
697 bool_name = ext_name.lower()
698 bool_name = re.sub('_extension_name', '', bool_name)
699 if type == 'Device':
700 struct += ' %s = instance_extensions->%s;\n' % (bool_name, bool_name)
701 struct += '\n'
702 struct += ' for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {\n'
703 struct += ' for (auto ext : known_extensions) {\n'
704 struct += ' if (!strcmp(ext.first, pCreateInfo->ppEnabledExtensionNames[i])) {\n'
705 struct += ' this->*(ext.second) = true;\n'
706 struct += ' break;\n'
707 struct += ' }\n'
708 struct += ' }\n'
709 struct += ' }\n'
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600710 struct += ' uint32_t api_version = NormalizeApiVersion(requested_api_version);\n'
711 struct += ' if (api_version >= VK_API_VERSION_1_1) {\n'
712 struct += ' for (auto promoted_ext : V_1_0_promoted_%s_extensions) {\n' % type.lower()
713 struct += ' for (auto ext : known_extensions) {\n'
714 struct += ' if (!strcmp(ext.first, promoted_ext)) {\n'
715 struct += ' this->*(ext.second) = true;\n'
716 struct += ' break;\n'
717 struct += ' }\n'
718 struct += ' }\n'
719 struct += ' }\n'
720 struct += ' }\n'
721 struct += ' return api_version;\n'
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600722 struct += ' }\n'
723 struct += '};\n'
724 struct += '\n'
Mark Lobodzinskifc9451f2018-01-03 11:18:31 -0700725 # Output reference lists of instance/device extension names
726 struct += 'static const char * const k%sExtensionNames = \n' % type
727 for ext_name, ifdef in extension_dict.items():
728 if ifdef is not None:
729 struct += '#ifdef %s\n' % ifdef
730 struct += ' %s\n' % ext_name
731 if ifdef is not None:
732 struct += '#endif\n'
733 struct += ';\n\n'
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600734 extension_helper_header += struct
735 extension_helper_header += '\n'
736 extension_helper_header += '#endif // VK_EXTENSION_HELPER_H_\n'
737 return extension_helper_header
738 #
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600739 # Combine object types helper header file preamble with body text and return
740 def GenerateObjectTypesHelperHeader(self):
741 object_types_helper_header = '\n'
742 object_types_helper_header += '#pragma once\n'
743 object_types_helper_header += '\n'
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600744 object_types_helper_header += '#include <vulkan/vulkan.h>\n\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600745 object_types_helper_header += self.GenerateObjectTypesHeader()
746 return object_types_helper_header
747 #
748 # Object types header: create object enum type header file
749 def GenerateObjectTypesHeader(self):
Mark Young6ba8abe2017-11-09 10:37:04 -0700750 object_types_header = ''
751 object_types_header += '// Object Type enum for validation layer internal object handling\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600752 object_types_header += 'typedef enum VulkanObjectType {\n'
753 object_types_header += ' kVulkanObjectTypeUnknown = 0,\n'
754 enum_num = 1
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600755 type_list = [];
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600756
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600757 # Output enum definition as each handle is processed, saving the names to use for the conversion routine
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600758 for item in self.object_types:
759 fixup_name = item[2:]
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600760 enum_entry = 'kVulkanObjectType%s' % fixup_name
761 object_types_header += ' ' + enum_entry
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600762 object_types_header += ' = %d,\n' % enum_num
763 enum_num += 1
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600764 type_list.append(enum_entry)
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600765 object_types_header += ' kVulkanObjectTypeMax = %d,\n' % enum_num
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600766 object_types_header += '} VulkanObjectType;\n\n'
767
768 # Output name string helper
769 object_types_header += '// Array of object name strings for OBJECT_TYPE enum conversion\n'
Mark Lobodzinski8eb37422017-04-18 14:22:10 -0600770 object_types_header += 'static const char * const object_string[kVulkanObjectTypeMax] = {\n'
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600771 object_types_header += ' "Unknown",\n'
772 for item in self.object_types:
773 fixup_name = item[2:]
774 object_types_header += ' "%s",\n' % fixup_name
775 object_types_header += '};\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600776
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600777 # Output a conversion routine from the layer object definitions to the debug report definitions
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600778 object_types_header += '\n'
Mark Young1ded24b2017-05-30 14:53:50 -0600779 object_types_header += '// Helper array to get Vulkan VK_EXT_debug_report object type enum from the internal layers version\n'
Mark Lobodzinskic51dbb72017-04-13 14:25:39 -0600780 object_types_header += 'const VkDebugReportObjectTypeEXT get_debug_report_enum[] = {\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700781 object_types_header += ' VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, // kVulkanObjectTypeUnknown\n'
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600782 for object_type in type_list:
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600783 search_type = object_type.replace("kVulkanObjectType", "").lower()
784 for vk_object_type in self.debug_report_object_types:
785 target_type = vk_object_type.replace("VK_DEBUG_REPORT_OBJECT_TYPE_", "").lower()
786 target_type = target_type[:-4]
787 target_type = target_type.replace("_", "")
788 if search_type == target_type:
Mark Lobodzinskiecf0ae12017-04-13 08:36:18 -0600789 object_types_header += ' %s, // %s\n' % (vk_object_type, object_type)
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600790 break
Mark Lobodzinskiecf0ae12017-04-13 08:36:18 -0600791 object_types_header += '};\n'
Mark Young1ded24b2017-05-30 14:53:50 -0600792
793 # Output a conversion routine from the layer object definitions to the core object type definitions
794 object_types_header += '\n'
795 object_types_header += '// Helper array to get Official Vulkan VkObjectType enum from the internal layers version\n'
796 object_types_header += 'const VkObjectType get_object_type_enum[] = {\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700797 object_types_header += ' VK_OBJECT_TYPE_UNKNOWN, // kVulkanObjectTypeUnknown\n'
Mark Young1ded24b2017-05-30 14:53:50 -0600798 for object_type in type_list:
Mark Young1ded24b2017-05-30 14:53:50 -0600799 search_type = object_type.replace("kVulkanObjectType", "").lower()
800 for vk_object_type in self.core_object_types:
801 target_type = vk_object_type.replace("VK_OBJECT_TYPE_", "").lower()
802 target_type = target_type.replace("_", "")
803 if search_type == target_type:
804 object_types_header += ' %s, // %s\n' % (vk_object_type, object_type)
Mark Young1ded24b2017-05-30 14:53:50 -0600805 break
Mark Young1ded24b2017-05-30 14:53:50 -0600806 object_types_header += '};\n'
807
Mark Young6ba8abe2017-11-09 10:37:04 -0700808 # Create a function to convert from VkDebugReportObjectTypeEXT to VkObjectType
809 object_types_header += '\n'
810 object_types_header += '// Helper function to convert from VkDebugReportObjectTypeEXT to VkObjectType\n'
811 object_types_header += 'static VkObjectType convertDebugReportObjectToCoreObject(VkDebugReportObjectTypeEXT debug_report_obj){\n'
812 object_types_header += ' if (debug_report_obj == VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT) {\n'
813 object_types_header += ' return VK_OBJECT_TYPE_UNKNOWN;\n'
814 for core_object_type in self.core_object_types:
815 core_target_type = core_object_type.replace("VK_OBJECT_TYPE_", "").lower()
816 core_target_type = core_target_type.replace("_", "")
817 for dr_object_type in self.debug_report_object_types:
818 dr_target_type = dr_object_type.replace("VK_DEBUG_REPORT_OBJECT_TYPE_", "").lower()
819 dr_target_type = dr_target_type[:-4]
820 dr_target_type = dr_target_type.replace("_", "")
821 if core_target_type == dr_target_type:
822 object_types_header += ' } else if (debug_report_obj == %s) {\n' % dr_object_type
823 object_types_header += ' return %s;\n' % core_object_type
824 break
825 object_types_header += ' }\n'
826 object_types_header += ' return VK_OBJECT_TYPE_UNKNOWN;\n'
827 object_types_header += '}\n'
828
829 # Create a function to convert from VkObjectType to VkDebugReportObjectTypeEXT
830 object_types_header += '\n'
831 object_types_header += '// Helper function to convert from VkDebugReportObjectTypeEXT to VkObjectType\n'
832 object_types_header += 'static VkDebugReportObjectTypeEXT convertCoreObjectToDebugReportObject(VkObjectType core_report_obj){\n'
833 object_types_header += ' if (core_report_obj == VK_OBJECT_TYPE_UNKNOWN) {\n'
834 object_types_header += ' return VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT;\n'
835 for core_object_type in self.core_object_types:
836 core_target_type = core_object_type.replace("VK_OBJECT_TYPE_", "").lower()
837 core_target_type = core_target_type.replace("_", "")
838 for dr_object_type in self.debug_report_object_types:
839 dr_target_type = dr_object_type.replace("VK_DEBUG_REPORT_OBJECT_TYPE_", "").lower()
840 dr_target_type = dr_target_type[:-4]
841 dr_target_type = dr_target_type.replace("_", "")
842 if core_target_type == dr_target_type:
843 object_types_header += ' } else if (core_report_obj == %s) {\n' % core_object_type
844 object_types_header += ' return %s;\n' % dr_object_type
845 break
846 object_types_header += ' }\n'
847 object_types_header += ' return VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT;\n'
848 object_types_header += '}\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600849 return object_types_header
850 #
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700851 # Determine if a structure needs a safe_struct helper function
852 # That is, it has an sType or one of its members is a pointer
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700853 def NeedSafeStruct(self, structure):
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700854 if 'sType' == structure.name:
855 return True
856 for member in structure.members:
857 if member.ispointer == True:
858 return True
859 return False
860 #
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700861 # Combine safe struct helper source file preamble with body text and return
862 def GenerateSafeStructHelperSource(self):
863 safe_struct_helper_source = '\n'
864 safe_struct_helper_source += '#include "vk_safe_struct.h"\n'
865 safe_struct_helper_source += '#include <string.h>\n'
866 safe_struct_helper_source += '\n'
867 safe_struct_helper_source += self.GenerateSafeStructSource()
868 return safe_struct_helper_source
869 #
870 # safe_struct source -- create bodies of safe struct helper functions
871 def GenerateSafeStructSource(self):
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700872 safe_struct_body = []
Mark Lobodzinski560729b2017-03-06 08:59:14 -0700873 wsi_structs = ['VkXlibSurfaceCreateInfoKHR',
874 'VkXcbSurfaceCreateInfoKHR',
875 'VkWaylandSurfaceCreateInfoKHR',
876 'VkMirSurfaceCreateInfoKHR',
877 'VkAndroidSurfaceCreateInfoKHR',
878 'VkWin32SurfaceCreateInfoKHR'
879 ]
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700880 for item in self.structMembers:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700881 if self.NeedSafeStruct(item) == False:
882 continue
Mark Lobodzinski560729b2017-03-06 08:59:14 -0700883 if item.name in wsi_structs:
884 continue
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700885 if item.ifdef_protect != None:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700886 safe_struct_body.append("#ifdef %s\n" % item.ifdef_protect)
887 ss_name = "safe_%s" % item.name
888 init_list = '' # list of members in struct constructor initializer
889 default_init_list = '' # Default constructor just inits ptrs to nullptr in initializer
890 init_func_txt = '' # Txt for initialize() function that takes struct ptr and inits members
891 construct_txt = '' # Body of constuctor as well as body of initialize() func following init_func_txt
892 destruct_txt = ''
Petr Krause91f7a12017-12-14 20:57:36 +0100893
894 custom_construct_txt = {
895 # VkWriteDescriptorSet is special case because pointers may be non-null but ignored
896 'VkWriteDescriptorSet' :
897 ' switch (descriptorType) {\n'
898 ' case VK_DESCRIPTOR_TYPE_SAMPLER:\n'
899 ' case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:\n'
900 ' case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:\n'
901 ' case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:\n'
902 ' case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:\n'
903 ' if (descriptorCount && in_struct->pImageInfo) {\n'
904 ' pImageInfo = new VkDescriptorImageInfo[descriptorCount];\n'
905 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
906 ' pImageInfo[i] = in_struct->pImageInfo[i];\n'
907 ' }\n'
908 ' }\n'
909 ' break;\n'
910 ' case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:\n'
911 ' case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:\n'
912 ' case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:\n'
913 ' case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:\n'
914 ' if (descriptorCount && in_struct->pBufferInfo) {\n'
915 ' pBufferInfo = new VkDescriptorBufferInfo[descriptorCount];\n'
916 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
917 ' pBufferInfo[i] = in_struct->pBufferInfo[i];\n'
918 ' }\n'
919 ' }\n'
920 ' break;\n'
921 ' case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:\n'
922 ' case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:\n'
923 ' if (descriptorCount && in_struct->pTexelBufferView) {\n'
924 ' pTexelBufferView = new VkBufferView[descriptorCount];\n'
925 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
926 ' pTexelBufferView[i] = in_struct->pTexelBufferView[i];\n'
927 ' }\n'
928 ' }\n'
929 ' break;\n'
930 ' default:\n'
931 ' break;\n'
932 ' }\n',
Petr Kraus42f6f8d2017-12-17 17:37:33 +0100933 'VkShaderModuleCreateInfo' :
Petr Krause91f7a12017-12-14 20:57:36 +0100934 ' if (in_struct->pCode) {\n'
935 ' pCode = reinterpret_cast<uint32_t *>(new uint8_t[codeSize]);\n'
936 ' memcpy((void *)pCode, (void *)in_struct->pCode, codeSize);\n'
937 ' }\n',
938 # VkGraphicsPipelineCreateInfo is special case because its pointers may be non-null but ignored
939 'VkGraphicsPipelineCreateInfo' :
940 ' if (stageCount && in_struct->pStages) {\n'
941 ' pStages = new safe_VkPipelineShaderStageCreateInfo[stageCount];\n'
942 ' for (uint32_t i=0; i<stageCount; ++i) {\n'
943 ' pStages[i].initialize(&in_struct->pStages[i]);\n'
944 ' }\n'
945 ' }\n'
946 ' if (in_struct->pVertexInputState)\n'
947 ' pVertexInputState = new safe_VkPipelineVertexInputStateCreateInfo(in_struct->pVertexInputState);\n'
948 ' else\n'
949 ' pVertexInputState = NULL;\n'
950 ' if (in_struct->pInputAssemblyState)\n'
951 ' pInputAssemblyState = new safe_VkPipelineInputAssemblyStateCreateInfo(in_struct->pInputAssemblyState);\n'
952 ' else\n'
953 ' pInputAssemblyState = NULL;\n'
954 ' bool has_tessellation_stage = false;\n'
955 ' if (stageCount && pStages)\n'
956 ' for (uint32_t i=0; i<stageCount && !has_tessellation_stage; ++i)\n'
957 ' if (pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)\n'
958 ' has_tessellation_stage = true;\n'
959 ' if (in_struct->pTessellationState && has_tessellation_stage)\n'
960 ' pTessellationState = new safe_VkPipelineTessellationStateCreateInfo(in_struct->pTessellationState);\n'
961 ' else\n'
962 ' pTessellationState = NULL; // original pTessellationState pointer ignored\n'
963 ' bool has_rasterization = in_struct->pRasterizationState ? !in_struct->pRasterizationState->rasterizerDiscardEnable : false;\n'
964 ' if (in_struct->pViewportState && has_rasterization) {\n'
965 ' bool is_dynamic_viewports = false;\n'
966 ' bool is_dynamic_scissors = false;\n'
967 ' if (in_struct->pDynamicState && in_struct->pDynamicState->pDynamicStates) {\n'
968 ' for (uint32_t i = 0; i < in_struct->pDynamicState->dynamicStateCount && !is_dynamic_viewports; ++i)\n'
969 ' if (in_struct->pDynamicState->pDynamicStates[i] == VK_DYNAMIC_STATE_VIEWPORT)\n'
970 ' is_dynamic_viewports = true;\n'
971 ' for (uint32_t i = 0; i < in_struct->pDynamicState->dynamicStateCount && !is_dynamic_scissors; ++i)\n'
972 ' if (in_struct->pDynamicState->pDynamicStates[i] == VK_DYNAMIC_STATE_SCISSOR)\n'
973 ' is_dynamic_scissors = true;\n'
974 ' }\n'
975 ' pViewportState = new safe_VkPipelineViewportStateCreateInfo(in_struct->pViewportState, is_dynamic_viewports, is_dynamic_scissors);\n'
976 ' } else\n'
977 ' pViewportState = NULL; // original pViewportState pointer ignored\n'
978 ' if (in_struct->pRasterizationState)\n'
979 ' pRasterizationState = new safe_VkPipelineRasterizationStateCreateInfo(in_struct->pRasterizationState);\n'
980 ' else\n'
981 ' pRasterizationState = NULL;\n'
982 ' if (in_struct->pMultisampleState && has_rasterization)\n'
983 ' pMultisampleState = new safe_VkPipelineMultisampleStateCreateInfo(in_struct->pMultisampleState);\n'
984 ' else\n'
985 ' pMultisampleState = NULL; // original pMultisampleState pointer ignored\n'
986 ' // needs a tracked subpass state uses_depthstencil_attachment\n'
987 ' if (in_struct->pDepthStencilState && has_rasterization && uses_depthstencil_attachment)\n'
988 ' pDepthStencilState = new safe_VkPipelineDepthStencilStateCreateInfo(in_struct->pDepthStencilState);\n'
989 ' else\n'
990 ' pDepthStencilState = NULL; // original pDepthStencilState pointer ignored\n'
991 ' // needs a tracked subpass state usesColorAttachment\n'
992 ' if (in_struct->pColorBlendState && has_rasterization && uses_color_attachment)\n'
993 ' pColorBlendState = new safe_VkPipelineColorBlendStateCreateInfo(in_struct->pColorBlendState);\n'
994 ' else\n'
995 ' pColorBlendState = NULL; // original pColorBlendState pointer ignored\n'
996 ' if (in_struct->pDynamicState)\n'
997 ' pDynamicState = new safe_VkPipelineDynamicStateCreateInfo(in_struct->pDynamicState);\n'
998 ' else\n'
999 ' pDynamicState = NULL;\n',
1000 # VkPipelineViewportStateCreateInfo is special case because its pointers may be non-null but ignored
1001 'VkPipelineViewportStateCreateInfo' :
1002 ' if (in_struct->pViewports && !is_dynamic_viewports) {\n'
1003 ' pViewports = new VkViewport[in_struct->viewportCount];\n'
1004 ' memcpy ((void *)pViewports, (void *)in_struct->pViewports, sizeof(VkViewport)*in_struct->viewportCount);\n'
1005 ' }\n'
1006 ' else\n'
1007 ' pViewports = NULL;\n'
1008 ' if (in_struct->pScissors && !is_dynamic_scissors) {\n'
1009 ' pScissors = new VkRect2D[in_struct->scissorCount];\n'
1010 ' memcpy ((void *)pScissors, (void *)in_struct->pScissors, sizeof(VkRect2D)*in_struct->scissorCount);\n'
1011 ' }\n'
1012 ' else\n'
1013 ' pScissors = NULL;\n',
Petr Kraus42f6f8d2017-12-17 17:37:33 +01001014 # VkDescriptorSetLayoutBinding is special case because its pImmutableSamplers pointer may be non-null but ignored
1015 'VkDescriptorSetLayoutBinding' :
1016 ' const bool sampler_type = in_struct->descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER || in_struct->descriptorType == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;\n'
1017 ' if (descriptorCount && in_struct->pImmutableSamplers && sampler_type) {\n'
1018 ' pImmutableSamplers = new VkSampler[descriptorCount];\n'
1019 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
1020 ' pImmutableSamplers[i] = in_struct->pImmutableSamplers[i];\n'
1021 ' }\n'
1022 ' }\n',
Petr Krause91f7a12017-12-14 20:57:36 +01001023 }
1024
1025 custom_copy_txt = {
1026 # VkGraphicsPipelineCreateInfo is special case because it has custom construct parameters
1027 'VkGraphicsPipelineCreateInfo' :
1028 ' if (stageCount && src.pStages) {\n'
1029 ' pStages = new safe_VkPipelineShaderStageCreateInfo[stageCount];\n'
1030 ' for (uint32_t i=0; i<stageCount; ++i) {\n'
1031 ' pStages[i].initialize(&src.pStages[i]);\n'
1032 ' }\n'
1033 ' }\n'
1034 ' if (src.pVertexInputState)\n'
1035 ' pVertexInputState = new safe_VkPipelineVertexInputStateCreateInfo(*src.pVertexInputState);\n'
1036 ' else\n'
1037 ' pVertexInputState = NULL;\n'
1038 ' if (src.pInputAssemblyState)\n'
1039 ' pInputAssemblyState = new safe_VkPipelineInputAssemblyStateCreateInfo(*src.pInputAssemblyState);\n'
1040 ' else\n'
1041 ' pInputAssemblyState = NULL;\n'
1042 ' bool has_tessellation_stage = false;\n'
1043 ' if (stageCount && pStages)\n'
1044 ' for (uint32_t i=0; i<stageCount && !has_tessellation_stage; ++i)\n'
1045 ' if (pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)\n'
1046 ' has_tessellation_stage = true;\n'
1047 ' if (src.pTessellationState && has_tessellation_stage)\n'
1048 ' pTessellationState = new safe_VkPipelineTessellationStateCreateInfo(*src.pTessellationState);\n'
1049 ' else\n'
1050 ' pTessellationState = NULL; // original pTessellationState pointer ignored\n'
1051 ' bool has_rasterization = src.pRasterizationState ? !src.pRasterizationState->rasterizerDiscardEnable : false;\n'
1052 ' if (src.pViewportState && has_rasterization) {\n'
1053 ' pViewportState = new safe_VkPipelineViewportStateCreateInfo(*src.pViewportState);\n'
1054 ' } else\n'
1055 ' pViewportState = NULL; // original pViewportState pointer ignored\n'
1056 ' if (src.pRasterizationState)\n'
1057 ' pRasterizationState = new safe_VkPipelineRasterizationStateCreateInfo(*src.pRasterizationState);\n'
1058 ' else\n'
1059 ' pRasterizationState = NULL;\n'
1060 ' if (src.pMultisampleState && has_rasterization)\n'
1061 ' pMultisampleState = new safe_VkPipelineMultisampleStateCreateInfo(*src.pMultisampleState);\n'
1062 ' else\n'
1063 ' pMultisampleState = NULL; // original pMultisampleState pointer ignored\n'
1064 ' if (src.pDepthStencilState && has_rasterization)\n'
1065 ' pDepthStencilState = new safe_VkPipelineDepthStencilStateCreateInfo(*src.pDepthStencilState);\n'
1066 ' else\n'
1067 ' pDepthStencilState = NULL; // original pDepthStencilState pointer ignored\n'
1068 ' if (src.pColorBlendState && has_rasterization)\n'
1069 ' pColorBlendState = new safe_VkPipelineColorBlendStateCreateInfo(*src.pColorBlendState);\n'
1070 ' else\n'
1071 ' pColorBlendState = NULL; // original pColorBlendState pointer ignored\n'
1072 ' if (src.pDynamicState)\n'
1073 ' pDynamicState = new safe_VkPipelineDynamicStateCreateInfo(*src.pDynamicState);\n'
1074 ' else\n'
1075 ' pDynamicState = NULL;\n',
1076 # VkPipelineViewportStateCreateInfo is special case because it has custom construct parameters
1077 'VkPipelineViewportStateCreateInfo' :
1078 ' if (src.pViewports) {\n'
1079 ' pViewports = new VkViewport[src.viewportCount];\n'
1080 ' memcpy ((void *)pViewports, (void *)src.pViewports, sizeof(VkViewport)*src.viewportCount);\n'
1081 ' }\n'
1082 ' else\n'
1083 ' pViewports = NULL;\n'
1084 ' if (src.pScissors) {\n'
1085 ' pScissors = new VkRect2D[src.scissorCount];\n'
1086 ' memcpy ((void *)pScissors, (void *)src.pScissors, sizeof(VkRect2D)*src.scissorCount);\n'
1087 ' }\n'
1088 ' else\n'
1089 ' pScissors = NULL;\n',
1090 }
1091
Mike Schuchardt81485762017-09-04 11:38:42 -06001092 custom_destruct_txt = {'VkShaderModuleCreateInfo' :
1093 ' if (pCode)\n'
1094 ' delete[] reinterpret_cast<const uint8_t *>(pCode);\n' }
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001095
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001096 for member in item.members:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001097 m_type = member.type
1098 if member.type in self.structNames:
1099 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
1100 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
1101 m_type = 'safe_%s' % member.type
1102 if member.ispointer and 'safe_' not in m_type and self.TypeContainsObjectHandle(member.type, False) == False:
1103 # Ptr types w/o a safe_struct, for non-null case need to allocate new ptr and copy data in
Mark Lobodzinski560729b2017-03-06 08:59:14 -07001104 if m_type in ['void', 'char']:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001105 # For these exceptions just copy initial value over for now
1106 init_list += '\n %s(in_struct->%s),' % (member.name, member.name)
1107 init_func_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001108 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001109 default_init_list += '\n %s(nullptr),' % (member.name)
1110 init_list += '\n %s(nullptr),' % (member.name)
1111 init_func_txt += ' %s = nullptr;\n' % (member.name)
1112 if 'pNext' != member.name and 'void' not in m_type:
Mark Lobodzinski51160a12017-01-18 11:05:48 -07001113 if not member.isstaticarray and (member.len is None or '/' in member.len):
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001114 construct_txt += ' if (in_struct->%s) {\n' % member.name
1115 construct_txt += ' %s = new %s(*in_struct->%s);\n' % (member.name, m_type, member.name)
1116 construct_txt += ' }\n'
1117 destruct_txt += ' if (%s)\n' % member.name
1118 destruct_txt += ' delete %s;\n' % member.name
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001119 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001120 construct_txt += ' if (in_struct->%s) {\n' % member.name
1121 construct_txt += ' %s = new %s[in_struct->%s];\n' % (member.name, m_type, member.len)
1122 construct_txt += ' memcpy ((void *)%s, (void *)in_struct->%s, sizeof(%s)*in_struct->%s);\n' % (member.name, member.name, m_type, member.len)
1123 construct_txt += ' }\n'
1124 destruct_txt += ' if (%s)\n' % member.name
1125 destruct_txt += ' delete[] %s;\n' % member.name
1126 elif member.isstaticarray or member.len is not None:
1127 if member.len is None:
1128 # Extract length of static array by grabbing val between []
1129 static_array_size = re.match(r"[^[]*\[([^]]*)\]", member.cdecl)
1130 construct_txt += ' for (uint32_t i=0; i<%s; ++i) {\n' % static_array_size.group(1)
1131 construct_txt += ' %s[i] = in_struct->%s[i];\n' % (member.name, member.name)
1132 construct_txt += ' }\n'
1133 else:
1134 # Init array ptr to NULL
1135 default_init_list += '\n %s(nullptr),' % member.name
1136 init_list += '\n %s(nullptr),' % member.name
1137 init_func_txt += ' %s = nullptr;\n' % member.name
1138 array_element = 'in_struct->%s[i]' % member.name
1139 if member.type in self.structNames:
1140 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
1141 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
1142 array_element = '%s(&in_struct->safe_%s[i])' % (member.type, member.name)
1143 construct_txt += ' if (%s && in_struct->%s) {\n' % (member.len, member.name)
1144 construct_txt += ' %s = new %s[%s];\n' % (member.name, m_type, member.len)
1145 destruct_txt += ' if (%s)\n' % member.name
1146 destruct_txt += ' delete[] %s;\n' % member.name
1147 construct_txt += ' for (uint32_t i=0; i<%s; ++i) {\n' % (member.len)
1148 if 'safe_' in m_type:
1149 construct_txt += ' %s[i].initialize(&in_struct->%s[i]);\n' % (member.name, member.name)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001150 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001151 construct_txt += ' %s[i] = %s;\n' % (member.name, array_element)
1152 construct_txt += ' }\n'
1153 construct_txt += ' }\n'
1154 elif member.ispointer == True:
1155 construct_txt += ' if (in_struct->%s)\n' % member.name
1156 construct_txt += ' %s = new %s(in_struct->%s);\n' % (member.name, m_type, member.name)
1157 construct_txt += ' else\n'
1158 construct_txt += ' %s = NULL;\n' % member.name
1159 destruct_txt += ' if (%s)\n' % member.name
1160 destruct_txt += ' delete %s;\n' % member.name
1161 elif 'safe_' in m_type:
1162 init_list += '\n %s(&in_struct->%s),' % (member.name, member.name)
1163 init_func_txt += ' %s.initialize(&in_struct->%s);\n' % (member.name, member.name)
1164 else:
1165 init_list += '\n %s(in_struct->%s),' % (member.name, member.name)
1166 init_func_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
1167 if '' != init_list:
1168 init_list = init_list[:-1] # hack off final comma
1169 if item.name in custom_construct_txt:
1170 construct_txt = custom_construct_txt[item.name]
Mike Schuchardt81485762017-09-04 11:38:42 -06001171 if item.name in custom_destruct_txt:
1172 destruct_txt = custom_destruct_txt[item.name]
Petr Krause91f7a12017-12-14 20:57:36 +01001173 safe_struct_body.append("\n%s::%s(const %s* in_struct%s) :%s\n{\n%s}" % (ss_name, ss_name, item.name, self.custom_construct_params.get(item.name, ''), init_list, construct_txt))
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001174 if '' != default_init_list:
1175 default_init_list = " :%s" % (default_init_list[:-1])
1176 safe_struct_body.append("\n%s::%s()%s\n{}" % (ss_name, ss_name, default_init_list))
1177 # Create slight variation of init and construct txt for copy constructor that takes a src object reference vs. struct ptr
1178 copy_construct_init = init_func_txt.replace('in_struct->', 'src.')
1179 copy_construct_txt = construct_txt.replace(' (in_struct->', ' (src.') # Exclude 'if' blocks from next line
1180 copy_construct_txt = copy_construct_txt.replace('(in_struct->', '(*src.') # Pass object to copy constructors
1181 copy_construct_txt = copy_construct_txt.replace('in_struct->', 'src.') # Modify remaining struct refs for src object
Petr Krause91f7a12017-12-14 20:57:36 +01001182 if item.name in custom_copy_txt:
1183 copy_construct_txt = custom_copy_txt[item.name]
Chris Forbesfb633832017-10-03 18:11:54 -07001184 copy_assign_txt = ' if (&src == this) return *this;\n\n' + destruct_txt + '\n' + copy_construct_init + copy_construct_txt + '\n return *this;'
Mark Lobodzinski5cd08512017-09-12 09:50:25 -06001185 safe_struct_body.append("\n%s::%s(const %s& src)\n{\n%s%s}" % (ss_name, ss_name, ss_name, copy_construct_init, copy_construct_txt)) # Copy constructor
Chris Forbesfb633832017-10-03 18:11:54 -07001186 safe_struct_body.append("\n%s& %s::operator=(const %s& src)\n{\n%s\n}" % (ss_name, ss_name, ss_name, copy_assign_txt)) # Copy assignment operator
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001187 safe_struct_body.append("\n%s::~%s()\n{\n%s}" % (ss_name, ss_name, destruct_txt))
Petr Krause91f7a12017-12-14 20:57:36 +01001188 safe_struct_body.append("\nvoid %s::initialize(const %s* in_struct%s)\n{\n%s%s}" % (ss_name, item.name, self.custom_construct_params.get(item.name, ''), init_func_txt, construct_txt))
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001189 # Copy initializer uses same txt as copy constructor but has a ptr and not a reference
1190 init_copy = copy_construct_init.replace('src.', 'src->')
1191 init_construct = copy_construct_txt.replace('src.', 'src->')
Mark Lobodzinski5cd08512017-09-12 09:50:25 -06001192 safe_struct_body.append("\nvoid %s::initialize(const %s* src)\n{\n%s%s}" % (ss_name, ss_name, init_copy, init_construct))
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001193 if item.ifdef_protect != None:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001194 safe_struct_body.append("#endif // %s\n" % item.ifdef_protect)
1195 return "\n".join(safe_struct_body)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001196 #
John Zulaufde972ac2017-10-26 12:07:05 -06001197 # Generate the type map
1198 def GenerateTypeMapHelperHeader(self):
1199 prefix = 'Lvl'
1200 fprefix = 'lvl_'
1201 typemap = prefix + 'TypeMap'
1202 idmap = prefix + 'STypeMap'
John Zulaufde972ac2017-10-26 12:07:05 -06001203 type_member = 'Type'
1204 id_member = 'kSType'
Mike Schuchardt97662b02017-12-06 13:31:29 -07001205 id_decl = 'static const VkStructureType '
John Zulaufde972ac2017-10-26 12:07:05 -06001206 generic_header = prefix + 'GenericHeader'
1207 typename_func = fprefix + 'typename'
1208 idname_func = fprefix + 'stype_name'
1209 find_func = fprefix + 'find_in_chain'
John Zulauf65ac9d52018-01-23 11:20:50 -07001210 init_func = fprefix + 'init_struct'
John Zulaufde972ac2017-10-26 12:07:05 -06001211
1212 explanatory_comment = '\n'.join((
1213 '// These empty generic templates are specialized for each type with sType',
1214 '// members and for each sType -- providing a two way map between structure',
Mike Schuchardt97662b02017-12-06 13:31:29 -07001215 '// types and sTypes'))
John Zulaufde972ac2017-10-26 12:07:05 -06001216
1217 empty_typemap = 'template <typename T> struct ' + typemap + ' {};'
1218 typemap_format = 'template <> struct {template}<{typename}> {{\n'
John Zulaufde972ac2017-10-26 12:07:05 -06001219 typemap_format += ' {id_decl}{id_member} = {id_value};\n'
1220 typemap_format += '}};\n'
1221
1222 empty_idmap = 'template <VkStructureType id> struct ' + idmap + ' {};'
1223 idmap_format = ''.join((
1224 'template <> struct {template}<{id_value}> {{\n',
1225 ' typedef {typename} {typedef};\n',
John Zulaufde972ac2017-10-26 12:07:05 -06001226 '}};\n'))
1227
1228 # Define the utilities (here so any renaming stays consistent), if this grows large, refactor to a fixed .h file
1229 utilities_format = '\n'.join((
1230 '// Header "base class" for pNext chain traversal',
1231 'struct {header} {{',
1232 ' VkStructureType sType;',
1233 ' const {header} *pNext;',
1234 '}};',
1235 '',
1236 '// Find an entry of the given type in the pNext chain',
1237 'template <typename T> const T *{find_func}(const void *next) {{',
1238 ' const {header} *current = reinterpret_cast<const {header} *>(next);',
1239 ' const T *found = nullptr;',
1240 ' while (current) {{',
1241 ' if ({type_map}<T>::{id_member} == current->sType) {{',
1242 ' found = reinterpret_cast<const T*>(current);',
1243 ' current = nullptr;',
1244 ' }} else {{',
1245 ' current = current->pNext;',
1246 ' }}',
1247 ' }}',
1248 ' return found;',
1249 '}}',
John Zulauf65ac9d52018-01-23 11:20:50 -07001250 '',
1251 '// Init the header of an sType struct with pNext',
1252 'template <typename T> T {init_func}(void *p_next) {{',
1253 ' T out = {{}};',
1254 ' out.sType = {type_map}<T>::kSType;',
1255 ' out.pNext = p_next;',
1256 ' return out;',
1257 '}}',
1258 '',
1259 '// Init the header of an sType struct',
1260 'template <typename T> T {init_func}() {{',
1261 ' T out = {{}};',
1262 ' out.sType = {type_map}<T>::kSType;',
1263 ' return out;',
1264 '}}',
1265
Mike Schuchardt97662b02017-12-06 13:31:29 -07001266 ''))
John Zulaufde972ac2017-10-26 12:07:05 -06001267
1268 code = []
John Zulauf65ac9d52018-01-23 11:20:50 -07001269
1270 # Generate header
John Zulaufde972ac2017-10-26 12:07:05 -06001271 code.append('\n'.join((
1272 '#pragma once',
1273 '#include <vulkan/vulkan.h>\n',
1274 explanatory_comment, '',
1275 empty_idmap,
John Zulauf65ac9d52018-01-23 11:20:50 -07001276 empty_typemap, '')))
John Zulaufde972ac2017-10-26 12:07:05 -06001277
1278 # Generate the specializations for each type and stype
John Zulaufde972ac2017-10-26 12:07:05 -06001279 for item in self.structMembers:
1280 typename = item.name
1281 info = self.structTypes.get(typename)
1282 if not info:
1283 continue
1284
1285 if item.ifdef_protect != None:
1286 code.append('#ifdef %s' % item.ifdef_protect)
1287
1288 code.append('// Map type {} to id {}'.format(typename, info.value))
1289 code.append(typemap_format.format(template=typemap, typename=typename, id_value=info.value,
Mike Schuchardt97662b02017-12-06 13:31:29 -07001290 id_decl=id_decl, id_member=id_member))
1291 code.append(idmap_format.format(template=idmap, typename=typename, id_value=info.value, typedef=type_member))
John Zulaufde972ac2017-10-26 12:07:05 -06001292
1293 if item.ifdef_protect != None:
1294 code.append('#endif // %s' % item.ifdef_protect)
1295
John Zulauf65ac9d52018-01-23 11:20:50 -07001296 # Generate utilities for all types
1297 code.append('\n'.join((
1298 utilities_format.format(id_member=id_member, id_map=idmap, type_map=typemap,
1299 type_member=type_member, header=generic_header, typename_func=typename_func, idname_func=idname_func,
1300 find_func=find_func, init_func=init_func), ''
1301 )))
1302
John Zulaufde972ac2017-10-26 12:07:05 -06001303 return "\n".join(code)
1304
1305 #
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -07001306 # Create a helper file and return it as a string
1307 def OutputDestFile(self):
Mark Lobodzinski46d388f2016-12-28 10:46:26 -07001308 if self.helper_file_type == 'enum_string_header':
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -07001309 return self.GenerateEnumStringHelperHeader()
Mark Lobodzinski46d388f2016-12-28 10:46:26 -07001310 elif self.helper_file_type == 'struct_size_header':
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -07001311 return self.GenerateStructSizeHelperHeader()
Mark Lobodzinski46d388f2016-12-28 10:46:26 -07001312 elif self.helper_file_type == 'struct_size_source':
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -07001313 return self.GenerateStructSizeHelperSource()
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001314 elif self.helper_file_type == 'safe_struct_header':
1315 return self.GenerateSafeStructHelperHeader()
1316 elif self.helper_file_type == 'safe_struct_source':
1317 return self.GenerateSafeStructHelperSource()
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -06001318 elif self.helper_file_type == 'object_types_header':
1319 return self.GenerateObjectTypesHelperHeader()
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -06001320 elif self.helper_file_type == 'extension_helper_header':
1321 return self.GenerateExtensionHelperHeader()
John Zulaufde972ac2017-10-26 12:07:05 -06001322 elif self.helper_file_type == 'typemap_helper_header':
1323 return self.GenerateTypeMapHelperHeader()
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -07001324 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001325 return 'Bad Helper File Generator Option %s' % self.helper_file_type
Mark Lobodzinskif36e58b2016-12-29 14:04:15 -07001326