blob: 2a8c2fdd5000508e98db1b1168cb7e0c07c3d61c [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)
Mike Schuchardt09a1c752019-06-20 12:04:38 -0700109 # Initialize members that require the tree
110 self.handle_types = GetHandleTypes(self.registry.tree)
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700111 # User-supplied prefix text, if any (list of strings)
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700112 self.helper_file_type = genOpts.helper_file_type
113 self.library_name = genOpts.library_name
114 # File Comment
115 file_comment = '// *** THIS FILE IS GENERATED - DO NOT EDIT ***\n'
116 file_comment += '// See helper_file_generator.py for modifications\n'
117 write(file_comment, file=self.outFile)
118 # Copyright Notice
119 copyright = ''
120 copyright += '\n'
121 copyright += '/***************************************************************************\n'
122 copyright += ' *\n'
Mike Schuchardt21638df2019-03-16 10:52:02 -0700123 copyright += ' * Copyright (c) 2015-2019 The Khronos Group Inc.\n'
124 copyright += ' * Copyright (c) 2015-2019 Valve Corporation\n'
125 copyright += ' * Copyright (c) 2015-2019 LunarG, Inc.\n'
126 copyright += ' * Copyright (c) 2015-2019 Google Inc.\n'
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700127 copyright += ' *\n'
128 copyright += ' * Licensed under the Apache License, Version 2.0 (the "License");\n'
129 copyright += ' * you may not use this file except in compliance with the License.\n'
130 copyright += ' * You may obtain a copy of the License at\n'
131 copyright += ' *\n'
132 copyright += ' * http://www.apache.org/licenses/LICENSE-2.0\n'
133 copyright += ' *\n'
134 copyright += ' * Unless required by applicable law or agreed to in writing, software\n'
135 copyright += ' * distributed under the License is distributed on an "AS IS" BASIS,\n'
136 copyright += ' * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n'
137 copyright += ' * See the License for the specific language governing permissions and\n'
138 copyright += ' * limitations under the License.\n'
139 copyright += ' *\n'
140 copyright += ' * Author: Mark Lobodzinski <mark@lunarg.com>\n'
Mark Lobodzinskia9c963d2016-12-28 07:45:35 -0700141 copyright += ' * Author: Courtney Goeltzenleuchter <courtneygo@google.com>\n'
142 copyright += ' * Author: Tobin Ehlis <tobine@google.com>\n'
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600143 copyright += ' * Author: Chris Forbes <chrisforbes@google.com>\n'
John Zulaufde972ac2017-10-26 12:07:05 -0600144 copyright += ' * Author: John Zulauf<jzulauf@lunarg.com>\n'
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700145 copyright += ' *\n'
146 copyright += ' ****************************************************************************/\n'
147 write(copyright, file=self.outFile)
148 #
Mark Lobodzinskia3cc3612017-01-03 13:25:10 -0700149 # Write generated file content to output file
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700150 def endFile(self):
151 dest_file = ''
152 dest_file += self.OutputDestFile()
Mark Lobodzinskiafe10542017-01-03 13:22:44 -0700153 # Remove blank lines at EOF
154 if dest_file.endswith('\n'):
155 dest_file = dest_file[:-1]
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700156 write(dest_file, file=self.outFile);
157 # Finish processing in superclass
158 OutputGenerator.endFile(self)
159 #
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600160 # Override parent class to be notified of the beginning of an extension
161 def beginFeature(self, interface, emit):
162 # Start processing in superclass
163 OutputGenerator.beginFeature(self, interface, emit)
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600164 self.featureExtraProtect = GetFeatureProtect(interface)
165
Mark Lobodzinski31964ca2017-09-18 14:15:09 -0600166 if self.featureName == 'VK_VERSION_1_0' or self.featureName == 'VK_VERSION_1_1':
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600167 return
John Zulauff6feb2a2018-04-12 14:24:57 -0600168 name = self.featureName
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600169 nameElem = interface[0][1]
John Zulauff6feb2a2018-04-12 14:24:57 -0600170 name_define = nameElem.get('name')
171 if 'EXTENSION_NAME' not in name_define:
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600172 print("Error in vk.xml file -- extension name is not available")
John Zulauf072677c2018-04-12 15:34:39 -0600173 requires = interface.get('requires')
174 if requires is not None:
175 required_extensions = requires.split(',')
176 else:
177 required_extensions = list()
178 info = { 'define': name_define, 'ifdef':self.featureExtraProtect, 'reqs':required_extensions }
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600179 if interface.get('type') == 'instance':
John Zulauff6feb2a2018-04-12 14:24:57 -0600180 self.instance_extension_info[name] = info
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600181 else:
John Zulauff6feb2a2018-04-12 14:24:57 -0600182 self.device_extension_info[name] = info
183
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600184 #
185 # Override parent class to be notified of the end of an extension
186 def endFeature(self):
187 # Finish processing in superclass
188 OutputGenerator.endFeature(self)
189 #
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700190 # Grab group (e.g. C "enum" type) info to output for enum-string conversion helper
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700191 def genGroup(self, groupinfo, groupName, alias):
192 OutputGenerator.genGroup(self, groupinfo, groupName, alias)
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700193 groupElem = groupinfo.elem
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700194 # For enum_string_header
195 if self.helper_file_type == 'enum_string_header':
Mike Schuchardtdf1e8dd2018-03-09 09:02:56 -0700196 value_set = set()
Mark Lobodzinski824ce642016-12-28 08:49:46 -0700197 for elem in groupElem.findall('enum'):
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100198 if elem.get('supported') != 'disabled' and elem.get('alias') is None:
Mike Schuchardtdf1e8dd2018-03-09 09:02:56 -0700199 value_set.add(elem.get('name'))
Tobias Hector30ad4fc2018-12-10 12:21:17 +0000200 if value_set != set():
201 self.enum_output += self.GenerateEnumStringConversion(groupName, value_set)
Mark Young1ded24b2017-05-30 14:53:50 -0600202 elif self.helper_file_type == 'object_types_header':
203 if groupName == 'VkDebugReportObjectTypeEXT':
204 for elem in groupElem.findall('enum'):
205 if elem.get('supported') != 'disabled':
206 item_name = elem.get('name')
207 self.debug_report_object_types.append(item_name)
208 elif groupName == 'VkObjectType':
209 for elem in groupElem.findall('enum'):
210 if elem.get('supported') != 'disabled':
211 item_name = elem.get('name')
212 self.core_object_types.append(item_name)
213
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700214 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700215 # Called for each type -- if the type is a struct/union, grab the metadata
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700216 def genType(self, typeinfo, name, alias):
217 OutputGenerator.genType(self, typeinfo, name, alias)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700218 typeElem = typeinfo.elem
219 # If the type is a struct type, traverse the imbedded <member> tags generating a structure.
220 # Otherwise, emit the tag text.
221 category = typeElem.get('category')
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600222 if category == 'handle':
John Zulaufd7435c62018-03-16 11:52:57 -0600223 if alias:
224 self.object_type_aliases.append((name,alias))
225 else:
226 self.object_types.append(name)
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600227 elif (category == 'struct' or category == 'union'):
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700228 self.structNames.append(name)
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700229 self.genStruct(typeinfo, name, alias)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700230 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700231 # Check if the parameter passed in is a pointer
232 def paramIsPointer(self, param):
233 ispointer = False
234 for elem in param:
Raul Tambre7b300182019-05-04 11:25:14 +0300235 if elem.tag == 'type' and elem.tail is not None and '*' in elem.tail:
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700236 ispointer = True
237 return ispointer
238 #
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700239 # Check if the parameter passed in is a static array
240 def paramIsStaticArray(self, param):
241 isstaticarray = 0
242 paramname = param.find('name')
243 if (paramname.tail is not None) and ('[' in paramname.tail):
244 isstaticarray = paramname.tail.count('[')
245 return isstaticarray
246 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700247 # Retrieve the type and name for a parameter
248 def getTypeNameTuple(self, param):
249 type = ''
250 name = ''
251 for elem in param:
252 if elem.tag == 'type':
253 type = noneStr(elem.text)
254 elif elem.tag == 'name':
255 name = noneStr(elem.text)
256 return (type, name)
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700257 # Extract length values from latexmath. Currently an inflexible solution that looks for specific
258 # patterns that are found in vk.xml. Will need to be updated when new patterns are introduced.
259 def parseLateXMath(self, source):
260 name = 'ERROR'
261 decoratedName = 'ERROR'
262 if 'mathit' in source:
Mark Lobodzinski36c33862017-02-13 10:15:53 -0700263 # Matches expressions similar to 'latexmath:[\lceil{\mathit{rasterizationSamples} \over 32}\rceil]'
264 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 -0700265 if not match or match.group(1) != match.group(4):
266 raise 'Unrecognized latexmath expression'
267 name = match.group(2)
mizhenc27f6c72017-03-31 09:08:16 -0600268 # Need to add 1 for ceiling function; otherwise, the allocated packet
269 # size will be less than needed during capture for some title which use
270 # this in VkPipelineMultisampleStateCreateInfo. based on ceiling function
271 # definition,it is '{0}%{1}?{0}/{1} + 1:{0}/{1}'.format(*match.group(2, 3)),
272 # its value <= '{}/{} + 1'.
273 if match.group(1) == 'ceil':
274 decoratedName = '{}/{} + 1'.format(*match.group(2, 3))
275 else:
276 decoratedName = '{}/{}'.format(*match.group(2, 3))
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700277 else:
Mark Lobodzinski36c33862017-02-13 10:15:53 -0700278 # Matches expressions similar to 'latexmath : [dataSize \over 4]'
Shannon McPhersonbd68df02018-10-29 15:04:41 -0600279 match = re.match(r'latexmath\s*\:\s*\[\s*(\\textrm\{)?(\w+)\}?\s*\\over\s*(\d+)\s*\]', source)
280 name = match.group(2)
281 decoratedName = '{}/{}'.format(*match.group(2, 3))
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700282 return name, decoratedName
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700283 #
284 # Retrieve the value of the len tag
285 def getLen(self, param):
286 result = None
287 len = param.attrib.get('len')
288 if len and len != 'null-terminated':
289 # For string arrays, 'len' can look like 'count,null-terminated', indicating that we
290 # have a null terminated array of strings. We strip the null-terminated from the
291 # 'len' field and only return the parameter specifying the string count
292 if 'null-terminated' in len:
293 result = len.split(',')[0]
294 else:
295 result = len
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700296 if 'latexmath' in len:
297 param_type, param_name = self.getTypeNameTuple(param)
298 len_name, result = self.parseLateXMath(len)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700299 # Spec has now notation for len attributes, using :: instead of platform specific pointer symbol
300 result = str(result).replace('::', '->')
301 return result
302 #
Shannon McPhersonbd68df02018-10-29 15:04:41 -0600303 # Check if a structure is or contains a dispatchable (dispatchable = True) or
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700304 # non-dispatchable (dispatchable = False) handle
305 def TypeContainsObjectHandle(self, handle_type, dispatchable):
306 if dispatchable:
307 type_key = 'VK_DEFINE_HANDLE'
308 else:
309 type_key = 'VK_DEFINE_NON_DISPATCHABLE_HANDLE'
Mike Schuchardt09a1c752019-06-20 12:04:38 -0700310 if self.handle_types.get(handle_type) == type_key:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700311 return True
312 # if handle_type is a struct, search its members
313 if handle_type in self.structNames:
314 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == handle_type), None)
315 if member_index is not None:
316 for item in self.structMembers[member_index].members:
Mike Schuchardt09a1c752019-06-20 12:04:38 -0700317 if self.handle_types.get(item.type) == type_key:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700318 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
Mike Schuchardt09a1c752019-06-20 12:04:38 -0700690 if self.handle_types.get(item) == 'VK_DEFINE_NON_DISPATCHABLE_HANDLE':
John Zulauf2c2ccd42019-04-05 13:13:13 -0600691 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'
locke-lunargb4c57852019-06-14 23:20:05 -0600705 object_types_header += ' "VkNonDispatchableHandle",\n'
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600706 for item in self.object_types:
locke-lunargb4c57852019-06-14 23:20:05 -0600707 object_types_header += ' "%s",\n' % item
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600708 object_types_header += '};\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600709
John Zulauf311a4892018-03-12 15:48:06 -0600710 # Key creation helper for map comprehensions that convert between k<Name> and VK<Name> symbols
711 def to_key(regex, raw_key): return re.search(regex, raw_key).group(1).lower().replace("_","")
712
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600713 # Output a conversion routine from the layer object definitions to the debug report definitions
John Zulauf311a4892018-03-12 15:48:06 -0600714 # As the VK_DEBUG_REPORT types are not being updated, specify UNKNOWN for unmatched types
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600715 object_types_header += '\n'
Mark Young1ded24b2017-05-30 14:53:50 -0600716 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 -0600717 object_types_header += 'const VkDebugReportObjectTypeEXT get_debug_report_enum[] = {\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700718 object_types_header += ' VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, // kVulkanObjectTypeUnknown\n'
Gabríel Arthúr Pétursson1a271d02018-03-18 17:34:01 +0000719
John Zulauf311a4892018-03-12 15:48:06 -0600720 dbg_re = '^VK_DEBUG_REPORT_OBJECT_TYPE_(.*)_EXT$'
721 dbg_map = {to_key(dbg_re, dbg) : dbg for dbg in self.debug_report_object_types}
722 dbg_default = 'VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT'
John Zulauf2c2ccd42019-04-05 13:13:13 -0600723
John Zulauf311a4892018-03-12 15:48:06 -0600724 for object_type in type_list:
725 vk_object_type = dbg_map.get(object_type.replace("kVulkanObjectType", "").lower(), dbg_default)
726 object_types_header += ' %s, // %s\n' % (vk_object_type, object_type)
John Zulauf2c2ccd42019-04-05 13:13:13 -0600727 object_type_info[object_type]['DbgType'] = vk_object_type
Mark Lobodzinskiecf0ae12017-04-13 08:36:18 -0600728 object_types_header += '};\n'
Mark Young1ded24b2017-05-30 14:53:50 -0600729
730 # Output a conversion routine from the layer object definitions to the core object type definitions
John Zulauf311a4892018-03-12 15:48:06 -0600731 # 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 -0600732 object_types_header += '\n'
733 object_types_header += '// Helper array to get Official Vulkan VkObjectType enum from the internal layers version\n'
734 object_types_header += 'const VkObjectType get_object_type_enum[] = {\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700735 object_types_header += ' VK_OBJECT_TYPE_UNKNOWN, // kVulkanObjectTypeUnknown\n'
John Zulauf311a4892018-03-12 15:48:06 -0600736
737 vko_re = '^VK_OBJECT_TYPE_(.*)'
738 vko_map = {to_key(vko_re, vko) : vko for vko in self.core_object_types}
Mark Young1ded24b2017-05-30 14:53:50 -0600739 for object_type in type_list:
John Zulauf311a4892018-03-12 15:48:06 -0600740 vk_object_type = vko_map[object_type.replace("kVulkanObjectType", "").lower()]
741 object_types_header += ' %s, // %s\n' % (vk_object_type, object_type)
John Zulauf2c2ccd42019-04-05 13:13:13 -0600742 object_type_info[object_type]['VkoType'] = vk_object_type
Mark Young1ded24b2017-05-30 14:53:50 -0600743 object_types_header += '};\n'
744
Mark Young6ba8abe2017-11-09 10:37:04 -0700745 # Create a function to convert from VkDebugReportObjectTypeEXT to VkObjectType
746 object_types_header += '\n'
747 object_types_header += '// Helper function to convert from VkDebugReportObjectTypeEXT to VkObjectType\n'
Mark Young8504ba62018-03-21 13:35:34 -0600748 object_types_header += 'static inline VkObjectType convertDebugReportObjectToCoreObject(VkDebugReportObjectTypeEXT debug_report_obj){\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700749 object_types_header += ' if (debug_report_obj == VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT) {\n'
750 object_types_header += ' return VK_OBJECT_TYPE_UNKNOWN;\n'
751 for core_object_type in self.core_object_types:
752 core_target_type = core_object_type.replace("VK_OBJECT_TYPE_", "").lower()
753 core_target_type = core_target_type.replace("_", "")
754 for dr_object_type in self.debug_report_object_types:
755 dr_target_type = dr_object_type.replace("VK_DEBUG_REPORT_OBJECT_TYPE_", "").lower()
756 dr_target_type = dr_target_type[:-4]
757 dr_target_type = dr_target_type.replace("_", "")
758 if core_target_type == dr_target_type:
759 object_types_header += ' } else if (debug_report_obj == %s) {\n' % dr_object_type
760 object_types_header += ' return %s;\n' % core_object_type
761 break
762 object_types_header += ' }\n'
763 object_types_header += ' return VK_OBJECT_TYPE_UNKNOWN;\n'
764 object_types_header += '}\n'
765
766 # Create a function to convert from VkObjectType to VkDebugReportObjectTypeEXT
767 object_types_header += '\n'
768 object_types_header += '// Helper function to convert from VkDebugReportObjectTypeEXT to VkObjectType\n'
Mark Young8504ba62018-03-21 13:35:34 -0600769 object_types_header += 'static inline VkDebugReportObjectTypeEXT convertCoreObjectToDebugReportObject(VkObjectType core_report_obj){\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700770 object_types_header += ' if (core_report_obj == VK_OBJECT_TYPE_UNKNOWN) {\n'
771 object_types_header += ' return VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT;\n'
772 for core_object_type in self.core_object_types:
773 core_target_type = core_object_type.replace("VK_OBJECT_TYPE_", "").lower()
774 core_target_type = core_target_type.replace("_", "")
775 for dr_object_type in self.debug_report_object_types:
776 dr_target_type = dr_object_type.replace("VK_DEBUG_REPORT_OBJECT_TYPE_", "").lower()
777 dr_target_type = dr_target_type[:-4]
778 dr_target_type = dr_target_type.replace("_", "")
779 if core_target_type == dr_target_type:
780 object_types_header += ' } else if (core_report_obj == %s) {\n' % core_object_type
781 object_types_header += ' return %s;\n' % dr_object_type
782 break
783 object_types_header += ' }\n'
784 object_types_header += ' return VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT;\n'
785 object_types_header += '}\n'
John Zulauf2c2ccd42019-04-05 13:13:13 -0600786
787 traits_format = Outdent('''
788 template <> struct VkHandleInfo<{vk_type}> {{
789 static const VulkanObjectType kVulkanObjectType = {obj_type};
790 static const VkDebugReportObjectTypeEXT kDebugReportObjectType = {dbg_type};
791 static const VkObjectType kVkObjectType = {vko_type};
792 static const char* Typename() {{
793 return "{vk_type}";
794 }}
795 }};
796 template <> struct VulkanObjectTypeInfo<{obj_type}> {{
797 typedef {vk_type} Type;
798 }};
799 ''')
800
801 object_types_header += Outdent('''
802 // Traits objects from each type statically map from Vk<handleType> to the various enums
803 template <typename VkType> struct VkHandleInfo {};
804 template <VulkanObjectType id> struct VulkanObjectTypeInfo {};
805
806 // The following line must match the vulkan_core.h condition guarding VK_DEFINE_NON_DISPATCHABLE_HANDLE
807 #if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__)) || defined(_M_X64) || defined(__ia64) || \
808 defined(_M_IA64) || defined(__aarch64__) || defined(__powerpc64__)
809 #define TYPESAFE_NONDISPATCHABLE_HANDLES
810 #else
811 VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkNonDispatchableHandle)
812 ''') +'\n'
813 object_types_header += traits_format.format(vk_type='VkNonDispatchableHandle', obj_type='kVulkanObjectTypeUnknown',
814 dbg_type='VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT',
815 vko_type='VK_OBJECT_TYPE_UNKNOWN') + '\n'
816 object_types_header += '#endif // VK_DEFINE_HANDLE logic duplication\n'
817
Mike Schuchardtaed5ac32019-06-21 09:03:31 -0700818 for vk_type, object_type in sorted(dispatchable.items()):
John Zulauf2c2ccd42019-04-05 13:13:13 -0600819 info = object_type_info[object_type]
820 object_types_header += traits_format.format(vk_type=vk_type, obj_type=object_type, dbg_type=info['DbgType'],
821 vko_type=info['VkoType'])
822 object_types_header += '#ifdef TYPESAFE_NONDISPATCHABLE_HANDLES\n'
Mike Schuchardtaed5ac32019-06-21 09:03:31 -0700823 for vk_type, object_type in sorted(non_dispatchable.items()):
John Zulauf2c2ccd42019-04-05 13:13:13 -0600824 info = object_type_info[object_type]
825 object_types_header += traits_format.format(vk_type=vk_type, obj_type=object_type, dbg_type=info['DbgType'],
826 vko_type=info['VkoType'])
827 object_types_header += '#endif // TYPESAFE_NONDISPATCHABLE_HANDLES\n'
828
829 object_types_header += Outdent('''
830 struct VulkanTypedHandle {
831 uint64_t handle;
832 VulkanObjectType type;
833 template <typename Handle>
John Zulauf4fea6622019-04-01 11:38:18 -0600834 VulkanTypedHandle(Handle handle_, VulkanObjectType type_) :
835 handle(CastToUint64(handle_)),
836 type(type_) {
837 #ifdef TYPESAFE_NONDISPATCHABLE_HANDLES
838 // For 32 bit it's not always safe to check for traits <-> type
839 // as all non-dispatchable handles have the same type-id and thus traits,
840 // but on 64 bit we can validate the passed type matches the passed handle
841 assert(type == VkHandleInfo<Handle>::kVulkanObjectType);
842 #endif // TYPESAFE_NONDISPATCHABLE_HANDLES
843 }
844 template <typename Handle>
845 Handle Cast() const {
846 #ifdef TYPESAFE_NONDISPATCHABLE_HANDLES
847 assert(type == VkHandleInfo<Handle>::kVulkanObjectType);
848 #endif // TYPESAFE_NONDISPATCHABLE_HANDLES
849 return CastFromUint64<Handle>(handle);
850 }
John Zulauf2c2ccd42019-04-05 13:13:13 -0600851 VulkanTypedHandle() :
852 handle(VK_NULL_HANDLE),
853 type(kVulkanObjectTypeUnknown) {}
854 }; ''') +'\n'
855
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600856 return object_types_header
857 #
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700858 # Determine if a structure needs a safe_struct helper function
859 # That is, it has an sType or one of its members is a pointer
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700860 def NeedSafeStruct(self, structure):
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700861 if 'sType' == structure.name:
862 return True
863 for member in structure.members:
864 if member.ispointer == True:
865 return True
866 return False
867 #
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700868 # Combine safe struct helper source file preamble with body text and return
869 def GenerateSafeStructHelperSource(self):
870 safe_struct_helper_source = '\n'
871 safe_struct_helper_source += '#include "vk_safe_struct.h"\n'
872 safe_struct_helper_source += '#include <string.h>\n'
873 safe_struct_helper_source += '\n'
874 safe_struct_helper_source += self.GenerateSafeStructSource()
875 return safe_struct_helper_source
876 #
877 # safe_struct source -- create bodies of safe struct helper functions
878 def GenerateSafeStructSource(self):
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700879 safe_struct_body = []
Mark Lobodzinski560729b2017-03-06 08:59:14 -0700880 wsi_structs = ['VkXlibSurfaceCreateInfoKHR',
881 'VkXcbSurfaceCreateInfoKHR',
882 'VkWaylandSurfaceCreateInfoKHR',
Mark Lobodzinski560729b2017-03-06 08:59:14 -0700883 'VkAndroidSurfaceCreateInfoKHR',
884 'VkWin32SurfaceCreateInfoKHR'
885 ]
Courtney Goeltzenleuchterdb6c2332018-06-28 14:32:55 -0600886
887 # For abstract types just want to save the pointer away
888 # since we cannot make a copy.
889 abstract_types = ['AHardwareBuffer',
890 'ANativeWindow',
891 ]
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700892 for item in self.structMembers:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700893 if self.NeedSafeStruct(item) == False:
894 continue
Mark Lobodzinski560729b2017-03-06 08:59:14 -0700895 if item.name in wsi_structs:
896 continue
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100897 if item.ifdef_protect is not None:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700898 safe_struct_body.append("#ifdef %s\n" % item.ifdef_protect)
899 ss_name = "safe_%s" % item.name
900 init_list = '' # list of members in struct constructor initializer
901 default_init_list = '' # Default constructor just inits ptrs to nullptr in initializer
902 init_func_txt = '' # Txt for initialize() function that takes struct ptr and inits members
903 construct_txt = '' # Body of constuctor as well as body of initialize() func following init_func_txt
904 destruct_txt = ''
Petr Krause91f7a12017-12-14 20:57:36 +0100905
906 custom_construct_txt = {
907 # VkWriteDescriptorSet is special case because pointers may be non-null but ignored
908 'VkWriteDescriptorSet' :
909 ' switch (descriptorType) {\n'
910 ' case VK_DESCRIPTOR_TYPE_SAMPLER:\n'
911 ' case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:\n'
912 ' case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:\n'
913 ' case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:\n'
914 ' case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:\n'
915 ' if (descriptorCount && in_struct->pImageInfo) {\n'
916 ' pImageInfo = new VkDescriptorImageInfo[descriptorCount];\n'
917 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
918 ' pImageInfo[i] = in_struct->pImageInfo[i];\n'
919 ' }\n'
920 ' }\n'
921 ' break;\n'
922 ' case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:\n'
923 ' case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:\n'
924 ' case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:\n'
925 ' case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:\n'
926 ' if (descriptorCount && in_struct->pBufferInfo) {\n'
927 ' pBufferInfo = new VkDescriptorBufferInfo[descriptorCount];\n'
928 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
929 ' pBufferInfo[i] = in_struct->pBufferInfo[i];\n'
930 ' }\n'
931 ' }\n'
932 ' break;\n'
933 ' case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:\n'
934 ' case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:\n'
935 ' if (descriptorCount && in_struct->pTexelBufferView) {\n'
936 ' pTexelBufferView = new VkBufferView[descriptorCount];\n'
937 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
938 ' pTexelBufferView[i] = in_struct->pTexelBufferView[i];\n'
939 ' }\n'
940 ' }\n'
941 ' break;\n'
942 ' default:\n'
943 ' break;\n'
944 ' }\n',
Petr Kraus42f6f8d2017-12-17 17:37:33 +0100945 'VkShaderModuleCreateInfo' :
Petr Krause91f7a12017-12-14 20:57:36 +0100946 ' if (in_struct->pCode) {\n'
947 ' pCode = reinterpret_cast<uint32_t *>(new uint8_t[codeSize]);\n'
948 ' memcpy((void *)pCode, (void *)in_struct->pCode, codeSize);\n'
949 ' }\n',
950 # VkGraphicsPipelineCreateInfo is special case because its pointers may be non-null but ignored
951 'VkGraphicsPipelineCreateInfo' :
952 ' if (stageCount && in_struct->pStages) {\n'
953 ' pStages = new safe_VkPipelineShaderStageCreateInfo[stageCount];\n'
954 ' for (uint32_t i=0; i<stageCount; ++i) {\n'
955 ' pStages[i].initialize(&in_struct->pStages[i]);\n'
956 ' }\n'
957 ' }\n'
958 ' if (in_struct->pVertexInputState)\n'
959 ' pVertexInputState = new safe_VkPipelineVertexInputStateCreateInfo(in_struct->pVertexInputState);\n'
960 ' else\n'
961 ' pVertexInputState = NULL;\n'
962 ' if (in_struct->pInputAssemblyState)\n'
963 ' pInputAssemblyState = new safe_VkPipelineInputAssemblyStateCreateInfo(in_struct->pInputAssemblyState);\n'
964 ' else\n'
965 ' pInputAssemblyState = NULL;\n'
966 ' bool has_tessellation_stage = false;\n'
967 ' if (stageCount && pStages)\n'
968 ' for (uint32_t i=0; i<stageCount && !has_tessellation_stage; ++i)\n'
969 ' if (pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)\n'
970 ' has_tessellation_stage = true;\n'
971 ' if (in_struct->pTessellationState && has_tessellation_stage)\n'
972 ' pTessellationState = new safe_VkPipelineTessellationStateCreateInfo(in_struct->pTessellationState);\n'
973 ' else\n'
974 ' pTessellationState = NULL; // original pTessellationState pointer ignored\n'
975 ' bool has_rasterization = in_struct->pRasterizationState ? !in_struct->pRasterizationState->rasterizerDiscardEnable : false;\n'
976 ' if (in_struct->pViewportState && has_rasterization) {\n'
977 ' bool is_dynamic_viewports = false;\n'
978 ' bool is_dynamic_scissors = false;\n'
979 ' if (in_struct->pDynamicState && in_struct->pDynamicState->pDynamicStates) {\n'
980 ' for (uint32_t i = 0; i < in_struct->pDynamicState->dynamicStateCount && !is_dynamic_viewports; ++i)\n'
981 ' if (in_struct->pDynamicState->pDynamicStates[i] == VK_DYNAMIC_STATE_VIEWPORT)\n'
982 ' is_dynamic_viewports = true;\n'
983 ' for (uint32_t i = 0; i < in_struct->pDynamicState->dynamicStateCount && !is_dynamic_scissors; ++i)\n'
984 ' if (in_struct->pDynamicState->pDynamicStates[i] == VK_DYNAMIC_STATE_SCISSOR)\n'
985 ' is_dynamic_scissors = true;\n'
986 ' }\n'
987 ' pViewportState = new safe_VkPipelineViewportStateCreateInfo(in_struct->pViewportState, is_dynamic_viewports, is_dynamic_scissors);\n'
988 ' } else\n'
989 ' pViewportState = NULL; // original pViewportState pointer ignored\n'
990 ' if (in_struct->pRasterizationState)\n'
991 ' pRasterizationState = new safe_VkPipelineRasterizationStateCreateInfo(in_struct->pRasterizationState);\n'
992 ' else\n'
993 ' pRasterizationState = NULL;\n'
994 ' if (in_struct->pMultisampleState && has_rasterization)\n'
995 ' pMultisampleState = new safe_VkPipelineMultisampleStateCreateInfo(in_struct->pMultisampleState);\n'
996 ' else\n'
997 ' pMultisampleState = NULL; // original pMultisampleState pointer ignored\n'
998 ' // needs a tracked subpass state uses_depthstencil_attachment\n'
999 ' if (in_struct->pDepthStencilState && has_rasterization && uses_depthstencil_attachment)\n'
1000 ' pDepthStencilState = new safe_VkPipelineDepthStencilStateCreateInfo(in_struct->pDepthStencilState);\n'
1001 ' else\n'
1002 ' pDepthStencilState = NULL; // original pDepthStencilState pointer ignored\n'
1003 ' // needs a tracked subpass state usesColorAttachment\n'
1004 ' if (in_struct->pColorBlendState && has_rasterization && uses_color_attachment)\n'
1005 ' pColorBlendState = new safe_VkPipelineColorBlendStateCreateInfo(in_struct->pColorBlendState);\n'
1006 ' else\n'
1007 ' pColorBlendState = NULL; // original pColorBlendState pointer ignored\n'
1008 ' if (in_struct->pDynamicState)\n'
1009 ' pDynamicState = new safe_VkPipelineDynamicStateCreateInfo(in_struct->pDynamicState);\n'
1010 ' else\n'
1011 ' pDynamicState = NULL;\n',
1012 # VkPipelineViewportStateCreateInfo is special case because its pointers may be non-null but ignored
1013 'VkPipelineViewportStateCreateInfo' :
1014 ' if (in_struct->pViewports && !is_dynamic_viewports) {\n'
1015 ' pViewports = new VkViewport[in_struct->viewportCount];\n'
1016 ' memcpy ((void *)pViewports, (void *)in_struct->pViewports, sizeof(VkViewport)*in_struct->viewportCount);\n'
1017 ' }\n'
1018 ' else\n'
1019 ' pViewports = NULL;\n'
1020 ' if (in_struct->pScissors && !is_dynamic_scissors) {\n'
1021 ' pScissors = new VkRect2D[in_struct->scissorCount];\n'
1022 ' memcpy ((void *)pScissors, (void *)in_struct->pScissors, sizeof(VkRect2D)*in_struct->scissorCount);\n'
1023 ' }\n'
1024 ' else\n'
1025 ' pScissors = NULL;\n',
Petr Kraus42f6f8d2017-12-17 17:37:33 +01001026 # VkDescriptorSetLayoutBinding is special case because its pImmutableSamplers pointer may be non-null but ignored
1027 'VkDescriptorSetLayoutBinding' :
1028 ' const bool sampler_type = in_struct->descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER || in_struct->descriptorType == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;\n'
1029 ' if (descriptorCount && in_struct->pImmutableSamplers && sampler_type) {\n'
1030 ' pImmutableSamplers = new VkSampler[descriptorCount];\n'
1031 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
1032 ' pImmutableSamplers[i] = in_struct->pImmutableSamplers[i];\n'
1033 ' }\n'
1034 ' }\n',
Petr Krause91f7a12017-12-14 20:57:36 +01001035 }
1036
1037 custom_copy_txt = {
1038 # VkGraphicsPipelineCreateInfo is special case because it has custom construct parameters
1039 'VkGraphicsPipelineCreateInfo' :
1040 ' if (stageCount && src.pStages) {\n'
1041 ' pStages = new safe_VkPipelineShaderStageCreateInfo[stageCount];\n'
1042 ' for (uint32_t i=0; i<stageCount; ++i) {\n'
1043 ' pStages[i].initialize(&src.pStages[i]);\n'
1044 ' }\n'
1045 ' }\n'
1046 ' if (src.pVertexInputState)\n'
1047 ' pVertexInputState = new safe_VkPipelineVertexInputStateCreateInfo(*src.pVertexInputState);\n'
1048 ' else\n'
1049 ' pVertexInputState = NULL;\n'
1050 ' if (src.pInputAssemblyState)\n'
1051 ' pInputAssemblyState = new safe_VkPipelineInputAssemblyStateCreateInfo(*src.pInputAssemblyState);\n'
1052 ' else\n'
1053 ' pInputAssemblyState = NULL;\n'
1054 ' bool has_tessellation_stage = false;\n'
1055 ' if (stageCount && pStages)\n'
1056 ' for (uint32_t i=0; i<stageCount && !has_tessellation_stage; ++i)\n'
1057 ' if (pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)\n'
1058 ' has_tessellation_stage = true;\n'
1059 ' if (src.pTessellationState && has_tessellation_stage)\n'
1060 ' pTessellationState = new safe_VkPipelineTessellationStateCreateInfo(*src.pTessellationState);\n'
1061 ' else\n'
1062 ' pTessellationState = NULL; // original pTessellationState pointer ignored\n'
1063 ' bool has_rasterization = src.pRasterizationState ? !src.pRasterizationState->rasterizerDiscardEnable : false;\n'
1064 ' if (src.pViewportState && has_rasterization) {\n'
1065 ' pViewportState = new safe_VkPipelineViewportStateCreateInfo(*src.pViewportState);\n'
1066 ' } else\n'
1067 ' pViewportState = NULL; // original pViewportState pointer ignored\n'
1068 ' if (src.pRasterizationState)\n'
1069 ' pRasterizationState = new safe_VkPipelineRasterizationStateCreateInfo(*src.pRasterizationState);\n'
1070 ' else\n'
1071 ' pRasterizationState = NULL;\n'
1072 ' if (src.pMultisampleState && has_rasterization)\n'
1073 ' pMultisampleState = new safe_VkPipelineMultisampleStateCreateInfo(*src.pMultisampleState);\n'
1074 ' else\n'
1075 ' pMultisampleState = NULL; // original pMultisampleState pointer ignored\n'
1076 ' if (src.pDepthStencilState && has_rasterization)\n'
1077 ' pDepthStencilState = new safe_VkPipelineDepthStencilStateCreateInfo(*src.pDepthStencilState);\n'
1078 ' else\n'
1079 ' pDepthStencilState = NULL; // original pDepthStencilState pointer ignored\n'
1080 ' if (src.pColorBlendState && has_rasterization)\n'
1081 ' pColorBlendState = new safe_VkPipelineColorBlendStateCreateInfo(*src.pColorBlendState);\n'
1082 ' else\n'
1083 ' pColorBlendState = NULL; // original pColorBlendState pointer ignored\n'
1084 ' if (src.pDynamicState)\n'
1085 ' pDynamicState = new safe_VkPipelineDynamicStateCreateInfo(*src.pDynamicState);\n'
1086 ' else\n'
1087 ' pDynamicState = NULL;\n',
1088 # VkPipelineViewportStateCreateInfo is special case because it has custom construct parameters
1089 'VkPipelineViewportStateCreateInfo' :
1090 ' if (src.pViewports) {\n'
1091 ' pViewports = new VkViewport[src.viewportCount];\n'
1092 ' memcpy ((void *)pViewports, (void *)src.pViewports, sizeof(VkViewport)*src.viewportCount);\n'
1093 ' }\n'
1094 ' else\n'
1095 ' pViewports = NULL;\n'
1096 ' if (src.pScissors) {\n'
1097 ' pScissors = new VkRect2D[src.scissorCount];\n'
1098 ' memcpy ((void *)pScissors, (void *)src.pScissors, sizeof(VkRect2D)*src.scissorCount);\n'
1099 ' }\n'
1100 ' else\n'
1101 ' pScissors = NULL;\n',
1102 }
1103
Mike Schuchardt81485762017-09-04 11:38:42 -06001104 custom_destruct_txt = {'VkShaderModuleCreateInfo' :
1105 ' if (pCode)\n'
1106 ' delete[] reinterpret_cast<const uint8_t *>(pCode);\n' }
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001107
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001108 for member in item.members:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001109 m_type = member.type
1110 if member.type in self.structNames:
1111 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
1112 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
1113 m_type = 'safe_%s' % member.type
1114 if member.ispointer and 'safe_' not in m_type and self.TypeContainsObjectHandle(member.type, False) == False:
1115 # 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 -07001116 if m_type in ['void', 'char']:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001117 # For these exceptions just copy initial value over for now
1118 init_list += '\n %s(in_struct->%s),' % (member.name, member.name)
1119 init_func_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001120 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001121 default_init_list += '\n %s(nullptr),' % (member.name)
1122 init_list += '\n %s(nullptr),' % (member.name)
Courtney Goeltzenleuchterdb6c2332018-06-28 14:32:55 -06001123 if m_type in abstract_types:
1124 construct_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
1125 else:
1126 init_func_txt += ' %s = nullptr;\n' % (member.name)
1127 if 'pNext' != member.name and 'void' not in m_type:
1128 if not member.isstaticarray and (member.len is None or '/' in member.len):
1129 construct_txt += ' if (in_struct->%s) {\n' % member.name
1130 construct_txt += ' %s = new %s(*in_struct->%s);\n' % (member.name, m_type, member.name)
1131 construct_txt += ' }\n'
1132 destruct_txt += ' if (%s)\n' % member.name
1133 destruct_txt += ' delete %s;\n' % member.name
1134 else:
1135 construct_txt += ' if (in_struct->%s) {\n' % member.name
1136 construct_txt += ' %s = new %s[in_struct->%s];\n' % (member.name, m_type, member.len)
1137 construct_txt += ' memcpy ((void *)%s, (void *)in_struct->%s, sizeof(%s)*in_struct->%s);\n' % (member.name, member.name, m_type, member.len)
1138 construct_txt += ' }\n'
1139 destruct_txt += ' if (%s)\n' % member.name
1140 destruct_txt += ' delete[] %s;\n' % member.name
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001141 elif member.isstaticarray or member.len is not None:
1142 if member.len is None:
1143 # Extract length of static array by grabbing val between []
1144 static_array_size = re.match(r"[^[]*\[([^]]*)\]", member.cdecl)
1145 construct_txt += ' for (uint32_t i=0; i<%s; ++i) {\n' % static_array_size.group(1)
1146 construct_txt += ' %s[i] = in_struct->%s[i];\n' % (member.name, member.name)
1147 construct_txt += ' }\n'
1148 else:
1149 # Init array ptr to NULL
1150 default_init_list += '\n %s(nullptr),' % member.name
1151 init_list += '\n %s(nullptr),' % member.name
1152 init_func_txt += ' %s = nullptr;\n' % member.name
1153 array_element = 'in_struct->%s[i]' % member.name
1154 if member.type in self.structNames:
1155 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
1156 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
1157 array_element = '%s(&in_struct->safe_%s[i])' % (member.type, member.name)
1158 construct_txt += ' if (%s && in_struct->%s) {\n' % (member.len, member.name)
1159 construct_txt += ' %s = new %s[%s];\n' % (member.name, m_type, member.len)
1160 destruct_txt += ' if (%s)\n' % member.name
1161 destruct_txt += ' delete[] %s;\n' % member.name
1162 construct_txt += ' for (uint32_t i=0; i<%s; ++i) {\n' % (member.len)
1163 if 'safe_' in m_type:
1164 construct_txt += ' %s[i].initialize(&in_struct->%s[i]);\n' % (member.name, member.name)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001165 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001166 construct_txt += ' %s[i] = %s;\n' % (member.name, array_element)
1167 construct_txt += ' }\n'
1168 construct_txt += ' }\n'
1169 elif member.ispointer == True:
1170 construct_txt += ' if (in_struct->%s)\n' % member.name
1171 construct_txt += ' %s = new %s(in_struct->%s);\n' % (member.name, m_type, member.name)
1172 construct_txt += ' else\n'
1173 construct_txt += ' %s = NULL;\n' % member.name
1174 destruct_txt += ' if (%s)\n' % member.name
1175 destruct_txt += ' delete %s;\n' % member.name
1176 elif 'safe_' in m_type:
1177 init_list += '\n %s(&in_struct->%s),' % (member.name, member.name)
1178 init_func_txt += ' %s.initialize(&in_struct->%s);\n' % (member.name, member.name)
1179 else:
1180 init_list += '\n %s(in_struct->%s),' % (member.name, member.name)
1181 init_func_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
1182 if '' != init_list:
1183 init_list = init_list[:-1] # hack off final comma
1184 if item.name in custom_construct_txt:
1185 construct_txt = custom_construct_txt[item.name]
Mike Schuchardt81485762017-09-04 11:38:42 -06001186 if item.name in custom_destruct_txt:
1187 destruct_txt = custom_destruct_txt[item.name]
Petr Krause91f7a12017-12-14 20:57:36 +01001188 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 -07001189 if '' != default_init_list:
1190 default_init_list = " :%s" % (default_init_list[:-1])
1191 safe_struct_body.append("\n%s::%s()%s\n{}" % (ss_name, ss_name, default_init_list))
1192 # Create slight variation of init and construct txt for copy constructor that takes a src object reference vs. struct ptr
1193 copy_construct_init = init_func_txt.replace('in_struct->', 'src.')
1194 copy_construct_txt = construct_txt.replace(' (in_struct->', ' (src.') # Exclude 'if' blocks from next line
1195 copy_construct_txt = copy_construct_txt.replace('(in_struct->', '(*src.') # Pass object to copy constructors
1196 copy_construct_txt = copy_construct_txt.replace('in_struct->', 'src.') # Modify remaining struct refs for src object
Petr Krause91f7a12017-12-14 20:57:36 +01001197 if item.name in custom_copy_txt:
1198 copy_construct_txt = custom_copy_txt[item.name]
Chris Forbesfb633832017-10-03 18:11:54 -07001199 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 -06001200 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 -07001201 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 -07001202 safe_struct_body.append("\n%s::~%s()\n{\n%s}" % (ss_name, ss_name, destruct_txt))
Petr Krause91f7a12017-12-14 20:57:36 +01001203 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 -07001204 # Copy initializer uses same txt as copy constructor but has a ptr and not a reference
1205 init_copy = copy_construct_init.replace('src.', 'src->')
1206 init_construct = copy_construct_txt.replace('src.', 'src->')
Mark Lobodzinski5cd08512017-09-12 09:50:25 -06001207 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 +01001208 if item.ifdef_protect is not None:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001209 safe_struct_body.append("#endif // %s\n" % item.ifdef_protect)
1210 return "\n".join(safe_struct_body)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001211 #
John Zulaufde972ac2017-10-26 12:07:05 -06001212 # Generate the type map
1213 def GenerateTypeMapHelperHeader(self):
1214 prefix = 'Lvl'
1215 fprefix = 'lvl_'
1216 typemap = prefix + 'TypeMap'
1217 idmap = prefix + 'STypeMap'
John Zulaufde972ac2017-10-26 12:07:05 -06001218 type_member = 'Type'
1219 id_member = 'kSType'
Mike Schuchardt97662b02017-12-06 13:31:29 -07001220 id_decl = 'static const VkStructureType '
Locke6b6b7382019-04-16 15:08:49 -06001221 generic_header = 'VkBaseOutStructure'
John Zulaufde972ac2017-10-26 12:07:05 -06001222 typename_func = fprefix + 'typename'
1223 idname_func = fprefix + 'stype_name'
1224 find_func = fprefix + 'find_in_chain'
John Zulauf65ac9d52018-01-23 11:20:50 -07001225 init_func = fprefix + 'init_struct'
John Zulaufde972ac2017-10-26 12:07:05 -06001226
1227 explanatory_comment = '\n'.join((
1228 '// These empty generic templates are specialized for each type with sType',
1229 '// members and for each sType -- providing a two way map between structure',
Mike Schuchardt97662b02017-12-06 13:31:29 -07001230 '// types and sTypes'))
John Zulaufde972ac2017-10-26 12:07:05 -06001231
1232 empty_typemap = 'template <typename T> struct ' + typemap + ' {};'
1233 typemap_format = 'template <> struct {template}<{typename}> {{\n'
John Zulaufde972ac2017-10-26 12:07:05 -06001234 typemap_format += ' {id_decl}{id_member} = {id_value};\n'
1235 typemap_format += '}};\n'
1236
1237 empty_idmap = 'template <VkStructureType id> struct ' + idmap + ' {};'
1238 idmap_format = ''.join((
1239 'template <> struct {template}<{id_value}> {{\n',
1240 ' typedef {typename} {typedef};\n',
John Zulaufde972ac2017-10-26 12:07:05 -06001241 '}};\n'))
1242
1243 # Define the utilities (here so any renaming stays consistent), if this grows large, refactor to a fixed .h file
1244 utilities_format = '\n'.join((
John Zulaufde972ac2017-10-26 12:07:05 -06001245 '// Find an entry of the given type in the pNext chain',
1246 'template <typename T> const T *{find_func}(const void *next) {{',
1247 ' const {header} *current = reinterpret_cast<const {header} *>(next);',
1248 ' const T *found = nullptr;',
1249 ' while (current) {{',
1250 ' if ({type_map}<T>::{id_member} == current->sType) {{',
1251 ' found = reinterpret_cast<const T*>(current);',
1252 ' current = nullptr;',
1253 ' }} else {{',
1254 ' current = current->pNext;',
1255 ' }}',
1256 ' }}',
1257 ' return found;',
1258 '}}',
John Zulauf65ac9d52018-01-23 11:20:50 -07001259 '',
1260 '// Init the header of an sType struct with pNext',
1261 'template <typename T> T {init_func}(void *p_next) {{',
1262 ' T out = {{}};',
1263 ' out.sType = {type_map}<T>::kSType;',
1264 ' out.pNext = p_next;',
1265 ' return out;',
1266 '}}',
1267 '',
1268 '// Init the header of an sType struct',
1269 'template <typename T> T {init_func}() {{',
1270 ' T out = {{}};',
1271 ' out.sType = {type_map}<T>::kSType;',
1272 ' return out;',
1273 '}}',
1274
Mike Schuchardt97662b02017-12-06 13:31:29 -07001275 ''))
John Zulaufde972ac2017-10-26 12:07:05 -06001276
1277 code = []
John Zulauf65ac9d52018-01-23 11:20:50 -07001278
1279 # Generate header
John Zulaufde972ac2017-10-26 12:07:05 -06001280 code.append('\n'.join((
1281 '#pragma once',
1282 '#include <vulkan/vulkan.h>\n',
1283 explanatory_comment, '',
1284 empty_idmap,
John Zulauf65ac9d52018-01-23 11:20:50 -07001285 empty_typemap, '')))
John Zulaufde972ac2017-10-26 12:07:05 -06001286
1287 # Generate the specializations for each type and stype
John Zulaufde972ac2017-10-26 12:07:05 -06001288 for item in self.structMembers:
1289 typename = item.name
1290 info = self.structTypes.get(typename)
1291 if not info:
1292 continue
1293
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +01001294 if item.ifdef_protect is not None:
John Zulaufde972ac2017-10-26 12:07:05 -06001295 code.append('#ifdef %s' % item.ifdef_protect)
1296
1297 code.append('// Map type {} to id {}'.format(typename, info.value))
1298 code.append(typemap_format.format(template=typemap, typename=typename, id_value=info.value,
Mike Schuchardt97662b02017-12-06 13:31:29 -07001299 id_decl=id_decl, id_member=id_member))
1300 code.append(idmap_format.format(template=idmap, typename=typename, id_value=info.value, typedef=type_member))
John Zulaufde972ac2017-10-26 12:07:05 -06001301
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +01001302 if item.ifdef_protect is not None:
John Zulaufde972ac2017-10-26 12:07:05 -06001303 code.append('#endif // %s' % item.ifdef_protect)
1304
John Zulauf65ac9d52018-01-23 11:20:50 -07001305 # Generate utilities for all types
1306 code.append('\n'.join((
1307 utilities_format.format(id_member=id_member, id_map=idmap, type_map=typemap,
1308 type_member=type_member, header=generic_header, typename_func=typename_func, idname_func=idname_func,
1309 find_func=find_func, init_func=init_func), ''
1310 )))
1311
John Zulaufde972ac2017-10-26 12:07:05 -06001312 return "\n".join(code)
1313
1314 #
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -07001315 # Create a helper file and return it as a string
1316 def OutputDestFile(self):
Mark Lobodzinski46d388f2016-12-28 10:46:26 -07001317 if self.helper_file_type == 'enum_string_header':
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -07001318 return self.GenerateEnumStringHelperHeader()
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001319 elif self.helper_file_type == 'safe_struct_header':
1320 return self.GenerateSafeStructHelperHeader()
1321 elif self.helper_file_type == 'safe_struct_source':
1322 return self.GenerateSafeStructHelperSource()
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -06001323 elif self.helper_file_type == 'object_types_header':
1324 return self.GenerateObjectTypesHelperHeader()
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -06001325 elif self.helper_file_type == 'extension_helper_header':
1326 return self.GenerateExtensionHelperHeader()
John Zulaufde972ac2017-10-26 12:07:05 -06001327 elif self.helper_file_type == 'typemap_helper_header':
1328 return self.GenerateTypeMapHelperHeader()
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -07001329 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001330 return 'Bad Helper File Generator Option %s' % self.helper_file_type