blob: 7ea4e2ae17df04313086e88b344238df100cdc94 [file] [log] [blame]
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -07001#!/usr/bin/python3 -i
2#
Mike Schuchardt21638df2019-03-16 10:52:02 -07003# Copyright (c) 2015-2019 The Khronos Group Inc.
4# Copyright (c) 2015-2019 Valve Corporation
5# Copyright (c) 2015-2019 LunarG, Inc.
6# Copyright (c) 2015-2019 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>
John Zulaufd7435c62018-03-16 11:52:57 -060022# Author: John Zulauf <jzulauf@lunarg.com>
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070023
24import os,re,sys
25import xml.etree.ElementTree as etree
26from generator import *
27from collections import namedtuple
Mark Lobodzinski62f71562017-10-24 13:41:18 -060028from common_codegen import *
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070029
30#
31# HelperFileOutputGeneratorOptions - subclass of GeneratorOptions.
32class HelperFileOutputGeneratorOptions(GeneratorOptions):
33 def __init__(self,
Mike Schuchardt21638df2019-03-16 10:52:02 -070034 conventions = None,
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070035 filename = None,
36 directory = '.',
37 apiname = None,
38 profile = None,
39 versions = '.*',
40 emitversions = '.*',
41 defaultExtensions = None,
42 addExtensions = None,
43 removeExtensions = None,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060044 emitExtensions = None,
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070045 sortProcedure = regSortFeatures,
46 prefixText = "",
47 genFuncPointers = True,
48 protectFile = True,
49 protectFeature = True,
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070050 apicall = '',
51 apientry = '',
52 apientryp = '',
53 alignFuncParam = 0,
54 library_name = '',
Mark Lobodzinski62f71562017-10-24 13:41:18 -060055 expandEnumerants = True,
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070056 helper_file_type = ''):
Mike Schuchardt21638df2019-03-16 10:52:02 -070057 GeneratorOptions.__init__(self, conventions, filename, directory, apiname, profile,
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070058 versions, emitversions, defaultExtensions,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060059 addExtensions, removeExtensions, emitExtensions, sortProcedure)
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070060 self.prefixText = prefixText
61 self.genFuncPointers = genFuncPointers
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070062 self.protectFile = protectFile
63 self.protectFeature = protectFeature
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070064 self.apicall = apicall
65 self.apientry = apientry
66 self.apientryp = apientryp
67 self.alignFuncParam = alignFuncParam
68 self.library_name = library_name
69 self.helper_file_type = helper_file_type
70#
Mark Lobodzinski46d388f2016-12-28 10:46:26 -070071# HelperFileOutputGenerator - subclass of OutputGenerator. Outputs Vulkan helper files
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070072class HelperFileOutputGenerator(OutputGenerator):
Mark Lobodzinskia3cc3612017-01-03 13:25:10 -070073 """Generate helper file based on XML element attributes"""
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070074 def __init__(self,
75 errFile = sys.stderr,
76 warnFile = sys.stderr,
77 diagFile = sys.stdout):
78 OutputGenerator.__init__(self, errFile, warnFile, diagFile)
79 # Internal state - accumulators for different inner block text
Mark Lobodzinski5380d132016-12-28 14:45:34 -070080 self.enum_output = '' # string built up of enum string routines
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
John Zulaufd7435c62018-03-16 11:52:57 -060086 self.object_type_aliases = [] # Aliases to handles types (for handles that were extensions)
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -060087 self.debug_report_object_types = [] # Handy copy of debug_report_object_type enum data
Mark Young1ded24b2017-05-30 14:53:50 -060088 self.core_object_types = [] # Handy copy of core_object_type enum data
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -060089 self.device_extension_info = dict() # Dict of device extension name defines and ifdef values
90 self.instance_extension_info = dict() # Dict of instance extension name defines and ifdef values
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -060091
Mark Lobodzinski46d388f2016-12-28 10:46:26 -070092 # Named tuples to store struct and command data
93 self.StructType = namedtuple('StructType', ['name', 'value'])
Mark Lobodzinskic67efd02017-01-04 09:16:00 -070094 self.CommandParam = namedtuple('CommandParam', ['type', 'name', 'ispointer', 'isstaticarray', 'isconst', 'iscount', 'len', 'extstructs', 'cdecl'])
Mark Lobodzinski5380d132016-12-28 14:45:34 -070095 self.StructMemberData = namedtuple('StructMemberData', ['name', 'members', 'ifdef_protect'])
Petr Krause91f7a12017-12-14 20:57:36 +010096
97 self.custom_construct_params = {
98 # safe_VkGraphicsPipelineCreateInfo needs to know if subpass has color and\or depth\stencil attachments to use its pointers
99 'VkGraphicsPipelineCreateInfo' :
100 ', const bool uses_color_attachment, const bool uses_depthstencil_attachment',
101 # safe_VkPipelineViewportStateCreateInfo needs to know if viewport and scissor is dynamic to use its pointers
102 'VkPipelineViewportStateCreateInfo' :
103 ', const bool is_dynamic_viewports, const bool is_dynamic_scissors',
104 }
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700105 #
106 # Called once at the beginning of each run
107 def beginFile(self, genOpts):
108 OutputGenerator.beginFile(self, genOpts)
109 # User-supplied prefix text, if any (list of strings)
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700110 self.helper_file_type = genOpts.helper_file_type
111 self.library_name = genOpts.library_name
112 # File Comment
113 file_comment = '// *** THIS FILE IS GENERATED - DO NOT EDIT ***\n'
114 file_comment += '// See helper_file_generator.py for modifications\n'
115 write(file_comment, file=self.outFile)
116 # Copyright Notice
117 copyright = ''
118 copyright += '\n'
119 copyright += '/***************************************************************************\n'
120 copyright += ' *\n'
Mike Schuchardt21638df2019-03-16 10:52:02 -0700121 copyright += ' * Copyright (c) 2015-2019 The Khronos Group Inc.\n'
122 copyright += ' * Copyright (c) 2015-2019 Valve Corporation\n'
123 copyright += ' * Copyright (c) 2015-2019 LunarG, Inc.\n'
124 copyright += ' * Copyright (c) 2015-2019 Google Inc.\n'
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700125 copyright += ' *\n'
126 copyright += ' * Licensed under the Apache License, Version 2.0 (the "License");\n'
127 copyright += ' * you may not use this file except in compliance with the License.\n'
128 copyright += ' * You may obtain a copy of the License at\n'
129 copyright += ' *\n'
130 copyright += ' * http://www.apache.org/licenses/LICENSE-2.0\n'
131 copyright += ' *\n'
132 copyright += ' * Unless required by applicable law or agreed to in writing, software\n'
133 copyright += ' * distributed under the License is distributed on an "AS IS" BASIS,\n'
134 copyright += ' * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n'
135 copyright += ' * See the License for the specific language governing permissions and\n'
136 copyright += ' * limitations under the License.\n'
137 copyright += ' *\n'
138 copyright += ' * Author: Mark Lobodzinski <mark@lunarg.com>\n'
Mark Lobodzinskia9c963d2016-12-28 07:45:35 -0700139 copyright += ' * Author: Courtney Goeltzenleuchter <courtneygo@google.com>\n'
140 copyright += ' * Author: Tobin Ehlis <tobine@google.com>\n'
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600141 copyright += ' * Author: Chris Forbes <chrisforbes@google.com>\n'
John Zulaufde972ac2017-10-26 12:07:05 -0600142 copyright += ' * Author: John Zulauf<jzulauf@lunarg.com>\n'
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700143 copyright += ' *\n'
144 copyright += ' ****************************************************************************/\n'
145 write(copyright, file=self.outFile)
146 #
Mark Lobodzinskia3cc3612017-01-03 13:25:10 -0700147 # Write generated file content to output file
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700148 def endFile(self):
149 dest_file = ''
150 dest_file += self.OutputDestFile()
Mark Lobodzinskiafe10542017-01-03 13:22:44 -0700151 # Remove blank lines at EOF
152 if dest_file.endswith('\n'):
153 dest_file = dest_file[:-1]
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700154 write(dest_file, file=self.outFile);
155 # Finish processing in superclass
156 OutputGenerator.endFile(self)
157 #
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600158 # Override parent class to be notified of the beginning of an extension
159 def beginFeature(self, interface, emit):
160 # Start processing in superclass
161 OutputGenerator.beginFeature(self, interface, emit)
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600162 self.featureExtraProtect = GetFeatureProtect(interface)
163
Mark Lobodzinski31964ca2017-09-18 14:15:09 -0600164 if self.featureName == 'VK_VERSION_1_0' or self.featureName == 'VK_VERSION_1_1':
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600165 return
John Zulauff6feb2a2018-04-12 14:24:57 -0600166 name = self.featureName
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600167 nameElem = interface[0][1]
John Zulauff6feb2a2018-04-12 14:24:57 -0600168 name_define = nameElem.get('name')
169 if 'EXTENSION_NAME' not in name_define:
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600170 print("Error in vk.xml file -- extension name is not available")
John Zulauf072677c2018-04-12 15:34:39 -0600171 requires = interface.get('requires')
172 if requires is not None:
173 required_extensions = requires.split(',')
174 else:
175 required_extensions = list()
176 info = { 'define': name_define, 'ifdef':self.featureExtraProtect, 'reqs':required_extensions }
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600177 if interface.get('type') == 'instance':
John Zulauff6feb2a2018-04-12 14:24:57 -0600178 self.instance_extension_info[name] = info
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600179 else:
John Zulauff6feb2a2018-04-12 14:24:57 -0600180 self.device_extension_info[name] = info
181
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600182 #
183 # Override parent class to be notified of the end of an extension
184 def endFeature(self):
185 # Finish processing in superclass
186 OutputGenerator.endFeature(self)
187 #
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700188 # Grab group (e.g. C "enum" type) info to output for enum-string conversion helper
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700189 def genGroup(self, groupinfo, groupName, alias):
190 OutputGenerator.genGroup(self, groupinfo, groupName, alias)
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700191 groupElem = groupinfo.elem
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700192 # For enum_string_header
193 if self.helper_file_type == 'enum_string_header':
Mike Schuchardtdf1e8dd2018-03-09 09:02:56 -0700194 value_set = set()
Mark Lobodzinski824ce642016-12-28 08:49:46 -0700195 for elem in groupElem.findall('enum'):
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100196 if elem.get('supported') != 'disabled' and elem.get('alias') is None:
Mike Schuchardtdf1e8dd2018-03-09 09:02:56 -0700197 value_set.add(elem.get('name'))
Tobias Hector30ad4fc2018-12-10 12:21:17 +0000198 if value_set != set():
199 self.enum_output += self.GenerateEnumStringConversion(groupName, value_set)
Mark Young1ded24b2017-05-30 14:53:50 -0600200 elif self.helper_file_type == 'object_types_header':
201 if groupName == 'VkDebugReportObjectTypeEXT':
202 for elem in groupElem.findall('enum'):
203 if elem.get('supported') != 'disabled':
204 item_name = elem.get('name')
205 self.debug_report_object_types.append(item_name)
206 elif groupName == 'VkObjectType':
207 for elem in groupElem.findall('enum'):
208 if elem.get('supported') != 'disabled':
209 item_name = elem.get('name')
210 self.core_object_types.append(item_name)
211
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700212 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700213 # Called for each type -- if the type is a struct/union, grab the metadata
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700214 def genType(self, typeinfo, name, alias):
215 OutputGenerator.genType(self, typeinfo, name, alias)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700216 typeElem = typeinfo.elem
217 # If the type is a struct type, traverse the imbedded <member> tags generating a structure.
218 # Otherwise, emit the tag text.
219 category = typeElem.get('category')
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600220 if category == 'handle':
John Zulaufd7435c62018-03-16 11:52:57 -0600221 if alias:
222 self.object_type_aliases.append((name,alias))
223 else:
224 self.object_types.append(name)
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600225 elif (category == 'struct' or category == 'union'):
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700226 self.structNames.append(name)
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700227 self.genStruct(typeinfo, name, alias)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700228 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700229 # Check if the parameter passed in is a pointer
230 def paramIsPointer(self, param):
231 ispointer = False
232 for elem in param:
Raul Tambre7b300182019-05-04 11:25:14 +0300233 if elem.tag == 'type' and elem.tail is not None and '*' in elem.tail:
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700234 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]'
Shannon McPhersonbd68df02018-10-29 15:04:41 -0600277 match = re.match(r'latexmath\s*\:\s*\[\s*(\\textrm\{)?(\w+)\}?\s*\\over\s*(\d+)\s*\]', source)
278 name = match.group(2)
279 decoratedName = '{}/{}'.format(*match.group(2, 3))
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700280 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 #
Shannon McPhersonbd68df02018-10-29 15:04:41 -0600301 # Check if a structure is or contains a dispatchable (dispatchable = True) or
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700302 # 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
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700322 def genStruct(self, typeinfo, typeName, alias):
323 OutputGenerator.genStruct(self, typeinfo, typeName, alias)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700324 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)
Mike Schuchardt08368cb2018-05-22 14:52:04 -0600347 # Store the required type value
348 self.structTypes[typeName] = self.StructType(name=name, value=value)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700349 # Store pointer/array/string info
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700350 isstaticarray = self.paramIsStaticArray(member)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700351 membersInfo.append(self.CommandParam(type=type,
352 name=name,
353 ispointer=self.paramIsPointer(member),
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700354 isstaticarray=isstaticarray,
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700355 isconst=True if 'const' in cdecl else False,
356 iscount=True if name in lens else False,
357 len=self.getLen(member),
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600358 extstructs=self.registry.validextensionstructs[typeName] if name == 'pNext' else None,
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700359 cdecl=cdecl))
Mark Lobodzinski5380d132016-12-28 14:45:34 -0700360 self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo, ifdef_protect=self.featureExtraProtect))
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700361 #
362 # Enum_string_header: Create a routine to convert an enumerated value into a string
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700363 def GenerateEnumStringConversion(self, groupName, value_list):
364 outstring = '\n'
Mike Schuchardt21638df2019-03-16 10:52:02 -0700365 if self.featureExtraProtect is not None:
366 outstring += '\n#ifdef %s\n\n' % self.featureExtraProtect
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700367 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'
Karl Schultz7fd3f6e2018-07-05 17:21:05 -0600371 # Emit these in a repeatable order so file is generated with the same contents each time.
372 # This helps compiler caching systems like ccache.
373 for item in sorted(value_list):
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700374 outstring += ' case %s:\n' % item
375 outstring += ' return "%s";\n' % item
376 outstring += ' default:\n'
377 outstring += ' return "Unhandled %s";\n' % groupName
378 outstring += ' }\n'
379 outstring += '}\n'
Mike Schuchardt21638df2019-03-16 10:52:02 -0700380 if self.featureExtraProtect is not None:
381 outstring += '#endif // %s\n' % self.featureExtraProtect
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700382 return outstring
383 #
Mark Lobodzinski64b432f2017-07-24 16:14:16 -0600384 # Tack on a helper which, given an index into a VkPhysicalDeviceFeatures structure, will print the corresponding feature name
385 def DeIndexPhysDevFeatures(self):
386 pdev_members = None
387 for name, members, ifdef in self.structMembers:
388 if name == 'VkPhysicalDeviceFeatures':
389 pdev_members = members
390 break
391 deindex = '\n'
Mark Young2ee6aea2018-02-21 15:30:27 -0700392 deindex += 'static inline const char * GetPhysDevFeatureString(uint32_t index) {\n'
Mark Lobodzinski64b432f2017-07-24 16:14:16 -0600393 deindex += ' const char * IndexToPhysDevFeatureString[] = {\n'
394 for feature in pdev_members:
395 deindex += ' "%s",\n' % feature.name
396 deindex += ' };\n\n'
397 deindex += ' return IndexToPhysDevFeatureString[index];\n'
398 deindex += '}\n'
399 return deindex
400 #
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700401 # Combine enum string helper header file preamble with body text and return
402 def GenerateEnumStringHelperHeader(self):
403 enum_string_helper_header = '\n'
404 enum_string_helper_header += '#pragma once\n'
405 enum_string_helper_header += '#ifdef _WIN32\n'
406 enum_string_helper_header += '#pragma warning( disable : 4065 )\n'
407 enum_string_helper_header += '#endif\n'
408 enum_string_helper_header += '\n'
409 enum_string_helper_header += '#include <vulkan/vulkan.h>\n'
410 enum_string_helper_header += '\n'
411 enum_string_helper_header += self.enum_output
Mark Lobodzinski64b432f2017-07-24 16:14:16 -0600412 enum_string_helper_header += self.DeIndexPhysDevFeatures()
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700413 return enum_string_helper_header
414 #
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -0700415 # Helper function for declaring a counter variable only once
416 def DeclareCounter(self, string_var, declare_flag):
417 if declare_flag == False:
418 string_var += ' uint32_t i = 0;\n'
419 declare_flag = True
420 return string_var, declare_flag
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700421 #
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700422 # Combine safe struct helper header file preamble with body text and return
423 def GenerateSafeStructHelperHeader(self):
424 safe_struct_helper_header = '\n'
425 safe_struct_helper_header += '#pragma once\n'
426 safe_struct_helper_header += '#include <vulkan/vulkan.h>\n'
427 safe_struct_helper_header += '\n'
428 safe_struct_helper_header += self.GenerateSafeStructHeader()
429 return safe_struct_helper_header
430 #
431 # safe_struct header: build function prototypes for header file
432 def GenerateSafeStructHeader(self):
433 safe_struct_header = ''
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700434 for item in self.structMembers:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700435 if self.NeedSafeStruct(item) == True:
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700436 safe_struct_header += '\n'
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100437 if item.ifdef_protect is not None:
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700438 safe_struct_header += '#ifdef %s\n' % item.ifdef_protect
439 safe_struct_header += 'struct safe_%s {\n' % (item.name)
440 for member in item.members:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700441 if member.type in self.structNames:
442 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
443 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
444 if member.ispointer:
445 safe_struct_header += ' safe_%s* %s;\n' % (member.type, member.name)
446 else:
447 safe_struct_header += ' safe_%s %s;\n' % (member.type, member.name)
448 continue
449 if member.len is not None and (self.TypeContainsObjectHandle(member.type, True) or self.TypeContainsObjectHandle(member.type, False)):
450 safe_struct_header += ' %s* %s;\n' % (member.type, member.name)
451 else:
452 safe_struct_header += '%s;\n' % member.cdecl
Petr Krause91f7a12017-12-14 20:57:36 +0100453 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 -0600454 safe_struct_header += ' safe_%s(const safe_%s& src);\n' % (item.name, item.name)
Chris Forbesfb633832017-10-03 18:11:54 -0700455 safe_struct_header += ' safe_%s& operator=(const safe_%s& src);\n' % (item.name, item.name)
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700456 safe_struct_header += ' safe_%s();\n' % item.name
457 safe_struct_header += ' ~safe_%s();\n' % item.name
Petr Krause91f7a12017-12-14 20:57:36 +0100458 safe_struct_header += ' void initialize(const %s* in_struct%s);\n' % (item.name, self.custom_construct_params.get(item.name, ''))
459 safe_struct_header += ' void initialize(const safe_%s* src);\n' % (item.name)
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700460 safe_struct_header += ' %s *ptr() { return reinterpret_cast<%s *>(this); }\n' % (item.name, item.name)
461 safe_struct_header += ' %s const *ptr() const { return reinterpret_cast<%s const *>(this); }\n' % (item.name, item.name)
462 safe_struct_header += '};\n'
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100463 if item.ifdef_protect is not None:
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700464 safe_struct_header += '#endif // %s\n' % item.ifdef_protect
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700465 return safe_struct_header
466 #
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600467 # Generate extension helper header file
468 def GenerateExtensionHelperHeader(self):
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600469
470 V_1_0_instance_extensions_promoted_to_core = [
471 'vk_khr_device_group_creation',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600472 'vk_khr_external_fence_capabilities',
John Zulauf2012bca2018-04-25 15:28:47 -0600473 'vk_khr_external_memory_capabilities',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600474 'vk_khr_external_semaphore_capabilities',
475 'vk_khr_get_physical_device_properties_2',
476 ]
477
478 V_1_0_device_extensions_promoted_to_core = [
John Zulauf2012bca2018-04-25 15:28:47 -0600479 'vk_khr_16bit_storage',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600480 'vk_khr_bind_memory_2',
John Zulauf2012bca2018-04-25 15:28:47 -0600481 'vk_khr_dedicated_allocation',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600482 'vk_khr_descriptor_update_template',
John Zulauf2012bca2018-04-25 15:28:47 -0600483 'vk_khr_device_group',
484 'vk_khr_external_fence',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600485 'vk_khr_external_memory',
486 'vk_khr_external_semaphore',
John Zulauf2012bca2018-04-25 15:28:47 -0600487 'vk_khr_get_memory_requirements_2',
488 'vk_khr_maintenance1',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600489 'vk_khr_maintenance2',
John Zulauf2012bca2018-04-25 15:28:47 -0600490 'vk_khr_maintenance3',
491 'vk_khr_multiview',
John Zulauf16826822018-04-25 15:40:32 -0600492 'vk_khr_relaxed_block_layout',
John Zulauf2012bca2018-04-25 15:28:47 -0600493 'vk_khr_sampler_ycbcr_conversion',
John Zulauf16826822018-04-25 15:40:32 -0600494 'vk_khr_shader_draw_parameters',
495 'vk_khr_storage_buffer_storage_class',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600496 'vk_khr_variable_pointers',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600497 ]
John Zulauf16826822018-04-25 15:40:32 -0600498
John Zulauff6feb2a2018-04-12 14:24:57 -0600499 output = [
500 '',
501 '#ifndef VK_EXTENSION_HELPER_H_',
502 '#define VK_EXTENSION_HELPER_H_',
Mark Lobodzinskif6a62282018-06-28 09:21:18 -0600503 '#include <unordered_set>',
John Zulauf072677c2018-04-12 15:34:39 -0600504 '#include <string>',
505 '#include <unordered_map>',
John Zulauff6feb2a2018-04-12 14:24:57 -0600506 '#include <utility>',
Mark Lobodzinskia0555012018-08-15 16:43:49 -0600507 '#include <set>',
John Zulauff6feb2a2018-04-12 14:24:57 -0600508 '',
John Zulauf072677c2018-04-12 15:34:39 -0600509 '#include <vulkan/vulkan.h>',
John Zulauff6feb2a2018-04-12 14:24:57 -0600510 '']
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600511
John Zulauff6feb2a2018-04-12 14:24:57 -0600512 def guarded(ifdef, value):
513 if ifdef is not None:
514 return '\n'.join([ '#ifdef %s' % ifdef, value, '#endif' ])
515 else:
516 return value
John Zulauf380bd942018-04-10 13:12:34 -0600517
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600518 for type in ['Instance', 'Device']:
John Zulauff6feb2a2018-04-12 14:24:57 -0600519 struct_type = '%sExtensions' % type
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600520 if type == 'Instance':
John Zulauff6feb2a2018-04-12 14:24:57 -0600521 extension_dict = self.instance_extension_info
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600522 promoted_ext_list = V_1_0_instance_extensions_promoted_to_core
John Zulauff6feb2a2018-04-12 14:24:57 -0600523 struct_decl = 'struct %s {' % struct_type
524 instance_struct_type = struct_type
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600525 else:
John Zulauff6feb2a2018-04-12 14:24:57 -0600526 extension_dict = self.device_extension_info
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600527 promoted_ext_list = V_1_0_device_extensions_promoted_to_core
John Zulauff6feb2a2018-04-12 14:24:57 -0600528 struct_decl = 'struct %s : public %s {' % (struct_type, instance_struct_type)
529
530 extension_items = sorted(extension_dict.items())
531
532 field_name = { ext_name: re.sub('_extension_name', '', info['define'].lower()) for ext_name, info in extension_items }
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600533 if type == 'Instance':
John Zulauff6feb2a2018-04-12 14:24:57 -0600534 instance_field_name = field_name
John Zulauf072677c2018-04-12 15:34:39 -0600535 instance_extension_dict = extension_dict
536 else:
537 # Get complete field name and extension data for both Instance and Device extensions
538 field_name.update(instance_field_name)
539 extension_dict = extension_dict.copy() # Don't modify the self.<dict> we're pointing to
540 extension_dict.update(instance_extension_dict)
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600541
John Zulauf072677c2018-04-12 15:34:39 -0600542 # Output the data member list
John Zulauff6feb2a2018-04-12 14:24:57 -0600543 struct = [struct_decl]
544 struct.extend([ ' bool %s{false};' % field_name[ext_name] for ext_name, info in extension_items])
John Zulauf072677c2018-04-12 15:34:39 -0600545
Mark Lobodzinskid5f83b92018-12-14 11:02:08 -0700546 # Create struct entries for saving extension count and extension list from Instance, DeviceCreateInfo
547 if type == 'Instance':
548 struct.extend([
549 '',
550 ' std::unordered_set<std::string> device_extension_set;'])
Mark Lobodzinskif6a62282018-06-28 09:21:18 -0600551
John Zulauf072677c2018-04-12 15:34:39 -0600552 # Construct the extension information map -- mapping name to data member (field), and required extensions
553 # The map is contained within a static function member for portability reasons.
554 info_type = '%sInfo' % type
555 info_map_type = '%sMap' % info_type
556 req_type = '%sReq' % type
557 req_vec_type = '%sVec' % req_type
558 struct.extend([
559 '',
560 ' struct %s {' % req_type,
561 ' const bool %s::* enabled;' % struct_type,
562 ' const char *name;',
563 ' };',
564 ' typedef std::vector<%s> %s;' % (req_type, req_vec_type),
565 ' struct %s {' % info_type,
566 ' %s(bool %s::* state_, const %s requires_): state(state_), requires(requires_) {}' % ( info_type, struct_type, req_vec_type),
567 ' bool %s::* state;' % struct_type,
568 ' %s requires;' % req_vec_type,
569 ' };',
570 '',
571 ' typedef std::unordered_map<std::string,%s> %s;' % (info_type, info_map_type),
572 ' static const %s &get_info(const char *name) {' %info_type,
573 ' static const %s info_map = {' % info_map_type ])
574
575 field_format = '&' + struct_type + '::%s'
576 req_format = '{' + field_format+ ', %s}'
577 req_indent = '\n '
578 req_join = ',' + req_indent
579 info_format = (' std::make_pair(%s, ' + info_type + '(' + field_format + ', {%s})),')
580 def format_info(ext_name, info):
581 reqs = req_join.join([req_format % (field_name[req], extension_dict[req]['define']) for req in info['reqs']])
582 return info_format % (info['define'], field_name[ext_name], '{%s}' % (req_indent + reqs) if reqs else '')
583
584 struct.extend([guarded(info['ifdef'], format_info(ext_name, info)) for ext_name, info in extension_items])
585 struct.extend([
586 ' };',
587 '',
588 ' static const %s empty_info {nullptr, %s()};' % (info_type, req_vec_type),
589 ' %s::const_iterator info = info_map.find(name);' % info_map_type,
590 ' if ( info != info_map.cend()) {',
591 ' return info->second;',
592 ' }',
593 ' return empty_info;',
594 ' }',
595 ''])
596
John Zulauff6feb2a2018-04-12 14:24:57 -0600597 if type == 'Instance':
598 struct.extend([
599 ' uint32_t NormalizeApiVersion(uint32_t specified_version) {',
600 ' uint32_t api_version = (specified_version < VK_API_VERSION_1_1) ? VK_API_VERSION_1_0 : VK_API_VERSION_1_1;',
601 ' return api_version;',
602 ' }',
603 '',
604 ' uint32_t InitFromInstanceCreateInfo(uint32_t requested_api_version, const VkInstanceCreateInfo *pCreateInfo) {'])
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600605 else:
John Zulauff6feb2a2018-04-12 14:24:57 -0600606 struct.extend([
John Zulauf072677c2018-04-12 15:34:39 -0600607 ' %s() = default;' % struct_type,
608 ' %s(const %s& instance_ext) : %s(instance_ext) {}' % (struct_type, instance_struct_type, instance_struct_type),
609 '',
610 ' uint32_t InitFromDeviceCreateInfo(const %s *instance_extensions, uint32_t requested_api_version,' % instance_struct_type,
611 ' const VkDeviceCreateInfo *pCreateInfo) {',
612 ' // Initialize: this to defaults, base class fields to input.',
613 ' assert(instance_extensions);',
Mark Lobodzinskif6a62282018-06-28 09:21:18 -0600614 ' *this = %s(*instance_extensions);' % struct_type,
Mark Lobodzinskid5f83b92018-12-14 11:02:08 -0700615 '']),
616 struct.extend([
Mark Lobodzinskif6a62282018-06-28 09:21:18 -0600617 '',
618 ' // Save pCreateInfo device extension list',
619 ' for (uint32_t extn = 0; extn < pCreateInfo->enabledExtensionCount; extn++) {',
620 ' device_extension_set.insert(pCreateInfo->ppEnabledExtensionNames[extn]);',
Mark Lobodzinskid5f83b92018-12-14 11:02:08 -0700621 ' }',
John Zulauff6feb2a2018-04-12 14:24:57 -0600622 '',
623 ' static const std::vector<const char *> V_1_0_promoted_%s_extensions = {' % type.lower() ])
624 struct.extend([' %s_EXTENSION_NAME,' % ext_name.upper() for ext_name in promoted_ext_list])
625 struct.extend([
626 ' };',
627 '',
John Zulauf072677c2018-04-12 15:34:39 -0600628 ' // Initialize struct data, robust to invalid pCreateInfo',
629 ' if (pCreateInfo->ppEnabledExtensionNames) {',
630 ' for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {',
631 ' if (!pCreateInfo->ppEnabledExtensionNames[i]) continue;',
632 ' auto info = get_info(pCreateInfo->ppEnabledExtensionNames[i]);',
633 ' if(info.state) this->*(info.state) = true;',
John Zulauff6feb2a2018-04-12 14:24:57 -0600634 ' }',
635 ' }',
636 ' uint32_t api_version = NormalizeApiVersion(requested_api_version);',
637 ' if (api_version >= VK_API_VERSION_1_1) {',
638 ' for (auto promoted_ext : V_1_0_promoted_%s_extensions) {' % type.lower(),
John Zulauf072677c2018-04-12 15:34:39 -0600639 ' auto info = get_info(promoted_ext);',
640 ' assert(info.state);',
641 ' if (info.state) this->*(info.state) = true;',
John Zulauff6feb2a2018-04-12 14:24:57 -0600642 ' }',
643 ' }',
644 ' return api_version;',
645 ' }',
John Zulauf072677c2018-04-12 15:34:39 -0600646 '};'])
John Zulauff6feb2a2018-04-12 14:24:57 -0600647
Mark Lobodzinskifc9451f2018-01-03 11:18:31 -0700648 # Output reference lists of instance/device extension names
Mark Lobodzinskia0555012018-08-15 16:43:49 -0600649 struct.extend(['', 'static const std::set<std::string> k%sExtensionNames = {' % type])
650 struct.extend([guarded(info['ifdef'], ' %s,' % info['define']) for ext_name, info in extension_items])
651 struct.extend(['};', ''])
John Zulauff6feb2a2018-04-12 14:24:57 -0600652 output.extend(struct)
653
654 output.extend(['', '#endif // VK_EXTENSION_HELPER_H_'])
655 return '\n'.join(output)
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600656 #
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600657 # Combine object types helper header file preamble with body text and return
658 def GenerateObjectTypesHelperHeader(self):
659 object_types_helper_header = '\n'
660 object_types_helper_header += '#pragma once\n'
661 object_types_helper_header += '\n'
662 object_types_helper_header += self.GenerateObjectTypesHeader()
663 return object_types_helper_header
664 #
665 # Object types header: create object enum type header file
666 def GenerateObjectTypesHeader(self):
John Zulauf4fea6622019-04-01 11:38:18 -0600667 object_types_header = '#include "cast_utils.h"\n'
668 object_types_header += '\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700669 object_types_header += '// Object Type enum for validation layer internal object handling\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600670 object_types_header += 'typedef enum VulkanObjectType {\n'
671 object_types_header += ' kVulkanObjectTypeUnknown = 0,\n'
672 enum_num = 1
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600673 type_list = [];
John Zulaufd7435c62018-03-16 11:52:57 -0600674 enum_entry_map = {}
John Zulauf2c2ccd42019-04-05 13:13:13 -0600675 non_dispatchable = {}
676 dispatchable = {}
677 object_type_info = {}
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600678
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600679 # Output enum definition as each handle is processed, saving the names to use for the conversion routine
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600680 for item in self.object_types:
681 fixup_name = item[2:]
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600682 enum_entry = 'kVulkanObjectType%s' % fixup_name
John Zulaufd7435c62018-03-16 11:52:57 -0600683 enum_entry_map[item] = enum_entry
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600684 object_types_header += ' ' + enum_entry
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600685 object_types_header += ' = %d,\n' % enum_num
686 enum_num += 1
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600687 type_list.append(enum_entry)
John Zulauf2c2ccd42019-04-05 13:13:13 -0600688 object_type_info[enum_entry] = { 'VkType': item }
689 # We'll want lists of the dispatchable and non dispatchable handles below with access to the same info
690 if IsHandleTypeNonDispatchable(self.registry.tree, item) :
691 non_dispatchable[item] = enum_entry
692 else:
693 dispatchable[item] = enum_entry
694
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600695 object_types_header += ' kVulkanObjectTypeMax = %d,\n' % enum_num
John Zulaufd7435c62018-03-16 11:52:57 -0600696 object_types_header += ' // Aliases for backwards compatibilty of "promoted" types\n'
697 for (name, alias) in self.object_type_aliases:
698 fixup_name = name[2:]
699 object_types_header += ' kVulkanObjectType{} = {},\n'.format(fixup_name, enum_entry_map[alias])
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600700 object_types_header += '} VulkanObjectType;\n\n'
701
702 # Output name string helper
703 object_types_header += '// Array of object name strings for OBJECT_TYPE enum conversion\n'
Mark Lobodzinski8eb37422017-04-18 14:22:10 -0600704 object_types_header += 'static const char * const object_string[kVulkanObjectTypeMax] = {\n'
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600705 object_types_header += ' "Unknown",\n'
706 for item in self.object_types:
707 fixup_name = item[2:]
708 object_types_header += ' "%s",\n' % fixup_name
709 object_types_header += '};\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600710
John Zulauf311a4892018-03-12 15:48:06 -0600711 # Key creation helper for map comprehensions that convert between k<Name> and VK<Name> symbols
712 def to_key(regex, raw_key): return re.search(regex, raw_key).group(1).lower().replace("_","")
713
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600714 # Output a conversion routine from the layer object definitions to the debug report definitions
John Zulauf311a4892018-03-12 15:48:06 -0600715 # As the VK_DEBUG_REPORT types are not being updated, specify UNKNOWN for unmatched types
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600716 object_types_header += '\n'
Mark Young1ded24b2017-05-30 14:53:50 -0600717 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 -0600718 object_types_header += 'const VkDebugReportObjectTypeEXT get_debug_report_enum[] = {\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700719 object_types_header += ' VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, // kVulkanObjectTypeUnknown\n'
Gabríel Arthúr Pétursson1a271d02018-03-18 17:34:01 +0000720
John Zulauf311a4892018-03-12 15:48:06 -0600721 dbg_re = '^VK_DEBUG_REPORT_OBJECT_TYPE_(.*)_EXT$'
722 dbg_map = {to_key(dbg_re, dbg) : dbg for dbg in self.debug_report_object_types}
723 dbg_default = 'VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT'
John Zulauf2c2ccd42019-04-05 13:13:13 -0600724
John Zulauf311a4892018-03-12 15:48:06 -0600725 for object_type in type_list:
726 vk_object_type = dbg_map.get(object_type.replace("kVulkanObjectType", "").lower(), dbg_default)
727 object_types_header += ' %s, // %s\n' % (vk_object_type, object_type)
John Zulauf2c2ccd42019-04-05 13:13:13 -0600728 object_type_info[object_type]['DbgType'] = vk_object_type
Mark Lobodzinskiecf0ae12017-04-13 08:36:18 -0600729 object_types_header += '};\n'
Mark Young1ded24b2017-05-30 14:53:50 -0600730
731 # Output a conversion routine from the layer object definitions to the core object type definitions
John Zulauf311a4892018-03-12 15:48:06 -0600732 # This will intentionally *fail* for unmatched types as the VK_OBJECT_TYPE list should match the kVulkanObjectType list
Mark Young1ded24b2017-05-30 14:53:50 -0600733 object_types_header += '\n'
734 object_types_header += '// Helper array to get Official Vulkan VkObjectType enum from the internal layers version\n'
735 object_types_header += 'const VkObjectType get_object_type_enum[] = {\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700736 object_types_header += ' VK_OBJECT_TYPE_UNKNOWN, // kVulkanObjectTypeUnknown\n'
John Zulauf311a4892018-03-12 15:48:06 -0600737
738 vko_re = '^VK_OBJECT_TYPE_(.*)'
739 vko_map = {to_key(vko_re, vko) : vko for vko in self.core_object_types}
Mark Young1ded24b2017-05-30 14:53:50 -0600740 for object_type in type_list:
John Zulauf311a4892018-03-12 15:48:06 -0600741 vk_object_type = vko_map[object_type.replace("kVulkanObjectType", "").lower()]
742 object_types_header += ' %s, // %s\n' % (vk_object_type, object_type)
John Zulauf2c2ccd42019-04-05 13:13:13 -0600743 object_type_info[object_type]['VkoType'] = vk_object_type
Mark Young1ded24b2017-05-30 14:53:50 -0600744 object_types_header += '};\n'
745
Mark Young6ba8abe2017-11-09 10:37:04 -0700746 # Create a function to convert from VkDebugReportObjectTypeEXT to VkObjectType
747 object_types_header += '\n'
748 object_types_header += '// Helper function to convert from VkDebugReportObjectTypeEXT to VkObjectType\n'
Mark Young8504ba62018-03-21 13:35:34 -0600749 object_types_header += 'static inline VkObjectType convertDebugReportObjectToCoreObject(VkDebugReportObjectTypeEXT debug_report_obj){\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700750 object_types_header += ' if (debug_report_obj == VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT) {\n'
751 object_types_header += ' return VK_OBJECT_TYPE_UNKNOWN;\n'
752 for core_object_type in self.core_object_types:
753 core_target_type = core_object_type.replace("VK_OBJECT_TYPE_", "").lower()
754 core_target_type = core_target_type.replace("_", "")
755 for dr_object_type in self.debug_report_object_types:
756 dr_target_type = dr_object_type.replace("VK_DEBUG_REPORT_OBJECT_TYPE_", "").lower()
757 dr_target_type = dr_target_type[:-4]
758 dr_target_type = dr_target_type.replace("_", "")
759 if core_target_type == dr_target_type:
760 object_types_header += ' } else if (debug_report_obj == %s) {\n' % dr_object_type
761 object_types_header += ' return %s;\n' % core_object_type
762 break
763 object_types_header += ' }\n'
764 object_types_header += ' return VK_OBJECT_TYPE_UNKNOWN;\n'
765 object_types_header += '}\n'
766
767 # Create a function to convert from VkObjectType to VkDebugReportObjectTypeEXT
768 object_types_header += '\n'
769 object_types_header += '// Helper function to convert from VkDebugReportObjectTypeEXT to VkObjectType\n'
Mark Young8504ba62018-03-21 13:35:34 -0600770 object_types_header += 'static inline VkDebugReportObjectTypeEXT convertCoreObjectToDebugReportObject(VkObjectType core_report_obj){\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700771 object_types_header += ' if (core_report_obj == VK_OBJECT_TYPE_UNKNOWN) {\n'
772 object_types_header += ' return VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT;\n'
773 for core_object_type in self.core_object_types:
774 core_target_type = core_object_type.replace("VK_OBJECT_TYPE_", "").lower()
775 core_target_type = core_target_type.replace("_", "")
776 for dr_object_type in self.debug_report_object_types:
777 dr_target_type = dr_object_type.replace("VK_DEBUG_REPORT_OBJECT_TYPE_", "").lower()
778 dr_target_type = dr_target_type[:-4]
779 dr_target_type = dr_target_type.replace("_", "")
780 if core_target_type == dr_target_type:
781 object_types_header += ' } else if (core_report_obj == %s) {\n' % core_object_type
782 object_types_header += ' return %s;\n' % dr_object_type
783 break
784 object_types_header += ' }\n'
785 object_types_header += ' return VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT;\n'
786 object_types_header += '}\n'
John Zulauf2c2ccd42019-04-05 13:13:13 -0600787
788 traits_format = Outdent('''
789 template <> struct VkHandleInfo<{vk_type}> {{
790 static const VulkanObjectType kVulkanObjectType = {obj_type};
791 static const VkDebugReportObjectTypeEXT kDebugReportObjectType = {dbg_type};
792 static const VkObjectType kVkObjectType = {vko_type};
793 static const char* Typename() {{
794 return "{vk_type}";
795 }}
796 }};
797 template <> struct VulkanObjectTypeInfo<{obj_type}> {{
798 typedef {vk_type} Type;
799 }};
800 ''')
801
802 object_types_header += Outdent('''
803 // Traits objects from each type statically map from Vk<handleType> to the various enums
804 template <typename VkType> struct VkHandleInfo {};
805 template <VulkanObjectType id> struct VulkanObjectTypeInfo {};
806
807 // The following line must match the vulkan_core.h condition guarding VK_DEFINE_NON_DISPATCHABLE_HANDLE
808 #if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__)) || defined(_M_X64) || defined(__ia64) || \
809 defined(_M_IA64) || defined(__aarch64__) || defined(__powerpc64__)
810 #define TYPESAFE_NONDISPATCHABLE_HANDLES
811 #else
812 VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkNonDispatchableHandle)
813 ''') +'\n'
814 object_types_header += traits_format.format(vk_type='VkNonDispatchableHandle', obj_type='kVulkanObjectTypeUnknown',
815 dbg_type='VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT',
816 vko_type='VK_OBJECT_TYPE_UNKNOWN') + '\n'
817 object_types_header += '#endif // VK_DEFINE_HANDLE logic duplication\n'
818
819 for vk_type, object_type in dispatchable.items():
820 info = object_type_info[object_type]
821 object_types_header += traits_format.format(vk_type=vk_type, obj_type=object_type, dbg_type=info['DbgType'],
822 vko_type=info['VkoType'])
823 object_types_header += '#ifdef TYPESAFE_NONDISPATCHABLE_HANDLES\n'
824 for vk_type, object_type in non_dispatchable.items():
825 info = object_type_info[object_type]
826 object_types_header += traits_format.format(vk_type=vk_type, obj_type=object_type, dbg_type=info['DbgType'],
827 vko_type=info['VkoType'])
828 object_types_header += '#endif // TYPESAFE_NONDISPATCHABLE_HANDLES\n'
829
830 object_types_header += Outdent('''
831 struct VulkanTypedHandle {
832 uint64_t handle;
833 VulkanObjectType type;
834 template <typename Handle>
John Zulauf4fea6622019-04-01 11:38:18 -0600835 VulkanTypedHandle(Handle handle_, VulkanObjectType type_) :
836 handle(CastToUint64(handle_)),
837 type(type_) {
838 #ifdef TYPESAFE_NONDISPATCHABLE_HANDLES
839 // For 32 bit it's not always safe to check for traits <-> type
840 // as all non-dispatchable handles have the same type-id and thus traits,
841 // but on 64 bit we can validate the passed type matches the passed handle
842 assert(type == VkHandleInfo<Handle>::kVulkanObjectType);
843 #endif // TYPESAFE_NONDISPATCHABLE_HANDLES
844 }
845 template <typename Handle>
846 Handle Cast() const {
847 #ifdef TYPESAFE_NONDISPATCHABLE_HANDLES
848 assert(type == VkHandleInfo<Handle>::kVulkanObjectType);
849 #endif // TYPESAFE_NONDISPATCHABLE_HANDLES
850 return CastFromUint64<Handle>(handle);
851 }
John Zulauf2c2ccd42019-04-05 13:13:13 -0600852 VulkanTypedHandle() :
853 handle(VK_NULL_HANDLE),
854 type(kVulkanObjectTypeUnknown) {}
855 }; ''') +'\n'
856
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600857 return object_types_header
858 #
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700859 # Determine if a structure needs a safe_struct helper function
860 # That is, it has an sType or one of its members is a pointer
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700861 def NeedSafeStruct(self, structure):
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700862 if 'sType' == structure.name:
863 return True
864 for member in structure.members:
865 if member.ispointer == True:
866 return True
867 return False
868 #
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700869 # Combine safe struct helper source file preamble with body text and return
870 def GenerateSafeStructHelperSource(self):
871 safe_struct_helper_source = '\n'
872 safe_struct_helper_source += '#include "vk_safe_struct.h"\n'
873 safe_struct_helper_source += '#include <string.h>\n'
874 safe_struct_helper_source += '\n'
875 safe_struct_helper_source += self.GenerateSafeStructSource()
876 return safe_struct_helper_source
877 #
878 # safe_struct source -- create bodies of safe struct helper functions
879 def GenerateSafeStructSource(self):
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700880 safe_struct_body = []
Mark Lobodzinski560729b2017-03-06 08:59:14 -0700881 wsi_structs = ['VkXlibSurfaceCreateInfoKHR',
882 'VkXcbSurfaceCreateInfoKHR',
883 'VkWaylandSurfaceCreateInfoKHR',
Mark Lobodzinski560729b2017-03-06 08:59:14 -0700884 'VkAndroidSurfaceCreateInfoKHR',
885 'VkWin32SurfaceCreateInfoKHR'
886 ]
Courtney Goeltzenleuchterdb6c2332018-06-28 14:32:55 -0600887
888 # For abstract types just want to save the pointer away
889 # since we cannot make a copy.
890 abstract_types = ['AHardwareBuffer',
891 'ANativeWindow',
892 ]
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700893 for item in self.structMembers:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700894 if self.NeedSafeStruct(item) == False:
895 continue
Mark Lobodzinski560729b2017-03-06 08:59:14 -0700896 if item.name in wsi_structs:
897 continue
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100898 if item.ifdef_protect is not None:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700899 safe_struct_body.append("#ifdef %s\n" % item.ifdef_protect)
900 ss_name = "safe_%s" % item.name
901 init_list = '' # list of members in struct constructor initializer
902 default_init_list = '' # Default constructor just inits ptrs to nullptr in initializer
903 init_func_txt = '' # Txt for initialize() function that takes struct ptr and inits members
904 construct_txt = '' # Body of constuctor as well as body of initialize() func following init_func_txt
905 destruct_txt = ''
Petr Krause91f7a12017-12-14 20:57:36 +0100906
907 custom_construct_txt = {
908 # VkWriteDescriptorSet is special case because pointers may be non-null but ignored
909 'VkWriteDescriptorSet' :
910 ' switch (descriptorType) {\n'
911 ' case VK_DESCRIPTOR_TYPE_SAMPLER:\n'
912 ' case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:\n'
913 ' case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:\n'
914 ' case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:\n'
915 ' case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:\n'
916 ' if (descriptorCount && in_struct->pImageInfo) {\n'
917 ' pImageInfo = new VkDescriptorImageInfo[descriptorCount];\n'
918 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
919 ' pImageInfo[i] = in_struct->pImageInfo[i];\n'
920 ' }\n'
921 ' }\n'
922 ' break;\n'
923 ' case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:\n'
924 ' case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:\n'
925 ' case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:\n'
926 ' case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:\n'
927 ' if (descriptorCount && in_struct->pBufferInfo) {\n'
928 ' pBufferInfo = new VkDescriptorBufferInfo[descriptorCount];\n'
929 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
930 ' pBufferInfo[i] = in_struct->pBufferInfo[i];\n'
931 ' }\n'
932 ' }\n'
933 ' break;\n'
934 ' case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:\n'
935 ' case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:\n'
936 ' if (descriptorCount && in_struct->pTexelBufferView) {\n'
937 ' pTexelBufferView = new VkBufferView[descriptorCount];\n'
938 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
939 ' pTexelBufferView[i] = in_struct->pTexelBufferView[i];\n'
940 ' }\n'
941 ' }\n'
942 ' break;\n'
943 ' default:\n'
944 ' break;\n'
945 ' }\n',
Petr Kraus42f6f8d2017-12-17 17:37:33 +0100946 'VkShaderModuleCreateInfo' :
Petr Krause91f7a12017-12-14 20:57:36 +0100947 ' if (in_struct->pCode) {\n'
948 ' pCode = reinterpret_cast<uint32_t *>(new uint8_t[codeSize]);\n'
949 ' memcpy((void *)pCode, (void *)in_struct->pCode, codeSize);\n'
950 ' }\n',
951 # VkGraphicsPipelineCreateInfo is special case because its pointers may be non-null but ignored
952 'VkGraphicsPipelineCreateInfo' :
953 ' if (stageCount && in_struct->pStages) {\n'
954 ' pStages = new safe_VkPipelineShaderStageCreateInfo[stageCount];\n'
955 ' for (uint32_t i=0; i<stageCount; ++i) {\n'
956 ' pStages[i].initialize(&in_struct->pStages[i]);\n'
957 ' }\n'
958 ' }\n'
959 ' if (in_struct->pVertexInputState)\n'
960 ' pVertexInputState = new safe_VkPipelineVertexInputStateCreateInfo(in_struct->pVertexInputState);\n'
961 ' else\n'
962 ' pVertexInputState = NULL;\n'
963 ' if (in_struct->pInputAssemblyState)\n'
964 ' pInputAssemblyState = new safe_VkPipelineInputAssemblyStateCreateInfo(in_struct->pInputAssemblyState);\n'
965 ' else\n'
966 ' pInputAssemblyState = NULL;\n'
967 ' bool has_tessellation_stage = false;\n'
968 ' if (stageCount && pStages)\n'
969 ' for (uint32_t i=0; i<stageCount && !has_tessellation_stage; ++i)\n'
970 ' if (pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)\n'
971 ' has_tessellation_stage = true;\n'
972 ' if (in_struct->pTessellationState && has_tessellation_stage)\n'
973 ' pTessellationState = new safe_VkPipelineTessellationStateCreateInfo(in_struct->pTessellationState);\n'
974 ' else\n'
975 ' pTessellationState = NULL; // original pTessellationState pointer ignored\n'
976 ' bool has_rasterization = in_struct->pRasterizationState ? !in_struct->pRasterizationState->rasterizerDiscardEnable : false;\n'
977 ' if (in_struct->pViewportState && has_rasterization) {\n'
978 ' bool is_dynamic_viewports = false;\n'
979 ' bool is_dynamic_scissors = false;\n'
980 ' if (in_struct->pDynamicState && in_struct->pDynamicState->pDynamicStates) {\n'
981 ' for (uint32_t i = 0; i < in_struct->pDynamicState->dynamicStateCount && !is_dynamic_viewports; ++i)\n'
982 ' if (in_struct->pDynamicState->pDynamicStates[i] == VK_DYNAMIC_STATE_VIEWPORT)\n'
983 ' is_dynamic_viewports = true;\n'
984 ' for (uint32_t i = 0; i < in_struct->pDynamicState->dynamicStateCount && !is_dynamic_scissors; ++i)\n'
985 ' if (in_struct->pDynamicState->pDynamicStates[i] == VK_DYNAMIC_STATE_SCISSOR)\n'
986 ' is_dynamic_scissors = true;\n'
987 ' }\n'
988 ' pViewportState = new safe_VkPipelineViewportStateCreateInfo(in_struct->pViewportState, is_dynamic_viewports, is_dynamic_scissors);\n'
989 ' } else\n'
990 ' pViewportState = NULL; // original pViewportState pointer ignored\n'
991 ' if (in_struct->pRasterizationState)\n'
992 ' pRasterizationState = new safe_VkPipelineRasterizationStateCreateInfo(in_struct->pRasterizationState);\n'
993 ' else\n'
994 ' pRasterizationState = NULL;\n'
995 ' if (in_struct->pMultisampleState && has_rasterization)\n'
996 ' pMultisampleState = new safe_VkPipelineMultisampleStateCreateInfo(in_struct->pMultisampleState);\n'
997 ' else\n'
998 ' pMultisampleState = NULL; // original pMultisampleState pointer ignored\n'
999 ' // needs a tracked subpass state uses_depthstencil_attachment\n'
1000 ' if (in_struct->pDepthStencilState && has_rasterization && uses_depthstencil_attachment)\n'
1001 ' pDepthStencilState = new safe_VkPipelineDepthStencilStateCreateInfo(in_struct->pDepthStencilState);\n'
1002 ' else\n'
1003 ' pDepthStencilState = NULL; // original pDepthStencilState pointer ignored\n'
1004 ' // needs a tracked subpass state usesColorAttachment\n'
1005 ' if (in_struct->pColorBlendState && has_rasterization && uses_color_attachment)\n'
1006 ' pColorBlendState = new safe_VkPipelineColorBlendStateCreateInfo(in_struct->pColorBlendState);\n'
1007 ' else\n'
1008 ' pColorBlendState = NULL; // original pColorBlendState pointer ignored\n'
1009 ' if (in_struct->pDynamicState)\n'
1010 ' pDynamicState = new safe_VkPipelineDynamicStateCreateInfo(in_struct->pDynamicState);\n'
1011 ' else\n'
1012 ' pDynamicState = NULL;\n',
1013 # VkPipelineViewportStateCreateInfo is special case because its pointers may be non-null but ignored
1014 'VkPipelineViewportStateCreateInfo' :
1015 ' if (in_struct->pViewports && !is_dynamic_viewports) {\n'
1016 ' pViewports = new VkViewport[in_struct->viewportCount];\n'
1017 ' memcpy ((void *)pViewports, (void *)in_struct->pViewports, sizeof(VkViewport)*in_struct->viewportCount);\n'
1018 ' }\n'
1019 ' else\n'
1020 ' pViewports = NULL;\n'
1021 ' if (in_struct->pScissors && !is_dynamic_scissors) {\n'
1022 ' pScissors = new VkRect2D[in_struct->scissorCount];\n'
1023 ' memcpy ((void *)pScissors, (void *)in_struct->pScissors, sizeof(VkRect2D)*in_struct->scissorCount);\n'
1024 ' }\n'
1025 ' else\n'
1026 ' pScissors = NULL;\n',
Petr Kraus42f6f8d2017-12-17 17:37:33 +01001027 # VkDescriptorSetLayoutBinding is special case because its pImmutableSamplers pointer may be non-null but ignored
1028 'VkDescriptorSetLayoutBinding' :
1029 ' const bool sampler_type = in_struct->descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER || in_struct->descriptorType == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;\n'
1030 ' if (descriptorCount && in_struct->pImmutableSamplers && sampler_type) {\n'
1031 ' pImmutableSamplers = new VkSampler[descriptorCount];\n'
1032 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
1033 ' pImmutableSamplers[i] = in_struct->pImmutableSamplers[i];\n'
1034 ' }\n'
1035 ' }\n',
Petr Krause91f7a12017-12-14 20:57:36 +01001036 }
1037
1038 custom_copy_txt = {
1039 # VkGraphicsPipelineCreateInfo is special case because it has custom construct parameters
1040 'VkGraphicsPipelineCreateInfo' :
1041 ' if (stageCount && src.pStages) {\n'
1042 ' pStages = new safe_VkPipelineShaderStageCreateInfo[stageCount];\n'
1043 ' for (uint32_t i=0; i<stageCount; ++i) {\n'
1044 ' pStages[i].initialize(&src.pStages[i]);\n'
1045 ' }\n'
1046 ' }\n'
1047 ' if (src.pVertexInputState)\n'
1048 ' pVertexInputState = new safe_VkPipelineVertexInputStateCreateInfo(*src.pVertexInputState);\n'
1049 ' else\n'
1050 ' pVertexInputState = NULL;\n'
1051 ' if (src.pInputAssemblyState)\n'
1052 ' pInputAssemblyState = new safe_VkPipelineInputAssemblyStateCreateInfo(*src.pInputAssemblyState);\n'
1053 ' else\n'
1054 ' pInputAssemblyState = NULL;\n'
1055 ' bool has_tessellation_stage = false;\n'
1056 ' if (stageCount && pStages)\n'
1057 ' for (uint32_t i=0; i<stageCount && !has_tessellation_stage; ++i)\n'
1058 ' if (pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)\n'
1059 ' has_tessellation_stage = true;\n'
1060 ' if (src.pTessellationState && has_tessellation_stage)\n'
1061 ' pTessellationState = new safe_VkPipelineTessellationStateCreateInfo(*src.pTessellationState);\n'
1062 ' else\n'
1063 ' pTessellationState = NULL; // original pTessellationState pointer ignored\n'
1064 ' bool has_rasterization = src.pRasterizationState ? !src.pRasterizationState->rasterizerDiscardEnable : false;\n'
1065 ' if (src.pViewportState && has_rasterization) {\n'
1066 ' pViewportState = new safe_VkPipelineViewportStateCreateInfo(*src.pViewportState);\n'
1067 ' } else\n'
1068 ' pViewportState = NULL; // original pViewportState pointer ignored\n'
1069 ' if (src.pRasterizationState)\n'
1070 ' pRasterizationState = new safe_VkPipelineRasterizationStateCreateInfo(*src.pRasterizationState);\n'
1071 ' else\n'
1072 ' pRasterizationState = NULL;\n'
1073 ' if (src.pMultisampleState && has_rasterization)\n'
1074 ' pMultisampleState = new safe_VkPipelineMultisampleStateCreateInfo(*src.pMultisampleState);\n'
1075 ' else\n'
1076 ' pMultisampleState = NULL; // original pMultisampleState pointer ignored\n'
1077 ' if (src.pDepthStencilState && has_rasterization)\n'
1078 ' pDepthStencilState = new safe_VkPipelineDepthStencilStateCreateInfo(*src.pDepthStencilState);\n'
1079 ' else\n'
1080 ' pDepthStencilState = NULL; // original pDepthStencilState pointer ignored\n'
1081 ' if (src.pColorBlendState && has_rasterization)\n'
1082 ' pColorBlendState = new safe_VkPipelineColorBlendStateCreateInfo(*src.pColorBlendState);\n'
1083 ' else\n'
1084 ' pColorBlendState = NULL; // original pColorBlendState pointer ignored\n'
1085 ' if (src.pDynamicState)\n'
1086 ' pDynamicState = new safe_VkPipelineDynamicStateCreateInfo(*src.pDynamicState);\n'
1087 ' else\n'
1088 ' pDynamicState = NULL;\n',
1089 # VkPipelineViewportStateCreateInfo is special case because it has custom construct parameters
1090 'VkPipelineViewportStateCreateInfo' :
1091 ' if (src.pViewports) {\n'
1092 ' pViewports = new VkViewport[src.viewportCount];\n'
1093 ' memcpy ((void *)pViewports, (void *)src.pViewports, sizeof(VkViewport)*src.viewportCount);\n'
1094 ' }\n'
1095 ' else\n'
1096 ' pViewports = NULL;\n'
1097 ' if (src.pScissors) {\n'
1098 ' pScissors = new VkRect2D[src.scissorCount];\n'
1099 ' memcpy ((void *)pScissors, (void *)src.pScissors, sizeof(VkRect2D)*src.scissorCount);\n'
1100 ' }\n'
1101 ' else\n'
1102 ' pScissors = NULL;\n',
1103 }
1104
Mike Schuchardt81485762017-09-04 11:38:42 -06001105 custom_destruct_txt = {'VkShaderModuleCreateInfo' :
1106 ' if (pCode)\n'
1107 ' delete[] reinterpret_cast<const uint8_t *>(pCode);\n' }
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001108
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001109 for member in item.members:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001110 m_type = member.type
1111 if member.type in self.structNames:
1112 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
1113 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
1114 m_type = 'safe_%s' % member.type
1115 if member.ispointer and 'safe_' not in m_type and self.TypeContainsObjectHandle(member.type, False) == False:
1116 # 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 -07001117 if m_type in ['void', 'char']:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001118 # For these exceptions just copy initial value over for now
1119 init_list += '\n %s(in_struct->%s),' % (member.name, member.name)
1120 init_func_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001121 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001122 default_init_list += '\n %s(nullptr),' % (member.name)
1123 init_list += '\n %s(nullptr),' % (member.name)
Courtney Goeltzenleuchterdb6c2332018-06-28 14:32:55 -06001124 if m_type in abstract_types:
1125 construct_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
1126 else:
1127 init_func_txt += ' %s = nullptr;\n' % (member.name)
1128 if 'pNext' != member.name and 'void' not in m_type:
1129 if not member.isstaticarray and (member.len is None or '/' in member.len):
1130 construct_txt += ' if (in_struct->%s) {\n' % member.name
1131 construct_txt += ' %s = new %s(*in_struct->%s);\n' % (member.name, m_type, member.name)
1132 construct_txt += ' }\n'
1133 destruct_txt += ' if (%s)\n' % member.name
1134 destruct_txt += ' delete %s;\n' % member.name
1135 else:
1136 construct_txt += ' if (in_struct->%s) {\n' % member.name
1137 construct_txt += ' %s = new %s[in_struct->%s];\n' % (member.name, m_type, member.len)
1138 construct_txt += ' memcpy ((void *)%s, (void *)in_struct->%s, sizeof(%s)*in_struct->%s);\n' % (member.name, member.name, m_type, member.len)
1139 construct_txt += ' }\n'
1140 destruct_txt += ' if (%s)\n' % member.name
1141 destruct_txt += ' delete[] %s;\n' % member.name
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001142 elif member.isstaticarray or member.len is not None:
1143 if member.len is None:
1144 # Extract length of static array by grabbing val between []
1145 static_array_size = re.match(r"[^[]*\[([^]]*)\]", member.cdecl)
1146 construct_txt += ' for (uint32_t i=0; i<%s; ++i) {\n' % static_array_size.group(1)
1147 construct_txt += ' %s[i] = in_struct->%s[i];\n' % (member.name, member.name)
1148 construct_txt += ' }\n'
1149 else:
1150 # Init array ptr to NULL
1151 default_init_list += '\n %s(nullptr),' % member.name
1152 init_list += '\n %s(nullptr),' % member.name
1153 init_func_txt += ' %s = nullptr;\n' % member.name
1154 array_element = 'in_struct->%s[i]' % member.name
1155 if member.type in self.structNames:
1156 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
1157 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
1158 array_element = '%s(&in_struct->safe_%s[i])' % (member.type, member.name)
1159 construct_txt += ' if (%s && in_struct->%s) {\n' % (member.len, member.name)
1160 construct_txt += ' %s = new %s[%s];\n' % (member.name, m_type, member.len)
1161 destruct_txt += ' if (%s)\n' % member.name
1162 destruct_txt += ' delete[] %s;\n' % member.name
1163 construct_txt += ' for (uint32_t i=0; i<%s; ++i) {\n' % (member.len)
1164 if 'safe_' in m_type:
1165 construct_txt += ' %s[i].initialize(&in_struct->%s[i]);\n' % (member.name, member.name)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001166 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001167 construct_txt += ' %s[i] = %s;\n' % (member.name, array_element)
1168 construct_txt += ' }\n'
1169 construct_txt += ' }\n'
1170 elif member.ispointer == True:
1171 construct_txt += ' if (in_struct->%s)\n' % member.name
1172 construct_txt += ' %s = new %s(in_struct->%s);\n' % (member.name, m_type, member.name)
1173 construct_txt += ' else\n'
1174 construct_txt += ' %s = NULL;\n' % member.name
1175 destruct_txt += ' if (%s)\n' % member.name
1176 destruct_txt += ' delete %s;\n' % member.name
1177 elif 'safe_' in m_type:
1178 init_list += '\n %s(&in_struct->%s),' % (member.name, member.name)
1179 init_func_txt += ' %s.initialize(&in_struct->%s);\n' % (member.name, member.name)
1180 else:
1181 init_list += '\n %s(in_struct->%s),' % (member.name, member.name)
1182 init_func_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
1183 if '' != init_list:
1184 init_list = init_list[:-1] # hack off final comma
1185 if item.name in custom_construct_txt:
1186 construct_txt = custom_construct_txt[item.name]
Mike Schuchardt81485762017-09-04 11:38:42 -06001187 if item.name in custom_destruct_txt:
1188 destruct_txt = custom_destruct_txt[item.name]
Petr Krause91f7a12017-12-14 20:57:36 +01001189 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 -07001190 if '' != default_init_list:
1191 default_init_list = " :%s" % (default_init_list[:-1])
1192 safe_struct_body.append("\n%s::%s()%s\n{}" % (ss_name, ss_name, default_init_list))
1193 # Create slight variation of init and construct txt for copy constructor that takes a src object reference vs. struct ptr
1194 copy_construct_init = init_func_txt.replace('in_struct->', 'src.')
1195 copy_construct_txt = construct_txt.replace(' (in_struct->', ' (src.') # Exclude 'if' blocks from next line
1196 copy_construct_txt = copy_construct_txt.replace('(in_struct->', '(*src.') # Pass object to copy constructors
1197 copy_construct_txt = copy_construct_txt.replace('in_struct->', 'src.') # Modify remaining struct refs for src object
Petr Krause91f7a12017-12-14 20:57:36 +01001198 if item.name in custom_copy_txt:
1199 copy_construct_txt = custom_copy_txt[item.name]
Chris Forbesfb633832017-10-03 18:11:54 -07001200 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 -06001201 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 -07001202 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 -07001203 safe_struct_body.append("\n%s::~%s()\n{\n%s}" % (ss_name, ss_name, destruct_txt))
Petr Krause91f7a12017-12-14 20:57:36 +01001204 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 -07001205 # Copy initializer uses same txt as copy constructor but has a ptr and not a reference
1206 init_copy = copy_construct_init.replace('src.', 'src->')
1207 init_construct = copy_construct_txt.replace('src.', 'src->')
Mark Lobodzinski5cd08512017-09-12 09:50:25 -06001208 safe_struct_body.append("\nvoid %s::initialize(const %s* src)\n{\n%s%s}" % (ss_name, ss_name, init_copy, init_construct))
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +01001209 if item.ifdef_protect is not None:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001210 safe_struct_body.append("#endif // %s\n" % item.ifdef_protect)
1211 return "\n".join(safe_struct_body)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001212 #
John Zulaufde972ac2017-10-26 12:07:05 -06001213 # Generate the type map
1214 def GenerateTypeMapHelperHeader(self):
1215 prefix = 'Lvl'
1216 fprefix = 'lvl_'
1217 typemap = prefix + 'TypeMap'
1218 idmap = prefix + 'STypeMap'
John Zulaufde972ac2017-10-26 12:07:05 -06001219 type_member = 'Type'
1220 id_member = 'kSType'
Mike Schuchardt97662b02017-12-06 13:31:29 -07001221 id_decl = 'static const VkStructureType '
Locke6b6b7382019-04-16 15:08:49 -06001222 generic_header = 'VkBaseOutStructure'
John Zulaufde972ac2017-10-26 12:07:05 -06001223 typename_func = fprefix + 'typename'
1224 idname_func = fprefix + 'stype_name'
1225 find_func = fprefix + 'find_in_chain'
John Zulauf65ac9d52018-01-23 11:20:50 -07001226 init_func = fprefix + 'init_struct'
John Zulaufde972ac2017-10-26 12:07:05 -06001227
1228 explanatory_comment = '\n'.join((
1229 '// These empty generic templates are specialized for each type with sType',
1230 '// members and for each sType -- providing a two way map between structure',
Mike Schuchardt97662b02017-12-06 13:31:29 -07001231 '// types and sTypes'))
John Zulaufde972ac2017-10-26 12:07:05 -06001232
1233 empty_typemap = 'template <typename T> struct ' + typemap + ' {};'
1234 typemap_format = 'template <> struct {template}<{typename}> {{\n'
John Zulaufde972ac2017-10-26 12:07:05 -06001235 typemap_format += ' {id_decl}{id_member} = {id_value};\n'
1236 typemap_format += '}};\n'
1237
1238 empty_idmap = 'template <VkStructureType id> struct ' + idmap + ' {};'
1239 idmap_format = ''.join((
1240 'template <> struct {template}<{id_value}> {{\n',
1241 ' typedef {typename} {typedef};\n',
John Zulaufde972ac2017-10-26 12:07:05 -06001242 '}};\n'))
1243
1244 # Define the utilities (here so any renaming stays consistent), if this grows large, refactor to a fixed .h file
1245 utilities_format = '\n'.join((
John Zulaufde972ac2017-10-26 12:07:05 -06001246 '// Find an entry of the given type in the pNext chain',
1247 'template <typename T> const T *{find_func}(const void *next) {{',
1248 ' const {header} *current = reinterpret_cast<const {header} *>(next);',
1249 ' const T *found = nullptr;',
1250 ' while (current) {{',
1251 ' if ({type_map}<T>::{id_member} == current->sType) {{',
1252 ' found = reinterpret_cast<const T*>(current);',
1253 ' current = nullptr;',
1254 ' }} else {{',
1255 ' current = current->pNext;',
1256 ' }}',
1257 ' }}',
1258 ' return found;',
1259 '}}',
John Zulauf65ac9d52018-01-23 11:20:50 -07001260 '',
1261 '// Init the header of an sType struct with pNext',
1262 'template <typename T> T {init_func}(void *p_next) {{',
1263 ' T out = {{}};',
1264 ' out.sType = {type_map}<T>::kSType;',
1265 ' out.pNext = p_next;',
1266 ' return out;',
1267 '}}',
1268 '',
1269 '// Init the header of an sType struct',
1270 'template <typename T> T {init_func}() {{',
1271 ' T out = {{}};',
1272 ' out.sType = {type_map}<T>::kSType;',
1273 ' return out;',
1274 '}}',
1275
Mike Schuchardt97662b02017-12-06 13:31:29 -07001276 ''))
John Zulaufde972ac2017-10-26 12:07:05 -06001277
1278 code = []
John Zulauf65ac9d52018-01-23 11:20:50 -07001279
1280 # Generate header
John Zulaufde972ac2017-10-26 12:07:05 -06001281 code.append('\n'.join((
1282 '#pragma once',
1283 '#include <vulkan/vulkan.h>\n',
1284 explanatory_comment, '',
1285 empty_idmap,
John Zulauf65ac9d52018-01-23 11:20:50 -07001286 empty_typemap, '')))
John Zulaufde972ac2017-10-26 12:07:05 -06001287
1288 # Generate the specializations for each type and stype
John Zulaufde972ac2017-10-26 12:07:05 -06001289 for item in self.structMembers:
1290 typename = item.name
1291 info = self.structTypes.get(typename)
1292 if not info:
1293 continue
1294
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +01001295 if item.ifdef_protect is not None:
John Zulaufde972ac2017-10-26 12:07:05 -06001296 code.append('#ifdef %s' % item.ifdef_protect)
1297
1298 code.append('// Map type {} to id {}'.format(typename, info.value))
1299 code.append(typemap_format.format(template=typemap, typename=typename, id_value=info.value,
Mike Schuchardt97662b02017-12-06 13:31:29 -07001300 id_decl=id_decl, id_member=id_member))
1301 code.append(idmap_format.format(template=idmap, typename=typename, id_value=info.value, typedef=type_member))
John Zulaufde972ac2017-10-26 12:07:05 -06001302
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +01001303 if item.ifdef_protect is not None:
John Zulaufde972ac2017-10-26 12:07:05 -06001304 code.append('#endif // %s' % item.ifdef_protect)
1305
John Zulauf65ac9d52018-01-23 11:20:50 -07001306 # Generate utilities for all types
1307 code.append('\n'.join((
1308 utilities_format.format(id_member=id_member, id_map=idmap, type_map=typemap,
1309 type_member=type_member, header=generic_header, typename_func=typename_func, idname_func=idname_func,
1310 find_func=find_func, init_func=init_func), ''
1311 )))
1312
John Zulaufde972ac2017-10-26 12:07:05 -06001313 return "\n".join(code)
1314
1315 #
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -07001316 # Create a helper file and return it as a string
1317 def OutputDestFile(self):
Mark Lobodzinski46d388f2016-12-28 10:46:26 -07001318 if self.helper_file_type == 'enum_string_header':
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -07001319 return self.GenerateEnumStringHelperHeader()
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001320 elif self.helper_file_type == 'safe_struct_header':
1321 return self.GenerateSafeStructHelperHeader()
1322 elif self.helper_file_type == 'safe_struct_source':
1323 return self.GenerateSafeStructHelperSource()
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -06001324 elif self.helper_file_type == 'object_types_header':
1325 return self.GenerateObjectTypesHelperHeader()
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -06001326 elif self.helper_file_type == 'extension_helper_header':
1327 return self.GenerateExtensionHelperHeader()
John Zulaufde972ac2017-10-26 12:07:05 -06001328 elif self.helper_file_type == 'typemap_helper_header':
1329 return self.GenerateTypeMapHelperHeader()
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -07001330 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001331 return 'Bad Helper File Generator Option %s' % self.helper_file_type