blob: c1105799412c0ffcb230ce2792be27317902c69f [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'
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600662 object_types_helper_header += '#include <vulkan/vulkan.h>\n\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600663 object_types_helper_header += self.GenerateObjectTypesHeader()
664 return object_types_helper_header
665 #
666 # Object types header: create object enum type header file
667 def GenerateObjectTypesHeader(self):
Mark Young6ba8abe2017-11-09 10:37:04 -0700668 object_types_header = ''
669 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 = {}
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600675
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600676 # Output enum definition as each handle is processed, saving the names to use for the conversion routine
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600677 for item in self.object_types:
678 fixup_name = item[2:]
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600679 enum_entry = 'kVulkanObjectType%s' % fixup_name
John Zulaufd7435c62018-03-16 11:52:57 -0600680 enum_entry_map[item] = enum_entry
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600681 object_types_header += ' ' + enum_entry
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600682 object_types_header += ' = %d,\n' % enum_num
683 enum_num += 1
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600684 type_list.append(enum_entry)
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600685 object_types_header += ' kVulkanObjectTypeMax = %d,\n' % enum_num
John Zulaufd7435c62018-03-16 11:52:57 -0600686 object_types_header += ' // Aliases for backwards compatibilty of "promoted" types\n'
687 for (name, alias) in self.object_type_aliases:
688 fixup_name = name[2:]
689 object_types_header += ' kVulkanObjectType{} = {},\n'.format(fixup_name, enum_entry_map[alias])
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600690 object_types_header += '} VulkanObjectType;\n\n'
691
692 # Output name string helper
693 object_types_header += '// Array of object name strings for OBJECT_TYPE enum conversion\n'
Mark Lobodzinski8eb37422017-04-18 14:22:10 -0600694 object_types_header += 'static const char * const object_string[kVulkanObjectTypeMax] = {\n'
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600695 object_types_header += ' "Unknown",\n'
696 for item in self.object_types:
697 fixup_name = item[2:]
698 object_types_header += ' "%s",\n' % fixup_name
699 object_types_header += '};\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600700
John Zulauf311a4892018-03-12 15:48:06 -0600701 # Key creation helper for map comprehensions that convert between k<Name> and VK<Name> symbols
702 def to_key(regex, raw_key): return re.search(regex, raw_key).group(1).lower().replace("_","")
703
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600704 # Output a conversion routine from the layer object definitions to the debug report definitions
John Zulauf311a4892018-03-12 15:48:06 -0600705 # As the VK_DEBUG_REPORT types are not being updated, specify UNKNOWN for unmatched types
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600706 object_types_header += '\n'
Mark Young1ded24b2017-05-30 14:53:50 -0600707 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 -0600708 object_types_header += 'const VkDebugReportObjectTypeEXT get_debug_report_enum[] = {\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700709 object_types_header += ' VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, // kVulkanObjectTypeUnknown\n'
Gabríel Arthúr Pétursson1a271d02018-03-18 17:34:01 +0000710
John Zulauf311a4892018-03-12 15:48:06 -0600711 dbg_re = '^VK_DEBUG_REPORT_OBJECT_TYPE_(.*)_EXT$'
712 dbg_map = {to_key(dbg_re, dbg) : dbg for dbg in self.debug_report_object_types}
713 dbg_default = 'VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT'
714 for object_type in type_list:
715 vk_object_type = dbg_map.get(object_type.replace("kVulkanObjectType", "").lower(), dbg_default)
716 object_types_header += ' %s, // %s\n' % (vk_object_type, object_type)
Mark Lobodzinskiecf0ae12017-04-13 08:36:18 -0600717 object_types_header += '};\n'
Mark Young1ded24b2017-05-30 14:53:50 -0600718
719 # Output a conversion routine from the layer object definitions to the core object type definitions
John Zulauf311a4892018-03-12 15:48:06 -0600720 # 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 -0600721 object_types_header += '\n'
722 object_types_header += '// Helper array to get Official Vulkan VkObjectType enum from the internal layers version\n'
723 object_types_header += 'const VkObjectType get_object_type_enum[] = {\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700724 object_types_header += ' VK_OBJECT_TYPE_UNKNOWN, // kVulkanObjectTypeUnknown\n'
John Zulauf311a4892018-03-12 15:48:06 -0600725
726 vko_re = '^VK_OBJECT_TYPE_(.*)'
727 vko_map = {to_key(vko_re, vko) : vko for vko in self.core_object_types}
Mark Young1ded24b2017-05-30 14:53:50 -0600728 for object_type in type_list:
John Zulauf311a4892018-03-12 15:48:06 -0600729 vk_object_type = vko_map[object_type.replace("kVulkanObjectType", "").lower()]
730 object_types_header += ' %s, // %s\n' % (vk_object_type, object_type)
Mark Young1ded24b2017-05-30 14:53:50 -0600731 object_types_header += '};\n'
732
Mark Young6ba8abe2017-11-09 10:37:04 -0700733 # Create a function to convert from VkDebugReportObjectTypeEXT to VkObjectType
734 object_types_header += '\n'
735 object_types_header += '// Helper function to convert from VkDebugReportObjectTypeEXT to VkObjectType\n'
Mark Young8504ba62018-03-21 13:35:34 -0600736 object_types_header += 'static inline VkObjectType convertDebugReportObjectToCoreObject(VkDebugReportObjectTypeEXT debug_report_obj){\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700737 object_types_header += ' if (debug_report_obj == VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT) {\n'
738 object_types_header += ' return VK_OBJECT_TYPE_UNKNOWN;\n'
739 for core_object_type in self.core_object_types:
740 core_target_type = core_object_type.replace("VK_OBJECT_TYPE_", "").lower()
741 core_target_type = core_target_type.replace("_", "")
742 for dr_object_type in self.debug_report_object_types:
743 dr_target_type = dr_object_type.replace("VK_DEBUG_REPORT_OBJECT_TYPE_", "").lower()
744 dr_target_type = dr_target_type[:-4]
745 dr_target_type = dr_target_type.replace("_", "")
746 if core_target_type == dr_target_type:
747 object_types_header += ' } else if (debug_report_obj == %s) {\n' % dr_object_type
748 object_types_header += ' return %s;\n' % core_object_type
749 break
750 object_types_header += ' }\n'
751 object_types_header += ' return VK_OBJECT_TYPE_UNKNOWN;\n'
752 object_types_header += '}\n'
753
754 # Create a function to convert from VkObjectType to VkDebugReportObjectTypeEXT
755 object_types_header += '\n'
756 object_types_header += '// Helper function to convert from VkDebugReportObjectTypeEXT to VkObjectType\n'
Mark Young8504ba62018-03-21 13:35:34 -0600757 object_types_header += 'static inline VkDebugReportObjectTypeEXT convertCoreObjectToDebugReportObject(VkObjectType core_report_obj){\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700758 object_types_header += ' if (core_report_obj == VK_OBJECT_TYPE_UNKNOWN) {\n'
759 object_types_header += ' return VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT;\n'
760 for core_object_type in self.core_object_types:
761 core_target_type = core_object_type.replace("VK_OBJECT_TYPE_", "").lower()
762 core_target_type = core_target_type.replace("_", "")
763 for dr_object_type in self.debug_report_object_types:
764 dr_target_type = dr_object_type.replace("VK_DEBUG_REPORT_OBJECT_TYPE_", "").lower()
765 dr_target_type = dr_target_type[:-4]
766 dr_target_type = dr_target_type.replace("_", "")
767 if core_target_type == dr_target_type:
768 object_types_header += ' } else if (core_report_obj == %s) {\n' % core_object_type
769 object_types_header += ' return %s;\n' % dr_object_type
770 break
771 object_types_header += ' }\n'
772 object_types_header += ' return VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT;\n'
773 object_types_header += '}\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600774 return object_types_header
775 #
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700776 # Determine if a structure needs a safe_struct helper function
777 # That is, it has an sType or one of its members is a pointer
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700778 def NeedSafeStruct(self, structure):
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700779 if 'sType' == structure.name:
780 return True
781 for member in structure.members:
782 if member.ispointer == True:
783 return True
784 return False
785 #
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700786 # Combine safe struct helper source file preamble with body text and return
787 def GenerateSafeStructHelperSource(self):
788 safe_struct_helper_source = '\n'
789 safe_struct_helper_source += '#include "vk_safe_struct.h"\n'
790 safe_struct_helper_source += '#include <string.h>\n'
791 safe_struct_helper_source += '\n'
792 safe_struct_helper_source += self.GenerateSafeStructSource()
793 return safe_struct_helper_source
794 #
795 # safe_struct source -- create bodies of safe struct helper functions
796 def GenerateSafeStructSource(self):
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700797 safe_struct_body = []
Mark Lobodzinski560729b2017-03-06 08:59:14 -0700798 wsi_structs = ['VkXlibSurfaceCreateInfoKHR',
799 'VkXcbSurfaceCreateInfoKHR',
800 'VkWaylandSurfaceCreateInfoKHR',
Mark Lobodzinski560729b2017-03-06 08:59:14 -0700801 'VkAndroidSurfaceCreateInfoKHR',
802 'VkWin32SurfaceCreateInfoKHR'
803 ]
Courtney Goeltzenleuchterdb6c2332018-06-28 14:32:55 -0600804
805 # For abstract types just want to save the pointer away
806 # since we cannot make a copy.
807 abstract_types = ['AHardwareBuffer',
808 'ANativeWindow',
809 ]
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700810 for item in self.structMembers:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700811 if self.NeedSafeStruct(item) == False:
812 continue
Mark Lobodzinski560729b2017-03-06 08:59:14 -0700813 if item.name in wsi_structs:
814 continue
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100815 if item.ifdef_protect is not None:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700816 safe_struct_body.append("#ifdef %s\n" % item.ifdef_protect)
817 ss_name = "safe_%s" % item.name
818 init_list = '' # list of members in struct constructor initializer
819 default_init_list = '' # Default constructor just inits ptrs to nullptr in initializer
820 init_func_txt = '' # Txt for initialize() function that takes struct ptr and inits members
821 construct_txt = '' # Body of constuctor as well as body of initialize() func following init_func_txt
822 destruct_txt = ''
Petr Krause91f7a12017-12-14 20:57:36 +0100823
824 custom_construct_txt = {
825 # VkWriteDescriptorSet is special case because pointers may be non-null but ignored
826 'VkWriteDescriptorSet' :
827 ' switch (descriptorType) {\n'
828 ' case VK_DESCRIPTOR_TYPE_SAMPLER:\n'
829 ' case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:\n'
830 ' case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:\n'
831 ' case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:\n'
832 ' case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:\n'
833 ' if (descriptorCount && in_struct->pImageInfo) {\n'
834 ' pImageInfo = new VkDescriptorImageInfo[descriptorCount];\n'
835 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
836 ' pImageInfo[i] = in_struct->pImageInfo[i];\n'
837 ' }\n'
838 ' }\n'
839 ' break;\n'
840 ' case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:\n'
841 ' case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:\n'
842 ' case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:\n'
843 ' case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:\n'
844 ' if (descriptorCount && in_struct->pBufferInfo) {\n'
845 ' pBufferInfo = new VkDescriptorBufferInfo[descriptorCount];\n'
846 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
847 ' pBufferInfo[i] = in_struct->pBufferInfo[i];\n'
848 ' }\n'
849 ' }\n'
850 ' break;\n'
851 ' case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:\n'
852 ' case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:\n'
853 ' if (descriptorCount && in_struct->pTexelBufferView) {\n'
854 ' pTexelBufferView = new VkBufferView[descriptorCount];\n'
855 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
856 ' pTexelBufferView[i] = in_struct->pTexelBufferView[i];\n'
857 ' }\n'
858 ' }\n'
859 ' break;\n'
860 ' default:\n'
861 ' break;\n'
862 ' }\n',
Petr Kraus42f6f8d2017-12-17 17:37:33 +0100863 'VkShaderModuleCreateInfo' :
Petr Krause91f7a12017-12-14 20:57:36 +0100864 ' if (in_struct->pCode) {\n'
865 ' pCode = reinterpret_cast<uint32_t *>(new uint8_t[codeSize]);\n'
866 ' memcpy((void *)pCode, (void *)in_struct->pCode, codeSize);\n'
867 ' }\n',
868 # VkGraphicsPipelineCreateInfo is special case because its pointers may be non-null but ignored
869 'VkGraphicsPipelineCreateInfo' :
870 ' if (stageCount && in_struct->pStages) {\n'
871 ' pStages = new safe_VkPipelineShaderStageCreateInfo[stageCount];\n'
872 ' for (uint32_t i=0; i<stageCount; ++i) {\n'
873 ' pStages[i].initialize(&in_struct->pStages[i]);\n'
874 ' }\n'
875 ' }\n'
876 ' if (in_struct->pVertexInputState)\n'
877 ' pVertexInputState = new safe_VkPipelineVertexInputStateCreateInfo(in_struct->pVertexInputState);\n'
878 ' else\n'
879 ' pVertexInputState = NULL;\n'
880 ' if (in_struct->pInputAssemblyState)\n'
881 ' pInputAssemblyState = new safe_VkPipelineInputAssemblyStateCreateInfo(in_struct->pInputAssemblyState);\n'
882 ' else\n'
883 ' pInputAssemblyState = NULL;\n'
884 ' bool has_tessellation_stage = false;\n'
885 ' if (stageCount && pStages)\n'
886 ' for (uint32_t i=0; i<stageCount && !has_tessellation_stage; ++i)\n'
887 ' if (pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)\n'
888 ' has_tessellation_stage = true;\n'
889 ' if (in_struct->pTessellationState && has_tessellation_stage)\n'
890 ' pTessellationState = new safe_VkPipelineTessellationStateCreateInfo(in_struct->pTessellationState);\n'
891 ' else\n'
892 ' pTessellationState = NULL; // original pTessellationState pointer ignored\n'
893 ' bool has_rasterization = in_struct->pRasterizationState ? !in_struct->pRasterizationState->rasterizerDiscardEnable : false;\n'
894 ' if (in_struct->pViewportState && has_rasterization) {\n'
895 ' bool is_dynamic_viewports = false;\n'
896 ' bool is_dynamic_scissors = false;\n'
897 ' if (in_struct->pDynamicState && in_struct->pDynamicState->pDynamicStates) {\n'
898 ' for (uint32_t i = 0; i < in_struct->pDynamicState->dynamicStateCount && !is_dynamic_viewports; ++i)\n'
899 ' if (in_struct->pDynamicState->pDynamicStates[i] == VK_DYNAMIC_STATE_VIEWPORT)\n'
900 ' is_dynamic_viewports = true;\n'
901 ' for (uint32_t i = 0; i < in_struct->pDynamicState->dynamicStateCount && !is_dynamic_scissors; ++i)\n'
902 ' if (in_struct->pDynamicState->pDynamicStates[i] == VK_DYNAMIC_STATE_SCISSOR)\n'
903 ' is_dynamic_scissors = true;\n'
904 ' }\n'
905 ' pViewportState = new safe_VkPipelineViewportStateCreateInfo(in_struct->pViewportState, is_dynamic_viewports, is_dynamic_scissors);\n'
906 ' } else\n'
907 ' pViewportState = NULL; // original pViewportState pointer ignored\n'
908 ' if (in_struct->pRasterizationState)\n'
909 ' pRasterizationState = new safe_VkPipelineRasterizationStateCreateInfo(in_struct->pRasterizationState);\n'
910 ' else\n'
911 ' pRasterizationState = NULL;\n'
912 ' if (in_struct->pMultisampleState && has_rasterization)\n'
913 ' pMultisampleState = new safe_VkPipelineMultisampleStateCreateInfo(in_struct->pMultisampleState);\n'
914 ' else\n'
915 ' pMultisampleState = NULL; // original pMultisampleState pointer ignored\n'
916 ' // needs a tracked subpass state uses_depthstencil_attachment\n'
917 ' if (in_struct->pDepthStencilState && has_rasterization && uses_depthstencil_attachment)\n'
918 ' pDepthStencilState = new safe_VkPipelineDepthStencilStateCreateInfo(in_struct->pDepthStencilState);\n'
919 ' else\n'
920 ' pDepthStencilState = NULL; // original pDepthStencilState pointer ignored\n'
921 ' // needs a tracked subpass state usesColorAttachment\n'
922 ' if (in_struct->pColorBlendState && has_rasterization && uses_color_attachment)\n'
923 ' pColorBlendState = new safe_VkPipelineColorBlendStateCreateInfo(in_struct->pColorBlendState);\n'
924 ' else\n'
925 ' pColorBlendState = NULL; // original pColorBlendState pointer ignored\n'
926 ' if (in_struct->pDynamicState)\n'
927 ' pDynamicState = new safe_VkPipelineDynamicStateCreateInfo(in_struct->pDynamicState);\n'
928 ' else\n'
929 ' pDynamicState = NULL;\n',
930 # VkPipelineViewportStateCreateInfo is special case because its pointers may be non-null but ignored
931 'VkPipelineViewportStateCreateInfo' :
932 ' if (in_struct->pViewports && !is_dynamic_viewports) {\n'
933 ' pViewports = new VkViewport[in_struct->viewportCount];\n'
934 ' memcpy ((void *)pViewports, (void *)in_struct->pViewports, sizeof(VkViewport)*in_struct->viewportCount);\n'
935 ' }\n'
936 ' else\n'
937 ' pViewports = NULL;\n'
938 ' if (in_struct->pScissors && !is_dynamic_scissors) {\n'
939 ' pScissors = new VkRect2D[in_struct->scissorCount];\n'
940 ' memcpy ((void *)pScissors, (void *)in_struct->pScissors, sizeof(VkRect2D)*in_struct->scissorCount);\n'
941 ' }\n'
942 ' else\n'
943 ' pScissors = NULL;\n',
Petr Kraus42f6f8d2017-12-17 17:37:33 +0100944 # VkDescriptorSetLayoutBinding is special case because its pImmutableSamplers pointer may be non-null but ignored
945 'VkDescriptorSetLayoutBinding' :
946 ' const bool sampler_type = in_struct->descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER || in_struct->descriptorType == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;\n'
947 ' if (descriptorCount && in_struct->pImmutableSamplers && sampler_type) {\n'
948 ' pImmutableSamplers = new VkSampler[descriptorCount];\n'
949 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
950 ' pImmutableSamplers[i] = in_struct->pImmutableSamplers[i];\n'
951 ' }\n'
952 ' }\n',
Petr Krause91f7a12017-12-14 20:57:36 +0100953 }
954
955 custom_copy_txt = {
956 # VkGraphicsPipelineCreateInfo is special case because it has custom construct parameters
957 'VkGraphicsPipelineCreateInfo' :
958 ' if (stageCount && src.pStages) {\n'
959 ' pStages = new safe_VkPipelineShaderStageCreateInfo[stageCount];\n'
960 ' for (uint32_t i=0; i<stageCount; ++i) {\n'
961 ' pStages[i].initialize(&src.pStages[i]);\n'
962 ' }\n'
963 ' }\n'
964 ' if (src.pVertexInputState)\n'
965 ' pVertexInputState = new safe_VkPipelineVertexInputStateCreateInfo(*src.pVertexInputState);\n'
966 ' else\n'
967 ' pVertexInputState = NULL;\n'
968 ' if (src.pInputAssemblyState)\n'
969 ' pInputAssemblyState = new safe_VkPipelineInputAssemblyStateCreateInfo(*src.pInputAssemblyState);\n'
970 ' else\n'
971 ' pInputAssemblyState = NULL;\n'
972 ' bool has_tessellation_stage = false;\n'
973 ' if (stageCount && pStages)\n'
974 ' for (uint32_t i=0; i<stageCount && !has_tessellation_stage; ++i)\n'
975 ' if (pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)\n'
976 ' has_tessellation_stage = true;\n'
977 ' if (src.pTessellationState && has_tessellation_stage)\n'
978 ' pTessellationState = new safe_VkPipelineTessellationStateCreateInfo(*src.pTessellationState);\n'
979 ' else\n'
980 ' pTessellationState = NULL; // original pTessellationState pointer ignored\n'
981 ' bool has_rasterization = src.pRasterizationState ? !src.pRasterizationState->rasterizerDiscardEnable : false;\n'
982 ' if (src.pViewportState && has_rasterization) {\n'
983 ' pViewportState = new safe_VkPipelineViewportStateCreateInfo(*src.pViewportState);\n'
984 ' } else\n'
985 ' pViewportState = NULL; // original pViewportState pointer ignored\n'
986 ' if (src.pRasterizationState)\n'
987 ' pRasterizationState = new safe_VkPipelineRasterizationStateCreateInfo(*src.pRasterizationState);\n'
988 ' else\n'
989 ' pRasterizationState = NULL;\n'
990 ' if (src.pMultisampleState && has_rasterization)\n'
991 ' pMultisampleState = new safe_VkPipelineMultisampleStateCreateInfo(*src.pMultisampleState);\n'
992 ' else\n'
993 ' pMultisampleState = NULL; // original pMultisampleState pointer ignored\n'
994 ' if (src.pDepthStencilState && has_rasterization)\n'
995 ' pDepthStencilState = new safe_VkPipelineDepthStencilStateCreateInfo(*src.pDepthStencilState);\n'
996 ' else\n'
997 ' pDepthStencilState = NULL; // original pDepthStencilState pointer ignored\n'
998 ' if (src.pColorBlendState && has_rasterization)\n'
999 ' pColorBlendState = new safe_VkPipelineColorBlendStateCreateInfo(*src.pColorBlendState);\n'
1000 ' else\n'
1001 ' pColorBlendState = NULL; // original pColorBlendState pointer ignored\n'
1002 ' if (src.pDynamicState)\n'
1003 ' pDynamicState = new safe_VkPipelineDynamicStateCreateInfo(*src.pDynamicState);\n'
1004 ' else\n'
1005 ' pDynamicState = NULL;\n',
1006 # VkPipelineViewportStateCreateInfo is special case because it has custom construct parameters
1007 'VkPipelineViewportStateCreateInfo' :
1008 ' if (src.pViewports) {\n'
1009 ' pViewports = new VkViewport[src.viewportCount];\n'
1010 ' memcpy ((void *)pViewports, (void *)src.pViewports, sizeof(VkViewport)*src.viewportCount);\n'
1011 ' }\n'
1012 ' else\n'
1013 ' pViewports = NULL;\n'
1014 ' if (src.pScissors) {\n'
1015 ' pScissors = new VkRect2D[src.scissorCount];\n'
1016 ' memcpy ((void *)pScissors, (void *)src.pScissors, sizeof(VkRect2D)*src.scissorCount);\n'
1017 ' }\n'
1018 ' else\n'
1019 ' pScissors = NULL;\n',
1020 }
1021
Mike Schuchardt81485762017-09-04 11:38:42 -06001022 custom_destruct_txt = {'VkShaderModuleCreateInfo' :
1023 ' if (pCode)\n'
1024 ' delete[] reinterpret_cast<const uint8_t *>(pCode);\n' }
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001025
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001026 for member in item.members:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001027 m_type = member.type
1028 if member.type in self.structNames:
1029 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
1030 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
1031 m_type = 'safe_%s' % member.type
1032 if member.ispointer and 'safe_' not in m_type and self.TypeContainsObjectHandle(member.type, False) == False:
1033 # 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 -07001034 if m_type in ['void', 'char']:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001035 # For these exceptions just copy initial value over for now
1036 init_list += '\n %s(in_struct->%s),' % (member.name, member.name)
1037 init_func_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001038 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001039 default_init_list += '\n %s(nullptr),' % (member.name)
1040 init_list += '\n %s(nullptr),' % (member.name)
Courtney Goeltzenleuchterdb6c2332018-06-28 14:32:55 -06001041 if m_type in abstract_types:
1042 construct_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
1043 else:
1044 init_func_txt += ' %s = nullptr;\n' % (member.name)
1045 if 'pNext' != member.name and 'void' not in m_type:
1046 if not member.isstaticarray and (member.len is None or '/' in member.len):
1047 construct_txt += ' if (in_struct->%s) {\n' % member.name
1048 construct_txt += ' %s = new %s(*in_struct->%s);\n' % (member.name, m_type, member.name)
1049 construct_txt += ' }\n'
1050 destruct_txt += ' if (%s)\n' % member.name
1051 destruct_txt += ' delete %s;\n' % member.name
1052 else:
1053 construct_txt += ' if (in_struct->%s) {\n' % member.name
1054 construct_txt += ' %s = new %s[in_struct->%s];\n' % (member.name, m_type, member.len)
1055 construct_txt += ' memcpy ((void *)%s, (void *)in_struct->%s, sizeof(%s)*in_struct->%s);\n' % (member.name, member.name, m_type, member.len)
1056 construct_txt += ' }\n'
1057 destruct_txt += ' if (%s)\n' % member.name
1058 destruct_txt += ' delete[] %s;\n' % member.name
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001059 elif member.isstaticarray or member.len is not None:
1060 if member.len is None:
1061 # Extract length of static array by grabbing val between []
1062 static_array_size = re.match(r"[^[]*\[([^]]*)\]", member.cdecl)
1063 construct_txt += ' for (uint32_t i=0; i<%s; ++i) {\n' % static_array_size.group(1)
1064 construct_txt += ' %s[i] = in_struct->%s[i];\n' % (member.name, member.name)
1065 construct_txt += ' }\n'
1066 else:
1067 # Init array ptr to NULL
1068 default_init_list += '\n %s(nullptr),' % member.name
1069 init_list += '\n %s(nullptr),' % member.name
1070 init_func_txt += ' %s = nullptr;\n' % member.name
1071 array_element = 'in_struct->%s[i]' % member.name
1072 if member.type in self.structNames:
1073 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
1074 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
1075 array_element = '%s(&in_struct->safe_%s[i])' % (member.type, member.name)
1076 construct_txt += ' if (%s && in_struct->%s) {\n' % (member.len, member.name)
1077 construct_txt += ' %s = new %s[%s];\n' % (member.name, m_type, member.len)
1078 destruct_txt += ' if (%s)\n' % member.name
1079 destruct_txt += ' delete[] %s;\n' % member.name
1080 construct_txt += ' for (uint32_t i=0; i<%s; ++i) {\n' % (member.len)
1081 if 'safe_' in m_type:
1082 construct_txt += ' %s[i].initialize(&in_struct->%s[i]);\n' % (member.name, member.name)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001083 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001084 construct_txt += ' %s[i] = %s;\n' % (member.name, array_element)
1085 construct_txt += ' }\n'
1086 construct_txt += ' }\n'
1087 elif member.ispointer == True:
1088 construct_txt += ' if (in_struct->%s)\n' % member.name
1089 construct_txt += ' %s = new %s(in_struct->%s);\n' % (member.name, m_type, member.name)
1090 construct_txt += ' else\n'
1091 construct_txt += ' %s = NULL;\n' % member.name
1092 destruct_txt += ' if (%s)\n' % member.name
1093 destruct_txt += ' delete %s;\n' % member.name
1094 elif 'safe_' in m_type:
1095 init_list += '\n %s(&in_struct->%s),' % (member.name, member.name)
1096 init_func_txt += ' %s.initialize(&in_struct->%s);\n' % (member.name, member.name)
1097 else:
1098 init_list += '\n %s(in_struct->%s),' % (member.name, member.name)
1099 init_func_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
1100 if '' != init_list:
1101 init_list = init_list[:-1] # hack off final comma
1102 if item.name in custom_construct_txt:
1103 construct_txt = custom_construct_txt[item.name]
Mike Schuchardt81485762017-09-04 11:38:42 -06001104 if item.name in custom_destruct_txt:
1105 destruct_txt = custom_destruct_txt[item.name]
Petr Krause91f7a12017-12-14 20:57:36 +01001106 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 -07001107 if '' != default_init_list:
1108 default_init_list = " :%s" % (default_init_list[:-1])
1109 safe_struct_body.append("\n%s::%s()%s\n{}" % (ss_name, ss_name, default_init_list))
1110 # Create slight variation of init and construct txt for copy constructor that takes a src object reference vs. struct ptr
1111 copy_construct_init = init_func_txt.replace('in_struct->', 'src.')
1112 copy_construct_txt = construct_txt.replace(' (in_struct->', ' (src.') # Exclude 'if' blocks from next line
1113 copy_construct_txt = copy_construct_txt.replace('(in_struct->', '(*src.') # Pass object to copy constructors
1114 copy_construct_txt = copy_construct_txt.replace('in_struct->', 'src.') # Modify remaining struct refs for src object
Petr Krause91f7a12017-12-14 20:57:36 +01001115 if item.name in custom_copy_txt:
1116 copy_construct_txt = custom_copy_txt[item.name]
Chris Forbesfb633832017-10-03 18:11:54 -07001117 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 -06001118 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 -07001119 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 -07001120 safe_struct_body.append("\n%s::~%s()\n{\n%s}" % (ss_name, ss_name, destruct_txt))
Petr Krause91f7a12017-12-14 20:57:36 +01001121 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 -07001122 # Copy initializer uses same txt as copy constructor but has a ptr and not a reference
1123 init_copy = copy_construct_init.replace('src.', 'src->')
1124 init_construct = copy_construct_txt.replace('src.', 'src->')
Mark Lobodzinski5cd08512017-09-12 09:50:25 -06001125 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 +01001126 if item.ifdef_protect is not None:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001127 safe_struct_body.append("#endif // %s\n" % item.ifdef_protect)
1128 return "\n".join(safe_struct_body)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001129 #
John Zulaufde972ac2017-10-26 12:07:05 -06001130 # Generate the type map
1131 def GenerateTypeMapHelperHeader(self):
1132 prefix = 'Lvl'
1133 fprefix = 'lvl_'
1134 typemap = prefix + 'TypeMap'
1135 idmap = prefix + 'STypeMap'
John Zulaufde972ac2017-10-26 12:07:05 -06001136 type_member = 'Type'
1137 id_member = 'kSType'
Mike Schuchardt97662b02017-12-06 13:31:29 -07001138 id_decl = 'static const VkStructureType '
Locke6b6b7382019-04-16 15:08:49 -06001139 generic_header = 'VkBaseOutStructure'
John Zulaufde972ac2017-10-26 12:07:05 -06001140 typename_func = fprefix + 'typename'
1141 idname_func = fprefix + 'stype_name'
1142 find_func = fprefix + 'find_in_chain'
John Zulauf65ac9d52018-01-23 11:20:50 -07001143 init_func = fprefix + 'init_struct'
John Zulaufde972ac2017-10-26 12:07:05 -06001144
1145 explanatory_comment = '\n'.join((
1146 '// These empty generic templates are specialized for each type with sType',
1147 '// members and for each sType -- providing a two way map between structure',
Mike Schuchardt97662b02017-12-06 13:31:29 -07001148 '// types and sTypes'))
John Zulaufde972ac2017-10-26 12:07:05 -06001149
1150 empty_typemap = 'template <typename T> struct ' + typemap + ' {};'
1151 typemap_format = 'template <> struct {template}<{typename}> {{\n'
John Zulaufde972ac2017-10-26 12:07:05 -06001152 typemap_format += ' {id_decl}{id_member} = {id_value};\n'
1153 typemap_format += '}};\n'
1154
1155 empty_idmap = 'template <VkStructureType id> struct ' + idmap + ' {};'
1156 idmap_format = ''.join((
1157 'template <> struct {template}<{id_value}> {{\n',
1158 ' typedef {typename} {typedef};\n',
John Zulaufde972ac2017-10-26 12:07:05 -06001159 '}};\n'))
1160
1161 # Define the utilities (here so any renaming stays consistent), if this grows large, refactor to a fixed .h file
1162 utilities_format = '\n'.join((
John Zulaufde972ac2017-10-26 12:07:05 -06001163 '// Find an entry of the given type in the pNext chain',
1164 'template <typename T> const T *{find_func}(const void *next) {{',
1165 ' const {header} *current = reinterpret_cast<const {header} *>(next);',
1166 ' const T *found = nullptr;',
1167 ' while (current) {{',
1168 ' if ({type_map}<T>::{id_member} == current->sType) {{',
1169 ' found = reinterpret_cast<const T*>(current);',
1170 ' current = nullptr;',
1171 ' }} else {{',
1172 ' current = current->pNext;',
1173 ' }}',
1174 ' }}',
1175 ' return found;',
1176 '}}',
John Zulauf65ac9d52018-01-23 11:20:50 -07001177 '',
1178 '// Init the header of an sType struct with pNext',
1179 'template <typename T> T {init_func}(void *p_next) {{',
1180 ' T out = {{}};',
1181 ' out.sType = {type_map}<T>::kSType;',
1182 ' out.pNext = p_next;',
1183 ' return out;',
1184 '}}',
1185 '',
1186 '// Init the header of an sType struct',
1187 'template <typename T> T {init_func}() {{',
1188 ' T out = {{}};',
1189 ' out.sType = {type_map}<T>::kSType;',
1190 ' return out;',
1191 '}}',
1192
Mike Schuchardt97662b02017-12-06 13:31:29 -07001193 ''))
John Zulaufde972ac2017-10-26 12:07:05 -06001194
1195 code = []
John Zulauf65ac9d52018-01-23 11:20:50 -07001196
1197 # Generate header
John Zulaufde972ac2017-10-26 12:07:05 -06001198 code.append('\n'.join((
1199 '#pragma once',
1200 '#include <vulkan/vulkan.h>\n',
1201 explanatory_comment, '',
1202 empty_idmap,
John Zulauf65ac9d52018-01-23 11:20:50 -07001203 empty_typemap, '')))
John Zulaufde972ac2017-10-26 12:07:05 -06001204
1205 # Generate the specializations for each type and stype
John Zulaufde972ac2017-10-26 12:07:05 -06001206 for item in self.structMembers:
1207 typename = item.name
1208 info = self.structTypes.get(typename)
1209 if not info:
1210 continue
1211
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +01001212 if item.ifdef_protect is not None:
John Zulaufde972ac2017-10-26 12:07:05 -06001213 code.append('#ifdef %s' % item.ifdef_protect)
1214
1215 code.append('// Map type {} to id {}'.format(typename, info.value))
1216 code.append(typemap_format.format(template=typemap, typename=typename, id_value=info.value,
Mike Schuchardt97662b02017-12-06 13:31:29 -07001217 id_decl=id_decl, id_member=id_member))
1218 code.append(idmap_format.format(template=idmap, typename=typename, id_value=info.value, typedef=type_member))
John Zulaufde972ac2017-10-26 12:07:05 -06001219
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +01001220 if item.ifdef_protect is not None:
John Zulaufde972ac2017-10-26 12:07:05 -06001221 code.append('#endif // %s' % item.ifdef_protect)
1222
John Zulauf65ac9d52018-01-23 11:20:50 -07001223 # Generate utilities for all types
1224 code.append('\n'.join((
1225 utilities_format.format(id_member=id_member, id_map=idmap, type_map=typemap,
1226 type_member=type_member, header=generic_header, typename_func=typename_func, idname_func=idname_func,
1227 find_func=find_func, init_func=init_func), ''
1228 )))
1229
John Zulaufde972ac2017-10-26 12:07:05 -06001230 return "\n".join(code)
1231
1232 #
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -07001233 # Create a helper file and return it as a string
1234 def OutputDestFile(self):
Mark Lobodzinski46d388f2016-12-28 10:46:26 -07001235 if self.helper_file_type == 'enum_string_header':
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -07001236 return self.GenerateEnumStringHelperHeader()
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001237 elif self.helper_file_type == 'safe_struct_header':
1238 return self.GenerateSafeStructHelperHeader()
1239 elif self.helper_file_type == 'safe_struct_source':
1240 return self.GenerateSafeStructHelperSource()
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -06001241 elif self.helper_file_type == 'object_types_header':
1242 return self.GenerateObjectTypesHelperHeader()
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -06001243 elif self.helper_file_type == 'extension_helper_header':
1244 return self.GenerateExtensionHelperHeader()
John Zulaufde972ac2017-10-26 12:07:05 -06001245 elif self.helper_file_type == 'typemap_helper_header':
1246 return self.GenerateTypeMapHelperHeader()
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -07001247 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001248 return 'Bad Helper File Generator Option %s' % self.helper_file_type