blob: 8a02bb2296469c7612194d97e03ea12307fce5ef [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 Lobodzinskib836ac92019-07-18 16:14:43 -060091 self.structextends_list = [] # List of structs which extend another struct via pNext
92
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -060093
Mark Lobodzinski46d388f2016-12-28 10:46:26 -070094 # Named tuples to store struct and command data
95 self.StructType = namedtuple('StructType', ['name', 'value'])
Mark Lobodzinskic67efd02017-01-04 09:16:00 -070096 self.CommandParam = namedtuple('CommandParam', ['type', 'name', 'ispointer', 'isstaticarray', 'isconst', 'iscount', 'len', 'extstructs', 'cdecl'])
Mark Lobodzinski5380d132016-12-28 14:45:34 -070097 self.StructMemberData = namedtuple('StructMemberData', ['name', 'members', 'ifdef_protect'])
Petr Krause91f7a12017-12-14 20:57:36 +010098
99 self.custom_construct_params = {
100 # safe_VkGraphicsPipelineCreateInfo needs to know if subpass has color and\or depth\stencil attachments to use its pointers
101 'VkGraphicsPipelineCreateInfo' :
102 ', const bool uses_color_attachment, const bool uses_depthstencil_attachment',
103 # safe_VkPipelineViewportStateCreateInfo needs to know if viewport and scissor is dynamic to use its pointers
104 'VkPipelineViewportStateCreateInfo' :
105 ', const bool is_dynamic_viewports, const bool is_dynamic_scissors',
106 }
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700107 #
108 # Called once at the beginning of each run
109 def beginFile(self, genOpts):
110 OutputGenerator.beginFile(self, genOpts)
Mike Schuchardt09a1c752019-06-20 12:04:38 -0700111 # Initialize members that require the tree
112 self.handle_types = GetHandleTypes(self.registry.tree)
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700113 # User-supplied prefix text, if any (list of strings)
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700114 self.helper_file_type = genOpts.helper_file_type
115 self.library_name = genOpts.library_name
116 # File Comment
117 file_comment = '// *** THIS FILE IS GENERATED - DO NOT EDIT ***\n'
118 file_comment += '// See helper_file_generator.py for modifications\n'
119 write(file_comment, file=self.outFile)
120 # Copyright Notice
121 copyright = ''
122 copyright += '\n'
123 copyright += '/***************************************************************************\n'
124 copyright += ' *\n'
Mike Schuchardt21638df2019-03-16 10:52:02 -0700125 copyright += ' * Copyright (c) 2015-2019 The Khronos Group Inc.\n'
126 copyright += ' * Copyright (c) 2015-2019 Valve Corporation\n'
127 copyright += ' * Copyright (c) 2015-2019 LunarG, Inc.\n'
128 copyright += ' * Copyright (c) 2015-2019 Google Inc.\n'
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700129 copyright += ' *\n'
130 copyright += ' * Licensed under the Apache License, Version 2.0 (the "License");\n'
131 copyright += ' * you may not use this file except in compliance with the License.\n'
132 copyright += ' * You may obtain a copy of the License at\n'
133 copyright += ' *\n'
134 copyright += ' * http://www.apache.org/licenses/LICENSE-2.0\n'
135 copyright += ' *\n'
136 copyright += ' * Unless required by applicable law or agreed to in writing, software\n'
137 copyright += ' * distributed under the License is distributed on an "AS IS" BASIS,\n'
138 copyright += ' * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n'
139 copyright += ' * See the License for the specific language governing permissions and\n'
140 copyright += ' * limitations under the License.\n'
141 copyright += ' *\n'
142 copyright += ' * Author: Mark Lobodzinski <mark@lunarg.com>\n'
Mark Lobodzinskia9c963d2016-12-28 07:45:35 -0700143 copyright += ' * Author: Courtney Goeltzenleuchter <courtneygo@google.com>\n'
144 copyright += ' * Author: Tobin Ehlis <tobine@google.com>\n'
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600145 copyright += ' * Author: Chris Forbes <chrisforbes@google.com>\n'
John Zulaufde972ac2017-10-26 12:07:05 -0600146 copyright += ' * Author: John Zulauf<jzulauf@lunarg.com>\n'
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700147 copyright += ' *\n'
148 copyright += ' ****************************************************************************/\n'
149 write(copyright, file=self.outFile)
150 #
Mark Lobodzinskia3cc3612017-01-03 13:25:10 -0700151 # Write generated file content to output file
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700152 def endFile(self):
153 dest_file = ''
154 dest_file += self.OutputDestFile()
Mark Lobodzinskiafe10542017-01-03 13:22:44 -0700155 # Remove blank lines at EOF
156 if dest_file.endswith('\n'):
157 dest_file = dest_file[:-1]
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700158 write(dest_file, file=self.outFile);
159 # Finish processing in superclass
160 OutputGenerator.endFile(self)
161 #
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600162 # Override parent class to be notified of the beginning of an extension
163 def beginFeature(self, interface, emit):
164 # Start processing in superclass
165 OutputGenerator.beginFeature(self, interface, emit)
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600166 self.featureExtraProtect = GetFeatureProtect(interface)
167
Mark Lobodzinski31964ca2017-09-18 14:15:09 -0600168 if self.featureName == 'VK_VERSION_1_0' or self.featureName == 'VK_VERSION_1_1':
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600169 return
John Zulauff6feb2a2018-04-12 14:24:57 -0600170 name = self.featureName
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600171 nameElem = interface[0][1]
John Zulauff6feb2a2018-04-12 14:24:57 -0600172 name_define = nameElem.get('name')
173 if 'EXTENSION_NAME' not in name_define:
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600174 print("Error in vk.xml file -- extension name is not available")
John Zulauf072677c2018-04-12 15:34:39 -0600175 requires = interface.get('requires')
176 if requires is not None:
177 required_extensions = requires.split(',')
178 else:
179 required_extensions = list()
180 info = { 'define': name_define, 'ifdef':self.featureExtraProtect, 'reqs':required_extensions }
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600181 if interface.get('type') == 'instance':
John Zulauff6feb2a2018-04-12 14:24:57 -0600182 self.instance_extension_info[name] = info
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600183 else:
John Zulauff6feb2a2018-04-12 14:24:57 -0600184 self.device_extension_info[name] = info
185
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600186 #
187 # Override parent class to be notified of the end of an extension
188 def endFeature(self):
189 # Finish processing in superclass
190 OutputGenerator.endFeature(self)
191 #
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700192 # Grab group (e.g. C "enum" type) info to output for enum-string conversion helper
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700193 def genGroup(self, groupinfo, groupName, alias):
194 OutputGenerator.genGroup(self, groupinfo, groupName, alias)
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700195 groupElem = groupinfo.elem
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700196 # For enum_string_header
197 if self.helper_file_type == 'enum_string_header':
Mike Schuchardtdf1e8dd2018-03-09 09:02:56 -0700198 value_set = set()
Mark Lobodzinski824ce642016-12-28 08:49:46 -0700199 for elem in groupElem.findall('enum'):
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100200 if elem.get('supported') != 'disabled' and elem.get('alias') is None:
Mike Schuchardtdf1e8dd2018-03-09 09:02:56 -0700201 value_set.add(elem.get('name'))
Tobias Hector30ad4fc2018-12-10 12:21:17 +0000202 if value_set != set():
203 self.enum_output += self.GenerateEnumStringConversion(groupName, value_set)
Mark Young1ded24b2017-05-30 14:53:50 -0600204 elif self.helper_file_type == 'object_types_header':
205 if groupName == 'VkDebugReportObjectTypeEXT':
206 for elem in groupElem.findall('enum'):
207 if elem.get('supported') != 'disabled':
208 item_name = elem.get('name')
209 self.debug_report_object_types.append(item_name)
210 elif groupName == 'VkObjectType':
211 for elem in groupElem.findall('enum'):
212 if elem.get('supported') != 'disabled':
213 item_name = elem.get('name')
214 self.core_object_types.append(item_name)
215
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700216 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700217 # Called for each type -- if the type is a struct/union, grab the metadata
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700218 def genType(self, typeinfo, name, alias):
219 OutputGenerator.genType(self, typeinfo, name, alias)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700220 typeElem = typeinfo.elem
221 # If the type is a struct type, traverse the imbedded <member> tags generating a structure.
222 # Otherwise, emit the tag text.
223 category = typeElem.get('category')
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600224 if category == 'handle':
John Zulaufd7435c62018-03-16 11:52:57 -0600225 if alias:
226 self.object_type_aliases.append((name,alias))
227 else:
228 self.object_types.append(name)
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600229 elif (category == 'struct' or category == 'union'):
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700230 self.structNames.append(name)
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700231 self.genStruct(typeinfo, name, alias)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700232 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700233 # Check if the parameter passed in is a pointer
234 def paramIsPointer(self, param):
235 ispointer = False
236 for elem in param:
Raul Tambre7b300182019-05-04 11:25:14 +0300237 if elem.tag == 'type' and elem.tail is not None and '*' in elem.tail:
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700238 ispointer = True
239 return ispointer
240 #
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700241 # Check if the parameter passed in is a static array
242 def paramIsStaticArray(self, param):
243 isstaticarray = 0
244 paramname = param.find('name')
245 if (paramname.tail is not None) and ('[' in paramname.tail):
246 isstaticarray = paramname.tail.count('[')
247 return isstaticarray
248 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700249 # Retrieve the type and name for a parameter
250 def getTypeNameTuple(self, param):
251 type = ''
252 name = ''
253 for elem in param:
254 if elem.tag == 'type':
255 type = noneStr(elem.text)
256 elif elem.tag == 'name':
257 name = noneStr(elem.text)
258 return (type, name)
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700259 # Extract length values from latexmath. Currently an inflexible solution that looks for specific
260 # patterns that are found in vk.xml. Will need to be updated when new patterns are introduced.
261 def parseLateXMath(self, source):
262 name = 'ERROR'
263 decoratedName = 'ERROR'
264 if 'mathit' in source:
Mark Lobodzinski36c33862017-02-13 10:15:53 -0700265 # Matches expressions similar to 'latexmath:[\lceil{\mathit{rasterizationSamples} \over 32}\rceil]'
266 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 -0700267 if not match or match.group(1) != match.group(4):
268 raise 'Unrecognized latexmath expression'
269 name = match.group(2)
mizhenc27f6c72017-03-31 09:08:16 -0600270 # Need to add 1 for ceiling function; otherwise, the allocated packet
271 # size will be less than needed during capture for some title which use
272 # this in VkPipelineMultisampleStateCreateInfo. based on ceiling function
273 # definition,it is '{0}%{1}?{0}/{1} + 1:{0}/{1}'.format(*match.group(2, 3)),
274 # its value <= '{}/{} + 1'.
275 if match.group(1) == 'ceil':
276 decoratedName = '{}/{} + 1'.format(*match.group(2, 3))
277 else:
278 decoratedName = '{}/{}'.format(*match.group(2, 3))
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700279 else:
Mark Lobodzinski36c33862017-02-13 10:15:53 -0700280 # Matches expressions similar to 'latexmath : [dataSize \over 4]'
Shannon McPhersonbd68df02018-10-29 15:04:41 -0600281 match = re.match(r'latexmath\s*\:\s*\[\s*(\\textrm\{)?(\w+)\}?\s*\\over\s*(\d+)\s*\]', source)
282 name = match.group(2)
283 decoratedName = '{}/{}'.format(*match.group(2, 3))
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700284 return name, decoratedName
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700285 #
286 # Retrieve the value of the len tag
287 def getLen(self, param):
288 result = None
289 len = param.attrib.get('len')
290 if len and len != 'null-terminated':
291 # For string arrays, 'len' can look like 'count,null-terminated', indicating that we
292 # have a null terminated array of strings. We strip the null-terminated from the
293 # 'len' field and only return the parameter specifying the string count
294 if 'null-terminated' in len:
295 result = len.split(',')[0]
296 else:
297 result = len
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700298 if 'latexmath' in len:
299 param_type, param_name = self.getTypeNameTuple(param)
300 len_name, result = self.parseLateXMath(len)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700301 # Spec has now notation for len attributes, using :: instead of platform specific pointer symbol
302 result = str(result).replace('::', '->')
303 return result
304 #
Shannon McPhersonbd68df02018-10-29 15:04:41 -0600305 # Check if a structure is or contains a dispatchable (dispatchable = True) or
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700306 # non-dispatchable (dispatchable = False) handle
307 def TypeContainsObjectHandle(self, handle_type, dispatchable):
308 if dispatchable:
Mike Schuchardtf8690262019-07-11 10:08:33 -0700309 type_check = self.handle_types.IsDispatchable
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700310 else:
Mike Schuchardtf8690262019-07-11 10:08:33 -0700311 type_check = self.handle_types.IsNonDispatchable
312 if type_check(handle_type):
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700313 return True
314 # if handle_type is a struct, search its members
315 if handle_type in self.structNames:
316 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == handle_type), None)
317 if member_index is not None:
318 for item in self.structMembers[member_index].members:
Mike Schuchardtf8690262019-07-11 10:08:33 -0700319 if type_check(item.type):
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700320 return True
321 return False
322 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700323 # Generate local ready-access data describing Vulkan structures and unions from the XML metadata
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700324 def genStruct(self, typeinfo, typeName, alias):
325 OutputGenerator.genStruct(self, typeinfo, typeName, alias)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700326 members = typeinfo.elem.findall('.//member')
327 # Iterate over members once to get length parameters for arrays
328 lens = set()
329 for member in members:
330 len = self.getLen(member)
331 if len:
332 lens.add(len)
333 # Generate member info
334 membersInfo = []
335 for member in members:
336 # Get the member's type and name
337 info = self.getTypeNameTuple(member)
338 type = info[0]
339 name = info[1]
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700340 cdecl = self.makeCParamDecl(member, 1)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700341 # Process VkStructureType
342 if type == 'VkStructureType':
343 # Extract the required struct type value from the comments
344 # embedded in the original text defining the 'typeinfo' element
345 rawXml = etree.tostring(typeinfo.elem).decode('ascii')
346 result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml)
347 if result:
348 value = result.group(0)
Mike Schuchardt08368cb2018-05-22 14:52:04 -0600349 # Store the required type value
350 self.structTypes[typeName] = self.StructType(name=name, value=value)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700351 # Store pointer/array/string info
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700352 isstaticarray = self.paramIsStaticArray(member)
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600353 structextends = False
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700354 membersInfo.append(self.CommandParam(type=type,
355 name=name,
356 ispointer=self.paramIsPointer(member),
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700357 isstaticarray=isstaticarray,
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700358 isconst=True if 'const' in cdecl else False,
359 iscount=True if name in lens else False,
360 len=self.getLen(member),
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600361 extstructs=self.registry.validextensionstructs[typeName] if name == 'pNext' else None,
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700362 cdecl=cdecl))
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600363 # If this struct extends another, keep its name in list for further processing
364 if typeinfo.elem.attrib.get('structextends') is not None:
365 self.structextends_list.append(typeName)
Mark Lobodzinski5380d132016-12-28 14:45:34 -0700366 self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo, ifdef_protect=self.featureExtraProtect))
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700367 #
368 # Enum_string_header: Create a routine to convert an enumerated value into a string
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700369 def GenerateEnumStringConversion(self, groupName, value_list):
370 outstring = '\n'
Mike Schuchardt21638df2019-03-16 10:52:02 -0700371 if self.featureExtraProtect is not None:
372 outstring += '\n#ifdef %s\n\n' % self.featureExtraProtect
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700373 outstring += 'static inline const char* string_%s(%s input_value)\n' % (groupName, groupName)
374 outstring += '{\n'
375 outstring += ' switch ((%s)input_value)\n' % groupName
376 outstring += ' {\n'
Karl Schultz7fd3f6e2018-07-05 17:21:05 -0600377 # Emit these in a repeatable order so file is generated with the same contents each time.
378 # This helps compiler caching systems like ccache.
379 for item in sorted(value_list):
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700380 outstring += ' case %s:\n' % item
381 outstring += ' return "%s";\n' % item
382 outstring += ' default:\n'
383 outstring += ' return "Unhandled %s";\n' % groupName
384 outstring += ' }\n'
385 outstring += '}\n'
unknown84220292019-07-01 17:09:36 -0600386
387 bitsIndex = groupName.find('Bits')
388 if (bitsIndex != -1):
389 outstring += '\n'
390 flagsName = groupName[0:bitsIndex] + "s" + groupName[bitsIndex+4:]
391 outstring += 'static inline std::string string_%s(%s input_value)\n' % (flagsName, flagsName)
392 outstring += '{\n'
393 outstring += ' std::string ret;\n'
394 outstring += ' int index = 0;\n'
395 outstring += ' while(input_value) {\n'
396 outstring += ' if (input_value & 1) {\n'
397 outstring += ' if( !ret.empty()) ret.append("|");\n'
398 outstring += ' ret.append(string_%s(static_cast<%s>(1 << index)));\n' % (groupName, groupName)
399 outstring += ' }\n'
400 outstring += ' ++index;\n'
401 outstring += ' input_value >>= 1;\n'
402 outstring += ' }\n'
403 outstring += ' if( ret.empty()) ret.append(string_%s(static_cast<%s>(0)));\n' % (groupName, groupName)
404 outstring += ' return ret;\n'
405 outstring += '}\n'
406
Mike Schuchardt21638df2019-03-16 10:52:02 -0700407 if self.featureExtraProtect is not None:
408 outstring += '#endif // %s\n' % self.featureExtraProtect
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700409 return outstring
410 #
Mark Lobodzinski64b432f2017-07-24 16:14:16 -0600411 # Tack on a helper which, given an index into a VkPhysicalDeviceFeatures structure, will print the corresponding feature name
412 def DeIndexPhysDevFeatures(self):
413 pdev_members = None
414 for name, members, ifdef in self.structMembers:
415 if name == 'VkPhysicalDeviceFeatures':
416 pdev_members = members
417 break
418 deindex = '\n'
Mark Young2ee6aea2018-02-21 15:30:27 -0700419 deindex += 'static inline const char * GetPhysDevFeatureString(uint32_t index) {\n'
Mark Lobodzinski64b432f2017-07-24 16:14:16 -0600420 deindex += ' const char * IndexToPhysDevFeatureString[] = {\n'
421 for feature in pdev_members:
422 deindex += ' "%s",\n' % feature.name
423 deindex += ' };\n\n'
424 deindex += ' return IndexToPhysDevFeatureString[index];\n'
425 deindex += '}\n'
426 return deindex
427 #
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700428 # Combine enum string helper header file preamble with body text and return
429 def GenerateEnumStringHelperHeader(self):
430 enum_string_helper_header = '\n'
431 enum_string_helper_header += '#pragma once\n'
432 enum_string_helper_header += '#ifdef _WIN32\n'
433 enum_string_helper_header += '#pragma warning( disable : 4065 )\n'
434 enum_string_helper_header += '#endif\n'
435 enum_string_helper_header += '\n'
David Pinedoddbb7fb2019-07-22 11:36:51 -0600436 enum_string_helper_header += '#include <string>\n'
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700437 enum_string_helper_header += '#include <vulkan/vulkan.h>\n'
438 enum_string_helper_header += '\n'
439 enum_string_helper_header += self.enum_output
Mark Lobodzinski64b432f2017-07-24 16:14:16 -0600440 enum_string_helper_header += self.DeIndexPhysDevFeatures()
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700441 return enum_string_helper_header
442 #
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -0700443 # Helper function for declaring a counter variable only once
444 def DeclareCounter(self, string_var, declare_flag):
445 if declare_flag == False:
446 string_var += ' uint32_t i = 0;\n'
447 declare_flag = True
448 return string_var, declare_flag
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700449 #
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700450 # Combine safe struct helper header file preamble with body text and return
451 def GenerateSafeStructHelperHeader(self):
452 safe_struct_helper_header = '\n'
453 safe_struct_helper_header += '#pragma once\n'
454 safe_struct_helper_header += '#include <vulkan/vulkan.h>\n'
455 safe_struct_helper_header += '\n'
Mark Lobodzinski7245fce2019-07-18 16:18:51 -0600456 safe_struct_helper_header += 'void *SafePnextCopy(const void *pNext);\n'
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -0600457 safe_struct_helper_header += 'void FreePnextChain(const void *head);\n'
Mark Lobodzinski7245fce2019-07-18 16:18:51 -0600458 safe_struct_helper_header += 'void FreePnextChain(void *head);\n'
459 safe_struct_helper_header += '\n'
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700460 safe_struct_helper_header += self.GenerateSafeStructHeader()
461 return safe_struct_helper_header
462 #
463 # safe_struct header: build function prototypes for header file
464 def GenerateSafeStructHeader(self):
465 safe_struct_header = ''
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700466 for item in self.structMembers:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700467 if self.NeedSafeStruct(item) == True:
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700468 safe_struct_header += '\n'
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100469 if item.ifdef_protect is not None:
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700470 safe_struct_header += '#ifdef %s\n' % item.ifdef_protect
471 safe_struct_header += 'struct safe_%s {\n' % (item.name)
472 for member in item.members:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700473 if member.type in self.structNames:
474 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
475 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
476 if member.ispointer:
477 safe_struct_header += ' safe_%s* %s;\n' % (member.type, member.name)
478 else:
479 safe_struct_header += ' safe_%s %s;\n' % (member.type, member.name)
480 continue
481 if member.len is not None and (self.TypeContainsObjectHandle(member.type, True) or self.TypeContainsObjectHandle(member.type, False)):
482 safe_struct_header += ' %s* %s;\n' % (member.type, member.name)
483 else:
484 safe_struct_header += '%s;\n' % member.cdecl
Petr Krause91f7a12017-12-14 20:57:36 +0100485 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 -0600486 safe_struct_header += ' safe_%s(const safe_%s& src);\n' % (item.name, item.name)
Chris Forbesfb633832017-10-03 18:11:54 -0700487 safe_struct_header += ' safe_%s& operator=(const safe_%s& src);\n' % (item.name, item.name)
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700488 safe_struct_header += ' safe_%s();\n' % item.name
489 safe_struct_header += ' ~safe_%s();\n' % item.name
Petr Krause91f7a12017-12-14 20:57:36 +0100490 safe_struct_header += ' void initialize(const %s* in_struct%s);\n' % (item.name, self.custom_construct_params.get(item.name, ''))
491 safe_struct_header += ' void initialize(const safe_%s* src);\n' % (item.name)
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700492 safe_struct_header += ' %s *ptr() { return reinterpret_cast<%s *>(this); }\n' % (item.name, item.name)
493 safe_struct_header += ' %s const *ptr() const { return reinterpret_cast<%s const *>(this); }\n' % (item.name, item.name)
494 safe_struct_header += '};\n'
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100495 if item.ifdef_protect is not None:
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700496 safe_struct_header += '#endif // %s\n' % item.ifdef_protect
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700497 return safe_struct_header
498 #
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600499 # Generate extension helper header file
500 def GenerateExtensionHelperHeader(self):
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600501
Mark Lobodzinski6ad0fbe2019-07-10 14:20:34 -0600502 V_1_1_level_feature_set = [
503 'VK_VERSION_1_1',
504 ]
505
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600506 V_1_0_instance_extensions_promoted_to_V_1_1_core = [
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600507 'vk_khr_device_group_creation',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600508 'vk_khr_external_fence_capabilities',
John Zulauf2012bca2018-04-25 15:28:47 -0600509 'vk_khr_external_memory_capabilities',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600510 'vk_khr_external_semaphore_capabilities',
511 'vk_khr_get_physical_device_properties_2',
512 ]
513
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600514 V_1_0_device_extensions_promoted_to_V_1_1_core = [
John Zulauf2012bca2018-04-25 15:28:47 -0600515 'vk_khr_16bit_storage',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600516 'vk_khr_bind_memory_2',
John Zulauf2012bca2018-04-25 15:28:47 -0600517 'vk_khr_dedicated_allocation',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600518 'vk_khr_descriptor_update_template',
John Zulauf2012bca2018-04-25 15:28:47 -0600519 'vk_khr_device_group',
520 'vk_khr_external_fence',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600521 'vk_khr_external_memory',
522 'vk_khr_external_semaphore',
John Zulauf2012bca2018-04-25 15:28:47 -0600523 'vk_khr_get_memory_requirements_2',
524 'vk_khr_maintenance1',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600525 'vk_khr_maintenance2',
John Zulauf2012bca2018-04-25 15:28:47 -0600526 'vk_khr_maintenance3',
527 'vk_khr_multiview',
John Zulauf16826822018-04-25 15:40:32 -0600528 'vk_khr_relaxed_block_layout',
John Zulauf2012bca2018-04-25 15:28:47 -0600529 'vk_khr_sampler_ycbcr_conversion',
John Zulauf16826822018-04-25 15:40:32 -0600530 'vk_khr_shader_draw_parameters',
531 'vk_khr_storage_buffer_storage_class',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600532 'vk_khr_variable_pointers',
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600533 ]
John Zulauf16826822018-04-25 15:40:32 -0600534
John Zulauff6feb2a2018-04-12 14:24:57 -0600535 output = [
536 '',
537 '#ifndef VK_EXTENSION_HELPER_H_',
538 '#define VK_EXTENSION_HELPER_H_',
Mark Lobodzinskif6a62282018-06-28 09:21:18 -0600539 '#include <unordered_set>',
John Zulauf072677c2018-04-12 15:34:39 -0600540 '#include <string>',
541 '#include <unordered_map>',
John Zulauff6feb2a2018-04-12 14:24:57 -0600542 '#include <utility>',
Mark Lobodzinskia0555012018-08-15 16:43:49 -0600543 '#include <set>',
Mark Lobodzinskif94196f2019-07-11 11:46:09 -0600544 '#include <vector>',
John Zulauff6feb2a2018-04-12 14:24:57 -0600545 '',
John Zulauf072677c2018-04-12 15:34:39 -0600546 '#include <vulkan/vulkan.h>',
John Zulauff6feb2a2018-04-12 14:24:57 -0600547 '']
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600548
John Zulauff6feb2a2018-04-12 14:24:57 -0600549 def guarded(ifdef, value):
550 if ifdef is not None:
551 return '\n'.join([ '#ifdef %s' % ifdef, value, '#endif' ])
552 else:
553 return value
John Zulauf380bd942018-04-10 13:12:34 -0600554
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600555 for type in ['Instance', 'Device']:
John Zulauff6feb2a2018-04-12 14:24:57 -0600556 struct_type = '%sExtensions' % type
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600557 if type == 'Instance':
John Zulauff6feb2a2018-04-12 14:24:57 -0600558 extension_dict = self.instance_extension_info
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600559 promoted_ext_list = V_1_0_instance_extensions_promoted_to_V_1_1_core
John Zulauff6feb2a2018-04-12 14:24:57 -0600560 struct_decl = 'struct %s {' % struct_type
561 instance_struct_type = struct_type
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600562 else:
John Zulauff6feb2a2018-04-12 14:24:57 -0600563 extension_dict = self.device_extension_info
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600564 promoted_ext_list = V_1_0_device_extensions_promoted_to_V_1_1_core
John Zulauff6feb2a2018-04-12 14:24:57 -0600565 struct_decl = 'struct %s : public %s {' % (struct_type, instance_struct_type)
566
567 extension_items = sorted(extension_dict.items())
568
569 field_name = { ext_name: re.sub('_extension_name', '', info['define'].lower()) for ext_name, info in extension_items }
Mark Lobodzinski6ad0fbe2019-07-10 14:20:34 -0600570
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600571 if type == 'Instance':
John Zulauff6feb2a2018-04-12 14:24:57 -0600572 instance_field_name = field_name
John Zulauf072677c2018-04-12 15:34:39 -0600573 instance_extension_dict = extension_dict
574 else:
575 # Get complete field name and extension data for both Instance and Device extensions
576 field_name.update(instance_field_name)
577 extension_dict = extension_dict.copy() # Don't modify the self.<dict> we're pointing to
578 extension_dict.update(instance_extension_dict)
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600579
John Zulauf072677c2018-04-12 15:34:39 -0600580 # Output the data member list
John Zulauff6feb2a2018-04-12 14:24:57 -0600581 struct = [struct_decl]
Mark Lobodzinski6ad0fbe2019-07-10 14:20:34 -0600582 struct.extend([ ' bool vk_feature_version_1_1{false};'])
John Zulauff6feb2a2018-04-12 14:24:57 -0600583 struct.extend([ ' bool %s{false};' % field_name[ext_name] for ext_name, info in extension_items])
John Zulauf072677c2018-04-12 15:34:39 -0600584
585 # Construct the extension information map -- mapping name to data member (field), and required extensions
586 # The map is contained within a static function member for portability reasons.
587 info_type = '%sInfo' % type
588 info_map_type = '%sMap' % info_type
589 req_type = '%sReq' % type
590 req_vec_type = '%sVec' % req_type
591 struct.extend([
592 '',
593 ' struct %s {' % req_type,
594 ' const bool %s::* enabled;' % struct_type,
595 ' const char *name;',
596 ' };',
597 ' typedef std::vector<%s> %s;' % (req_type, req_vec_type),
598 ' struct %s {' % info_type,
599 ' %s(bool %s::* state_, const %s requires_): state(state_), requires(requires_) {}' % ( info_type, struct_type, req_vec_type),
600 ' bool %s::* state;' % struct_type,
601 ' %s requires;' % req_vec_type,
602 ' };',
603 '',
604 ' typedef std::unordered_map<std::string,%s> %s;' % (info_type, info_map_type),
605 ' static const %s &get_info(const char *name) {' %info_type,
606 ' static const %s info_map = {' % info_map_type ])
Mark Lobodzinski6ad0fbe2019-07-10 14:20:34 -0600607 struct.extend([
608 ' std::make_pair("VK_VERSION_1_1", %sInfo(&%sExtensions::vk_feature_version_1_1, {})),' % (type, type)])
John Zulauf072677c2018-04-12 15:34:39 -0600609
610 field_format = '&' + struct_type + '::%s'
611 req_format = '{' + field_format+ ', %s}'
612 req_indent = '\n '
613 req_join = ',' + req_indent
614 info_format = (' std::make_pair(%s, ' + info_type + '(' + field_format + ', {%s})),')
615 def format_info(ext_name, info):
616 reqs = req_join.join([req_format % (field_name[req], extension_dict[req]['define']) for req in info['reqs']])
617 return info_format % (info['define'], field_name[ext_name], '{%s}' % (req_indent + reqs) if reqs else '')
618
619 struct.extend([guarded(info['ifdef'], format_info(ext_name, info)) for ext_name, info in extension_items])
620 struct.extend([
621 ' };',
622 '',
623 ' static const %s empty_info {nullptr, %s()};' % (info_type, req_vec_type),
624 ' %s::const_iterator info = info_map.find(name);' % info_map_type,
625 ' if ( info != info_map.cend()) {',
626 ' return info->second;',
627 ' }',
628 ' return empty_info;',
629 ' }',
630 ''])
631
John Zulauff6feb2a2018-04-12 14:24:57 -0600632 if type == 'Instance':
633 struct.extend([
634 ' uint32_t NormalizeApiVersion(uint32_t specified_version) {',
635 ' uint32_t api_version = (specified_version < VK_API_VERSION_1_1) ? VK_API_VERSION_1_0 : VK_API_VERSION_1_1;',
636 ' return api_version;',
637 ' }',
638 '',
639 ' uint32_t InitFromInstanceCreateInfo(uint32_t requested_api_version, const VkInstanceCreateInfo *pCreateInfo) {'])
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600640 else:
John Zulauff6feb2a2018-04-12 14:24:57 -0600641 struct.extend([
John Zulauf072677c2018-04-12 15:34:39 -0600642 ' %s() = default;' % struct_type,
643 ' %s(const %s& instance_ext) : %s(instance_ext) {}' % (struct_type, instance_struct_type, instance_struct_type),
644 '',
645 ' uint32_t InitFromDeviceCreateInfo(const %s *instance_extensions, uint32_t requested_api_version,' % instance_struct_type,
646 ' const VkDeviceCreateInfo *pCreateInfo) {',
647 ' // Initialize: this to defaults, base class fields to input.',
648 ' assert(instance_extensions);',
Mark Lobodzinskif6a62282018-06-28 09:21:18 -0600649 ' *this = %s(*instance_extensions);' % struct_type,
Mark Lobodzinskid5f83b92018-12-14 11:02:08 -0700650 '']),
651 struct.extend([
John Zulauff6feb2a2018-04-12 14:24:57 -0600652 '',
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600653 ' static const std::vector<const char *> V_1_1_promoted_%s_apis = {' % type.lower() ])
John Zulauff6feb2a2018-04-12 14:24:57 -0600654 struct.extend([' %s_EXTENSION_NAME,' % ext_name.upper() for ext_name in promoted_ext_list])
Mark Lobodzinski6ad0fbe2019-07-10 14:20:34 -0600655 struct.extend([' "VK_VERSION_1_1",'])
John Zulauff6feb2a2018-04-12 14:24:57 -0600656 struct.extend([
657 ' };',
658 '',
John Zulauf072677c2018-04-12 15:34:39 -0600659 ' // Initialize struct data, robust to invalid pCreateInfo',
660 ' if (pCreateInfo->ppEnabledExtensionNames) {',
661 ' for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {',
662 ' if (!pCreateInfo->ppEnabledExtensionNames[i]) continue;',
663 ' auto info = get_info(pCreateInfo->ppEnabledExtensionNames[i]);',
664 ' if(info.state) this->*(info.state) = true;',
John Zulauff6feb2a2018-04-12 14:24:57 -0600665 ' }',
666 ' }',
667 ' uint32_t api_version = NormalizeApiVersion(requested_api_version);',
668 ' if (api_version >= VK_API_VERSION_1_1) {',
Mark Lobodzinski71a4b562019-07-16 10:47:17 -0600669 ' for (auto promoted_ext : V_1_1_promoted_%s_apis) {' % type.lower(),
John Zulauf072677c2018-04-12 15:34:39 -0600670 ' auto info = get_info(promoted_ext);',
671 ' assert(info.state);',
672 ' if (info.state) this->*(info.state) = true;',
John Zulauff6feb2a2018-04-12 14:24:57 -0600673 ' }',
674 ' }',
675 ' return api_version;',
676 ' }',
John Zulauf072677c2018-04-12 15:34:39 -0600677 '};'])
John Zulauff6feb2a2018-04-12 14:24:57 -0600678
Mark Lobodzinskifc9451f2018-01-03 11:18:31 -0700679 # Output reference lists of instance/device extension names
Mark Lobodzinskia0555012018-08-15 16:43:49 -0600680 struct.extend(['', 'static const std::set<std::string> k%sExtensionNames = {' % type])
681 struct.extend([guarded(info['ifdef'], ' %s,' % info['define']) for ext_name, info in extension_items])
682 struct.extend(['};', ''])
John Zulauff6feb2a2018-04-12 14:24:57 -0600683 output.extend(struct)
684
685 output.extend(['', '#endif // VK_EXTENSION_HELPER_H_'])
686 return '\n'.join(output)
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600687 #
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600688 # Combine object types helper header file preamble with body text and return
689 def GenerateObjectTypesHelperHeader(self):
690 object_types_helper_header = '\n'
691 object_types_helper_header += '#pragma once\n'
692 object_types_helper_header += '\n'
693 object_types_helper_header += self.GenerateObjectTypesHeader()
694 return object_types_helper_header
695 #
696 # Object types header: create object enum type header file
697 def GenerateObjectTypesHeader(self):
John Zulauf4fea6622019-04-01 11:38:18 -0600698 object_types_header = '#include "cast_utils.h"\n'
699 object_types_header += '\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700700 object_types_header += '// Object Type enum for validation layer internal object handling\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600701 object_types_header += 'typedef enum VulkanObjectType {\n'
702 object_types_header += ' kVulkanObjectTypeUnknown = 0,\n'
703 enum_num = 1
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600704 type_list = [];
John Zulaufd7435c62018-03-16 11:52:57 -0600705 enum_entry_map = {}
John Zulauf2c2ccd42019-04-05 13:13:13 -0600706 non_dispatchable = {}
707 dispatchable = {}
708 object_type_info = {}
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600709
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600710 # Output enum definition as each handle is processed, saving the names to use for the conversion routine
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600711 for item in self.object_types:
712 fixup_name = item[2:]
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600713 enum_entry = 'kVulkanObjectType%s' % fixup_name
John Zulaufd7435c62018-03-16 11:52:57 -0600714 enum_entry_map[item] = enum_entry
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600715 object_types_header += ' ' + enum_entry
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600716 object_types_header += ' = %d,\n' % enum_num
717 enum_num += 1
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600718 type_list.append(enum_entry)
John Zulauf2c2ccd42019-04-05 13:13:13 -0600719 object_type_info[enum_entry] = { 'VkType': item }
720 # We'll want lists of the dispatchable and non dispatchable handles below with access to the same info
Mike Schuchardtf8690262019-07-11 10:08:33 -0700721 if self.handle_types.IsNonDispatchable(item):
John Zulauf2c2ccd42019-04-05 13:13:13 -0600722 non_dispatchable[item] = enum_entry
723 else:
724 dispatchable[item] = enum_entry
725
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600726 object_types_header += ' kVulkanObjectTypeMax = %d,\n' % enum_num
John Zulaufd7435c62018-03-16 11:52:57 -0600727 object_types_header += ' // Aliases for backwards compatibilty of "promoted" types\n'
728 for (name, alias) in self.object_type_aliases:
729 fixup_name = name[2:]
730 object_types_header += ' kVulkanObjectType{} = {},\n'.format(fixup_name, enum_entry_map[alias])
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600731 object_types_header += '} VulkanObjectType;\n\n'
732
733 # Output name string helper
734 object_types_header += '// Array of object name strings for OBJECT_TYPE enum conversion\n'
Mark Lobodzinski8eb37422017-04-18 14:22:10 -0600735 object_types_header += 'static const char * const object_string[kVulkanObjectTypeMax] = {\n'
locke-lunargb4c57852019-06-14 23:20:05 -0600736 object_types_header += ' "VkNonDispatchableHandle",\n'
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600737 for item in self.object_types:
locke-lunargb4c57852019-06-14 23:20:05 -0600738 object_types_header += ' "%s",\n' % item
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600739 object_types_header += '};\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600740
John Zulauf311a4892018-03-12 15:48:06 -0600741 # Key creation helper for map comprehensions that convert between k<Name> and VK<Name> symbols
742 def to_key(regex, raw_key): return re.search(regex, raw_key).group(1).lower().replace("_","")
743
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600744 # Output a conversion routine from the layer object definitions to the debug report definitions
John Zulauf311a4892018-03-12 15:48:06 -0600745 # As the VK_DEBUG_REPORT types are not being updated, specify UNKNOWN for unmatched types
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600746 object_types_header += '\n'
Mark Young1ded24b2017-05-30 14:53:50 -0600747 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 -0600748 object_types_header += 'const VkDebugReportObjectTypeEXT get_debug_report_enum[] = {\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700749 object_types_header += ' VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, // kVulkanObjectTypeUnknown\n'
Gabríel Arthúr Pétursson1a271d02018-03-18 17:34:01 +0000750
John Zulauf311a4892018-03-12 15:48:06 -0600751 dbg_re = '^VK_DEBUG_REPORT_OBJECT_TYPE_(.*)_EXT$'
752 dbg_map = {to_key(dbg_re, dbg) : dbg for dbg in self.debug_report_object_types}
753 dbg_default = 'VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT'
John Zulauf2c2ccd42019-04-05 13:13:13 -0600754
John Zulauf311a4892018-03-12 15:48:06 -0600755 for object_type in type_list:
756 vk_object_type = dbg_map.get(object_type.replace("kVulkanObjectType", "").lower(), dbg_default)
757 object_types_header += ' %s, // %s\n' % (vk_object_type, object_type)
John Zulauf2c2ccd42019-04-05 13:13:13 -0600758 object_type_info[object_type]['DbgType'] = vk_object_type
Mark Lobodzinskiecf0ae12017-04-13 08:36:18 -0600759 object_types_header += '};\n'
Mark Young1ded24b2017-05-30 14:53:50 -0600760
761 # Output a conversion routine from the layer object definitions to the core object type definitions
John Zulauf311a4892018-03-12 15:48:06 -0600762 # 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 -0600763 object_types_header += '\n'
764 object_types_header += '// Helper array to get Official Vulkan VkObjectType enum from the internal layers version\n'
765 object_types_header += 'const VkObjectType get_object_type_enum[] = {\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700766 object_types_header += ' VK_OBJECT_TYPE_UNKNOWN, // kVulkanObjectTypeUnknown\n'
John Zulauf311a4892018-03-12 15:48:06 -0600767
768 vko_re = '^VK_OBJECT_TYPE_(.*)'
769 vko_map = {to_key(vko_re, vko) : vko for vko in self.core_object_types}
Mark Young1ded24b2017-05-30 14:53:50 -0600770 for object_type in type_list:
John Zulauf311a4892018-03-12 15:48:06 -0600771 vk_object_type = vko_map[object_type.replace("kVulkanObjectType", "").lower()]
772 object_types_header += ' %s, // %s\n' % (vk_object_type, object_type)
John Zulauf2c2ccd42019-04-05 13:13:13 -0600773 object_type_info[object_type]['VkoType'] = vk_object_type
Mark Young1ded24b2017-05-30 14:53:50 -0600774 object_types_header += '};\n'
775
Mark Young6ba8abe2017-11-09 10:37:04 -0700776 # Create a function to convert from VkDebugReportObjectTypeEXT to VkObjectType
777 object_types_header += '\n'
778 object_types_header += '// Helper function to convert from VkDebugReportObjectTypeEXT to VkObjectType\n'
Mark Young8504ba62018-03-21 13:35:34 -0600779 object_types_header += 'static inline VkObjectType convertDebugReportObjectToCoreObject(VkDebugReportObjectTypeEXT debug_report_obj){\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700780 object_types_header += ' if (debug_report_obj == VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT) {\n'
781 object_types_header += ' return VK_OBJECT_TYPE_UNKNOWN;\n'
782 for core_object_type in self.core_object_types:
783 core_target_type = core_object_type.replace("VK_OBJECT_TYPE_", "").lower()
784 core_target_type = core_target_type.replace("_", "")
785 for dr_object_type in self.debug_report_object_types:
786 dr_target_type = dr_object_type.replace("VK_DEBUG_REPORT_OBJECT_TYPE_", "").lower()
787 dr_target_type = dr_target_type[:-4]
788 dr_target_type = dr_target_type.replace("_", "")
789 if core_target_type == dr_target_type:
790 object_types_header += ' } else if (debug_report_obj == %s) {\n' % dr_object_type
791 object_types_header += ' return %s;\n' % core_object_type
792 break
793 object_types_header += ' }\n'
794 object_types_header += ' return VK_OBJECT_TYPE_UNKNOWN;\n'
795 object_types_header += '}\n'
796
797 # Create a function to convert from VkObjectType to VkDebugReportObjectTypeEXT
798 object_types_header += '\n'
799 object_types_header += '// Helper function to convert from VkDebugReportObjectTypeEXT to VkObjectType\n'
Mark Young8504ba62018-03-21 13:35:34 -0600800 object_types_header += 'static inline VkDebugReportObjectTypeEXT convertCoreObjectToDebugReportObject(VkObjectType core_report_obj){\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700801 object_types_header += ' if (core_report_obj == VK_OBJECT_TYPE_UNKNOWN) {\n'
802 object_types_header += ' return VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT;\n'
803 for core_object_type in self.core_object_types:
804 core_target_type = core_object_type.replace("VK_OBJECT_TYPE_", "").lower()
805 core_target_type = core_target_type.replace("_", "")
806 for dr_object_type in self.debug_report_object_types:
807 dr_target_type = dr_object_type.replace("VK_DEBUG_REPORT_OBJECT_TYPE_", "").lower()
808 dr_target_type = dr_target_type[:-4]
809 dr_target_type = dr_target_type.replace("_", "")
810 if core_target_type == dr_target_type:
811 object_types_header += ' } else if (core_report_obj == %s) {\n' % core_object_type
812 object_types_header += ' return %s;\n' % dr_object_type
813 break
814 object_types_header += ' }\n'
815 object_types_header += ' return VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT;\n'
816 object_types_header += '}\n'
John Zulauf2c2ccd42019-04-05 13:13:13 -0600817
818 traits_format = Outdent('''
819 template <> struct VkHandleInfo<{vk_type}> {{
820 static const VulkanObjectType kVulkanObjectType = {obj_type};
821 static const VkDebugReportObjectTypeEXT kDebugReportObjectType = {dbg_type};
822 static const VkObjectType kVkObjectType = {vko_type};
823 static const char* Typename() {{
824 return "{vk_type}";
825 }}
826 }};
827 template <> struct VulkanObjectTypeInfo<{obj_type}> {{
828 typedef {vk_type} Type;
829 }};
830 ''')
831
832 object_types_header += Outdent('''
833 // Traits objects from each type statically map from Vk<handleType> to the various enums
834 template <typename VkType> struct VkHandleInfo {};
835 template <VulkanObjectType id> struct VulkanObjectTypeInfo {};
836
837 // The following line must match the vulkan_core.h condition guarding VK_DEFINE_NON_DISPATCHABLE_HANDLE
838 #if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__)) || defined(_M_X64) || defined(__ia64) || \
839 defined(_M_IA64) || defined(__aarch64__) || defined(__powerpc64__)
840 #define TYPESAFE_NONDISPATCHABLE_HANDLES
841 #else
842 VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkNonDispatchableHandle)
843 ''') +'\n'
844 object_types_header += traits_format.format(vk_type='VkNonDispatchableHandle', obj_type='kVulkanObjectTypeUnknown',
845 dbg_type='VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT',
846 vko_type='VK_OBJECT_TYPE_UNKNOWN') + '\n'
847 object_types_header += '#endif // VK_DEFINE_HANDLE logic duplication\n'
848
Mike Schuchardtaed5ac32019-06-21 09:03:31 -0700849 for vk_type, object_type in sorted(dispatchable.items()):
John Zulauf2c2ccd42019-04-05 13:13:13 -0600850 info = object_type_info[object_type]
851 object_types_header += traits_format.format(vk_type=vk_type, obj_type=object_type, dbg_type=info['DbgType'],
852 vko_type=info['VkoType'])
853 object_types_header += '#ifdef TYPESAFE_NONDISPATCHABLE_HANDLES\n'
Mike Schuchardtaed5ac32019-06-21 09:03:31 -0700854 for vk_type, object_type in sorted(non_dispatchable.items()):
John Zulauf2c2ccd42019-04-05 13:13:13 -0600855 info = object_type_info[object_type]
856 object_types_header += traits_format.format(vk_type=vk_type, obj_type=object_type, dbg_type=info['DbgType'],
857 vko_type=info['VkoType'])
858 object_types_header += '#endif // TYPESAFE_NONDISPATCHABLE_HANDLES\n'
859
860 object_types_header += Outdent('''
861 struct VulkanTypedHandle {
862 uint64_t handle;
863 VulkanObjectType type;
864 template <typename Handle>
John Zulauf4fea6622019-04-01 11:38:18 -0600865 VulkanTypedHandle(Handle handle_, VulkanObjectType type_) :
866 handle(CastToUint64(handle_)),
867 type(type_) {
868 #ifdef TYPESAFE_NONDISPATCHABLE_HANDLES
869 // For 32 bit it's not always safe to check for traits <-> type
870 // as all non-dispatchable handles have the same type-id and thus traits,
871 // but on 64 bit we can validate the passed type matches the passed handle
872 assert(type == VkHandleInfo<Handle>::kVulkanObjectType);
873 #endif // TYPESAFE_NONDISPATCHABLE_HANDLES
874 }
875 template <typename Handle>
876 Handle Cast() const {
877 #ifdef TYPESAFE_NONDISPATCHABLE_HANDLES
878 assert(type == VkHandleInfo<Handle>::kVulkanObjectType);
879 #endif // TYPESAFE_NONDISPATCHABLE_HANDLES
880 return CastFromUint64<Handle>(handle);
881 }
John Zulauf2c2ccd42019-04-05 13:13:13 -0600882 VulkanTypedHandle() :
883 handle(VK_NULL_HANDLE),
884 type(kVulkanObjectTypeUnknown) {}
885 }; ''') +'\n'
886
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600887 return object_types_header
888 #
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600889 # Generate pNext handling function
890 def build_pnext_chain_processing_func(self):
891 # Construct helper functions to build and free pNext extension chains
892 build_pnext_proc = '\n\n'
893 build_pnext_proc += 'void *SafePnextCopy(const void *pNext) {\n'
894 build_pnext_proc += ' void *cur_pnext = const_cast<void *>(pNext);\n'
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -0600895 build_pnext_proc += ' void *cur_ext_struct = NULL;\n'
896 build_pnext_proc += ' bool unrecognized_stype = true;\n\n'
897 build_pnext_proc += ' while (unrecognized_stype) {\n'
898 build_pnext_proc += ' unrecognized_stype = false;\n'
899 build_pnext_proc += ' if (cur_pnext == nullptr) {\n'
900 build_pnext_proc += ' return nullptr;\n'
901 build_pnext_proc += ' } else {\n'
902 build_pnext_proc += ' VkBaseOutStructure *header = reinterpret_cast<VkBaseOutStructure *>(cur_pnext);\n\n'
903 build_pnext_proc += ' switch (header->sType) {\n'
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600904
905 free_pnext_proc = '\n\n'
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -0600906 free_pnext_proc += '// Free a const pNext extension chain\n'
907 free_pnext_proc += 'void FreePnextChain(const void *head) {\n'
908 free_pnext_proc += ' FreePnextChain(const_cast<void *>(head));\n'
909 free_pnext_proc += '}\n\n'
910
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600911 free_pnext_proc += '// Free a pNext extension chain\n'
912 free_pnext_proc += 'void FreePnextChain(void *head) {\n'
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -0600913 free_pnext_proc += ' if (nullptr == head) return;\n'
914 free_pnext_proc += ' VkBaseOutStructure *header = reinterpret_cast<VkBaseOutStructure *>(head);\n\n'
915 free_pnext_proc += ' switch (header->sType) {\n';
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600916
917 for item in self.structextends_list:
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -0600918
919 struct = next((v for v in self.structMembers if v.name == item), None)
920 if struct is None:
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600921 continue
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -0600922
923 if struct.ifdef_protect is not None:
924 build_pnext_proc += '#ifdef %s\n' % struct.ifdef_protect
925 free_pnext_proc += '#ifdef %s\n' % struct.ifdef_protect
926 build_pnext_proc += ' case %s: {\n' % self.structTypes[item].value
927 build_pnext_proc += ' safe_%s *safe_struct = new safe_%s;\n' % (item, item)
928 build_pnext_proc += ' safe_struct->initialize(reinterpret_cast<const %s *>(cur_pnext));\n' % item
929 build_pnext_proc += ' cur_ext_struct = reinterpret_cast<void *>(safe_struct);\n'
930 build_pnext_proc += ' } break;\n'
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600931
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -0600932 free_pnext_proc += ' case %s:\n' % self.structTypes[item].value
933 free_pnext_proc += ' delete reinterpret_cast<safe_%s *>(header);\n' % item
934 free_pnext_proc += ' break;\n'
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600935
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -0600936 if struct.ifdef_protect is not None:
937 build_pnext_proc += '#endif // %s\n' % struct.ifdef_protect
938 free_pnext_proc += '#endif // %s\n' % struct.ifdef_protect
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600939 build_pnext_proc += '\n'
940 free_pnext_proc += '\n'
941
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -0600942 build_pnext_proc += ' default:\n'
943 build_pnext_proc += ' // Encountered an unknown sType -- skip (do not copy) this entry in the chain\n'
944 build_pnext_proc += ' unrecognized_stype = true;\n'
945 build_pnext_proc += ' cur_pnext = header->pNext;\n'
946 build_pnext_proc += ' break;\n'
947 build_pnext_proc += ' }\n'
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600948 build_pnext_proc += ' }\n'
949 build_pnext_proc += ' }\n'
950 build_pnext_proc += ' return cur_ext_struct;\n'
951 build_pnext_proc += '}\n\n'
952
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -0600953 free_pnext_proc += ' default:\n'
954 free_pnext_proc += ' // Do nothing -- skip unrecognized sTypes\n'
955 free_pnext_proc += ' break;\n'
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600956 free_pnext_proc += ' }\n'
957 free_pnext_proc += '}\n'
958
959 pnext_procs = build_pnext_proc + free_pnext_proc
960 return pnext_procs
961 #
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700962 # Determine if a structure needs a safe_struct helper function
963 # That is, it has an sType or one of its members is a pointer
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700964 def NeedSafeStruct(self, structure):
Mark Lobodzinskib6cc5412019-07-19 09:56:58 -0600965 if 'VkBase' in structure.name:
966 return False
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700967 if 'sType' == structure.name:
968 return True
969 for member in structure.members:
970 if member.ispointer == True:
971 return True
972 return False
973 #
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700974 # Combine safe struct helper source file preamble with body text and return
975 def GenerateSafeStructHelperSource(self):
976 safe_struct_helper_source = '\n'
977 safe_struct_helper_source += '#include "vk_safe_struct.h"\n'
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600978 safe_struct_helper_source += '#include <assert.h>\n'
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700979 safe_struct_helper_source += '#include <string.h>\n'
980 safe_struct_helper_source += '\n'
981 safe_struct_helper_source += self.GenerateSafeStructSource()
Mark Lobodzinskib836ac92019-07-18 16:14:43 -0600982 safe_struct_helper_source += self.build_pnext_chain_processing_func()
983
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700984 return safe_struct_helper_source
985 #
986 # safe_struct source -- create bodies of safe struct helper functions
987 def GenerateSafeStructSource(self):
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700988 safe_struct_body = []
Mark Lobodzinski560729b2017-03-06 08:59:14 -0700989 wsi_structs = ['VkXlibSurfaceCreateInfoKHR',
990 'VkXcbSurfaceCreateInfoKHR',
991 'VkWaylandSurfaceCreateInfoKHR',
Mark Lobodzinski560729b2017-03-06 08:59:14 -0700992 'VkAndroidSurfaceCreateInfoKHR',
993 'VkWin32SurfaceCreateInfoKHR'
994 ]
Courtney Goeltzenleuchterdb6c2332018-06-28 14:32:55 -0600995
996 # For abstract types just want to save the pointer away
997 # since we cannot make a copy.
998 abstract_types = ['AHardwareBuffer',
999 'ANativeWindow',
1000 ]
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001001 for item in self.structMembers:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001002 if self.NeedSafeStruct(item) == False:
1003 continue
Mark Lobodzinski560729b2017-03-06 08:59:14 -07001004 if item.name in wsi_structs:
1005 continue
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +01001006 if item.ifdef_protect is not None:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001007 safe_struct_body.append("#ifdef %s\n" % item.ifdef_protect)
1008 ss_name = "safe_%s" % item.name
1009 init_list = '' # list of members in struct constructor initializer
1010 default_init_list = '' # Default constructor just inits ptrs to nullptr in initializer
1011 init_func_txt = '' # Txt for initialize() function that takes struct ptr and inits members
1012 construct_txt = '' # Body of constuctor as well as body of initialize() func following init_func_txt
1013 destruct_txt = ''
Petr Krause91f7a12017-12-14 20:57:36 +01001014
1015 custom_construct_txt = {
1016 # VkWriteDescriptorSet is special case because pointers may be non-null but ignored
1017 'VkWriteDescriptorSet' :
1018 ' switch (descriptorType) {\n'
1019 ' case VK_DESCRIPTOR_TYPE_SAMPLER:\n'
1020 ' case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:\n'
1021 ' case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:\n'
1022 ' case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:\n'
1023 ' case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:\n'
1024 ' if (descriptorCount && in_struct->pImageInfo) {\n'
1025 ' pImageInfo = new VkDescriptorImageInfo[descriptorCount];\n'
1026 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
1027 ' pImageInfo[i] = in_struct->pImageInfo[i];\n'
1028 ' }\n'
1029 ' }\n'
1030 ' break;\n'
1031 ' case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:\n'
1032 ' case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:\n'
1033 ' case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:\n'
1034 ' case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:\n'
1035 ' if (descriptorCount && in_struct->pBufferInfo) {\n'
1036 ' pBufferInfo = new VkDescriptorBufferInfo[descriptorCount];\n'
1037 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
1038 ' pBufferInfo[i] = in_struct->pBufferInfo[i];\n'
1039 ' }\n'
1040 ' }\n'
1041 ' break;\n'
1042 ' case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:\n'
1043 ' case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:\n'
1044 ' if (descriptorCount && in_struct->pTexelBufferView) {\n'
1045 ' pTexelBufferView = new VkBufferView[descriptorCount];\n'
1046 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
1047 ' pTexelBufferView[i] = in_struct->pTexelBufferView[i];\n'
1048 ' }\n'
1049 ' }\n'
1050 ' break;\n'
1051 ' default:\n'
1052 ' break;\n'
1053 ' }\n',
Petr Kraus42f6f8d2017-12-17 17:37:33 +01001054 'VkShaderModuleCreateInfo' :
Petr Krause91f7a12017-12-14 20:57:36 +01001055 ' if (in_struct->pCode) {\n'
1056 ' pCode = reinterpret_cast<uint32_t *>(new uint8_t[codeSize]);\n'
1057 ' memcpy((void *)pCode, (void *)in_struct->pCode, codeSize);\n'
1058 ' }\n',
1059 # VkGraphicsPipelineCreateInfo is special case because its pointers may be non-null but ignored
1060 'VkGraphicsPipelineCreateInfo' :
1061 ' if (stageCount && in_struct->pStages) {\n'
1062 ' pStages = new safe_VkPipelineShaderStageCreateInfo[stageCount];\n'
1063 ' for (uint32_t i=0; i<stageCount; ++i) {\n'
1064 ' pStages[i].initialize(&in_struct->pStages[i]);\n'
1065 ' }\n'
1066 ' }\n'
1067 ' if (in_struct->pVertexInputState)\n'
1068 ' pVertexInputState = new safe_VkPipelineVertexInputStateCreateInfo(in_struct->pVertexInputState);\n'
1069 ' else\n'
1070 ' pVertexInputState = NULL;\n'
1071 ' if (in_struct->pInputAssemblyState)\n'
1072 ' pInputAssemblyState = new safe_VkPipelineInputAssemblyStateCreateInfo(in_struct->pInputAssemblyState);\n'
1073 ' else\n'
1074 ' pInputAssemblyState = NULL;\n'
1075 ' bool has_tessellation_stage = false;\n'
1076 ' if (stageCount && pStages)\n'
1077 ' for (uint32_t i=0; i<stageCount && !has_tessellation_stage; ++i)\n'
1078 ' if (pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)\n'
1079 ' has_tessellation_stage = true;\n'
1080 ' if (in_struct->pTessellationState && has_tessellation_stage)\n'
1081 ' pTessellationState = new safe_VkPipelineTessellationStateCreateInfo(in_struct->pTessellationState);\n'
1082 ' else\n'
1083 ' pTessellationState = NULL; // original pTessellationState pointer ignored\n'
1084 ' bool has_rasterization = in_struct->pRasterizationState ? !in_struct->pRasterizationState->rasterizerDiscardEnable : false;\n'
1085 ' if (in_struct->pViewportState && has_rasterization) {\n'
1086 ' bool is_dynamic_viewports = false;\n'
1087 ' bool is_dynamic_scissors = false;\n'
1088 ' if (in_struct->pDynamicState && in_struct->pDynamicState->pDynamicStates) {\n'
1089 ' for (uint32_t i = 0; i < in_struct->pDynamicState->dynamicStateCount && !is_dynamic_viewports; ++i)\n'
1090 ' if (in_struct->pDynamicState->pDynamicStates[i] == VK_DYNAMIC_STATE_VIEWPORT)\n'
1091 ' is_dynamic_viewports = true;\n'
1092 ' for (uint32_t i = 0; i < in_struct->pDynamicState->dynamicStateCount && !is_dynamic_scissors; ++i)\n'
1093 ' if (in_struct->pDynamicState->pDynamicStates[i] == VK_DYNAMIC_STATE_SCISSOR)\n'
1094 ' is_dynamic_scissors = true;\n'
1095 ' }\n'
1096 ' pViewportState = new safe_VkPipelineViewportStateCreateInfo(in_struct->pViewportState, is_dynamic_viewports, is_dynamic_scissors);\n'
1097 ' } else\n'
1098 ' pViewportState = NULL; // original pViewportState pointer ignored\n'
1099 ' if (in_struct->pRasterizationState)\n'
1100 ' pRasterizationState = new safe_VkPipelineRasterizationStateCreateInfo(in_struct->pRasterizationState);\n'
1101 ' else\n'
1102 ' pRasterizationState = NULL;\n'
1103 ' if (in_struct->pMultisampleState && has_rasterization)\n'
1104 ' pMultisampleState = new safe_VkPipelineMultisampleStateCreateInfo(in_struct->pMultisampleState);\n'
1105 ' else\n'
1106 ' pMultisampleState = NULL; // original pMultisampleState pointer ignored\n'
1107 ' // needs a tracked subpass state uses_depthstencil_attachment\n'
1108 ' if (in_struct->pDepthStencilState && has_rasterization && uses_depthstencil_attachment)\n'
1109 ' pDepthStencilState = new safe_VkPipelineDepthStencilStateCreateInfo(in_struct->pDepthStencilState);\n'
1110 ' else\n'
1111 ' pDepthStencilState = NULL; // original pDepthStencilState pointer ignored\n'
1112 ' // needs a tracked subpass state usesColorAttachment\n'
1113 ' if (in_struct->pColorBlendState && has_rasterization && uses_color_attachment)\n'
1114 ' pColorBlendState = new safe_VkPipelineColorBlendStateCreateInfo(in_struct->pColorBlendState);\n'
1115 ' else\n'
1116 ' pColorBlendState = NULL; // original pColorBlendState pointer ignored\n'
1117 ' if (in_struct->pDynamicState)\n'
1118 ' pDynamicState = new safe_VkPipelineDynamicStateCreateInfo(in_struct->pDynamicState);\n'
1119 ' else\n'
1120 ' pDynamicState = NULL;\n',
1121 # VkPipelineViewportStateCreateInfo is special case because its pointers may be non-null but ignored
1122 'VkPipelineViewportStateCreateInfo' :
1123 ' if (in_struct->pViewports && !is_dynamic_viewports) {\n'
1124 ' pViewports = new VkViewport[in_struct->viewportCount];\n'
1125 ' memcpy ((void *)pViewports, (void *)in_struct->pViewports, sizeof(VkViewport)*in_struct->viewportCount);\n'
1126 ' }\n'
1127 ' else\n'
1128 ' pViewports = NULL;\n'
1129 ' if (in_struct->pScissors && !is_dynamic_scissors) {\n'
1130 ' pScissors = new VkRect2D[in_struct->scissorCount];\n'
1131 ' memcpy ((void *)pScissors, (void *)in_struct->pScissors, sizeof(VkRect2D)*in_struct->scissorCount);\n'
1132 ' }\n'
1133 ' else\n'
1134 ' pScissors = NULL;\n',
Petr Kraus42f6f8d2017-12-17 17:37:33 +01001135 # VkDescriptorSetLayoutBinding is special case because its pImmutableSamplers pointer may be non-null but ignored
1136 'VkDescriptorSetLayoutBinding' :
1137 ' const bool sampler_type = in_struct->descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER || in_struct->descriptorType == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;\n'
1138 ' if (descriptorCount && in_struct->pImmutableSamplers && sampler_type) {\n'
1139 ' pImmutableSamplers = new VkSampler[descriptorCount];\n'
1140 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
1141 ' pImmutableSamplers[i] = in_struct->pImmutableSamplers[i];\n'
1142 ' }\n'
1143 ' }\n',
Petr Krause91f7a12017-12-14 20:57:36 +01001144 }
1145
1146 custom_copy_txt = {
1147 # VkGraphicsPipelineCreateInfo is special case because it has custom construct parameters
1148 'VkGraphicsPipelineCreateInfo' :
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001149 ' pNext = SafePnextCopy(src.pNext);\n'
Petr Krause91f7a12017-12-14 20:57:36 +01001150 ' if (stageCount && src.pStages) {\n'
1151 ' pStages = new safe_VkPipelineShaderStageCreateInfo[stageCount];\n'
1152 ' for (uint32_t i=0; i<stageCount; ++i) {\n'
1153 ' pStages[i].initialize(&src.pStages[i]);\n'
1154 ' }\n'
1155 ' }\n'
1156 ' if (src.pVertexInputState)\n'
1157 ' pVertexInputState = new safe_VkPipelineVertexInputStateCreateInfo(*src.pVertexInputState);\n'
1158 ' else\n'
1159 ' pVertexInputState = NULL;\n'
1160 ' if (src.pInputAssemblyState)\n'
1161 ' pInputAssemblyState = new safe_VkPipelineInputAssemblyStateCreateInfo(*src.pInputAssemblyState);\n'
1162 ' else\n'
1163 ' pInputAssemblyState = NULL;\n'
1164 ' bool has_tessellation_stage = false;\n'
1165 ' if (stageCount && pStages)\n'
1166 ' for (uint32_t i=0; i<stageCount && !has_tessellation_stage; ++i)\n'
1167 ' if (pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)\n'
1168 ' has_tessellation_stage = true;\n'
1169 ' if (src.pTessellationState && has_tessellation_stage)\n'
1170 ' pTessellationState = new safe_VkPipelineTessellationStateCreateInfo(*src.pTessellationState);\n'
1171 ' else\n'
1172 ' pTessellationState = NULL; // original pTessellationState pointer ignored\n'
1173 ' bool has_rasterization = src.pRasterizationState ? !src.pRasterizationState->rasterizerDiscardEnable : false;\n'
1174 ' if (src.pViewportState && has_rasterization) {\n'
1175 ' pViewportState = new safe_VkPipelineViewportStateCreateInfo(*src.pViewportState);\n'
1176 ' } else\n'
1177 ' pViewportState = NULL; // original pViewportState pointer ignored\n'
1178 ' if (src.pRasterizationState)\n'
1179 ' pRasterizationState = new safe_VkPipelineRasterizationStateCreateInfo(*src.pRasterizationState);\n'
1180 ' else\n'
1181 ' pRasterizationState = NULL;\n'
1182 ' if (src.pMultisampleState && has_rasterization)\n'
1183 ' pMultisampleState = new safe_VkPipelineMultisampleStateCreateInfo(*src.pMultisampleState);\n'
1184 ' else\n'
1185 ' pMultisampleState = NULL; // original pMultisampleState pointer ignored\n'
1186 ' if (src.pDepthStencilState && has_rasterization)\n'
1187 ' pDepthStencilState = new safe_VkPipelineDepthStencilStateCreateInfo(*src.pDepthStencilState);\n'
1188 ' else\n'
1189 ' pDepthStencilState = NULL; // original pDepthStencilState pointer ignored\n'
1190 ' if (src.pColorBlendState && has_rasterization)\n'
1191 ' pColorBlendState = new safe_VkPipelineColorBlendStateCreateInfo(*src.pColorBlendState);\n'
1192 ' else\n'
1193 ' pColorBlendState = NULL; // original pColorBlendState pointer ignored\n'
1194 ' if (src.pDynamicState)\n'
1195 ' pDynamicState = new safe_VkPipelineDynamicStateCreateInfo(*src.pDynamicState);\n'
1196 ' else\n'
1197 ' pDynamicState = NULL;\n',
1198 # VkPipelineViewportStateCreateInfo is special case because it has custom construct parameters
1199 'VkPipelineViewportStateCreateInfo' :
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001200 ' pNext = SafePnextCopy(src.pNext);\n'
Petr Krause91f7a12017-12-14 20:57:36 +01001201 ' if (src.pViewports) {\n'
1202 ' pViewports = new VkViewport[src.viewportCount];\n'
1203 ' memcpy ((void *)pViewports, (void *)src.pViewports, sizeof(VkViewport)*src.viewportCount);\n'
1204 ' }\n'
1205 ' else\n'
1206 ' pViewports = NULL;\n'
1207 ' if (src.pScissors) {\n'
1208 ' pScissors = new VkRect2D[src.scissorCount];\n'
1209 ' memcpy ((void *)pScissors, (void *)src.pScissors, sizeof(VkRect2D)*src.scissorCount);\n'
1210 ' }\n'
1211 ' else\n'
1212 ' pScissors = NULL;\n',
1213 }
1214
Mike Schuchardt81485762017-09-04 11:38:42 -06001215 custom_destruct_txt = {'VkShaderModuleCreateInfo' :
1216 ' if (pCode)\n'
1217 ' delete[] reinterpret_cast<const uint8_t *>(pCode);\n' }
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001218
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001219 copy_pnext = ''
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001220 for member in item.members:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001221 m_type = member.type
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001222 if member.name == 'pNext':
1223 copy_pnext = ' pNext = SafePnextCopy(in_struct->pNext);\n'
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001224 if member.type in self.structNames:
1225 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
1226 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
1227 m_type = 'safe_%s' % member.type
1228 if member.ispointer and 'safe_' not in m_type and self.TypeContainsObjectHandle(member.type, False) == False:
1229 # 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 -07001230 if m_type in ['void', 'char']:
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001231 if member.name != 'pNext':
1232 # For these exceptions just copy initial value over for now
1233 init_list += '\n %s(in_struct->%s),' % (member.name, member.name)
1234 init_func_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001235 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001236 default_init_list += '\n %s(nullptr),' % (member.name)
1237 init_list += '\n %s(nullptr),' % (member.name)
Courtney Goeltzenleuchterdb6c2332018-06-28 14:32:55 -06001238 if m_type in abstract_types:
1239 construct_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
1240 else:
1241 init_func_txt += ' %s = nullptr;\n' % (member.name)
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001242 if not member.isstaticarray and (member.len is None or '/' in member.len):
1243 construct_txt += ' if (in_struct->%s) {\n' % member.name
1244 construct_txt += ' %s = new %s(*in_struct->%s);\n' % (member.name, m_type, member.name)
1245 construct_txt += ' }\n'
1246 destruct_txt += ' if (%s)\n' % member.name
1247 destruct_txt += ' delete %s;\n' % member.name
1248 else:
1249 construct_txt += ' if (in_struct->%s) {\n' % member.name
1250 construct_txt += ' %s = new %s[in_struct->%s];\n' % (member.name, m_type, member.len)
1251 construct_txt += ' memcpy ((void *)%s, (void *)in_struct->%s, sizeof(%s)*in_struct->%s);\n' % (member.name, member.name, m_type, member.len)
1252 construct_txt += ' }\n'
1253 destruct_txt += ' if (%s)\n' % member.name
1254 destruct_txt += ' delete[] %s;\n' % member.name
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001255 elif member.isstaticarray or member.len is not None:
1256 if member.len is None:
1257 # Extract length of static array by grabbing val between []
1258 static_array_size = re.match(r"[^[]*\[([^]]*)\]", member.cdecl)
1259 construct_txt += ' for (uint32_t i=0; i<%s; ++i) {\n' % static_array_size.group(1)
1260 construct_txt += ' %s[i] = in_struct->%s[i];\n' % (member.name, member.name)
1261 construct_txt += ' }\n'
1262 else:
1263 # Init array ptr to NULL
1264 default_init_list += '\n %s(nullptr),' % member.name
1265 init_list += '\n %s(nullptr),' % member.name
1266 init_func_txt += ' %s = nullptr;\n' % member.name
1267 array_element = 'in_struct->%s[i]' % member.name
1268 if member.type in self.structNames:
1269 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
1270 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
1271 array_element = '%s(&in_struct->safe_%s[i])' % (member.type, member.name)
1272 construct_txt += ' if (%s && in_struct->%s) {\n' % (member.len, member.name)
1273 construct_txt += ' %s = new %s[%s];\n' % (member.name, m_type, member.len)
1274 destruct_txt += ' if (%s)\n' % member.name
1275 destruct_txt += ' delete[] %s;\n' % member.name
1276 construct_txt += ' for (uint32_t i=0; i<%s; ++i) {\n' % (member.len)
1277 if 'safe_' in m_type:
1278 construct_txt += ' %s[i].initialize(&in_struct->%s[i]);\n' % (member.name, member.name)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001279 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001280 construct_txt += ' %s[i] = %s;\n' % (member.name, array_element)
1281 construct_txt += ' }\n'
1282 construct_txt += ' }\n'
1283 elif member.ispointer == True:
1284 construct_txt += ' if (in_struct->%s)\n' % member.name
1285 construct_txt += ' %s = new %s(in_struct->%s);\n' % (member.name, m_type, member.name)
1286 construct_txt += ' else\n'
1287 construct_txt += ' %s = NULL;\n' % member.name
1288 destruct_txt += ' if (%s)\n' % member.name
1289 destruct_txt += ' delete %s;\n' % member.name
1290 elif 'safe_' in m_type:
1291 init_list += '\n %s(&in_struct->%s),' % (member.name, member.name)
1292 init_func_txt += ' %s.initialize(&in_struct->%s);\n' % (member.name, member.name)
1293 else:
1294 init_list += '\n %s(in_struct->%s),' % (member.name, member.name)
1295 init_func_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
1296 if '' != init_list:
1297 init_list = init_list[:-1] # hack off final comma
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001298
1299
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001300 if item.name in custom_construct_txt:
1301 construct_txt = custom_construct_txt[item.name]
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001302
1303 construct_txt = copy_pnext + construct_txt
1304
Mike Schuchardt81485762017-09-04 11:38:42 -06001305 if item.name in custom_destruct_txt:
1306 destruct_txt = custom_destruct_txt[item.name]
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001307
1308 if copy_pnext:
1309 destruct_txt += ' if (pNext)\n FreePnextChain(pNext);\n'
1310
Petr Krause91f7a12017-12-14 20:57:36 +01001311 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 -07001312 if '' != default_init_list:
1313 default_init_list = " :%s" % (default_init_list[:-1])
1314 safe_struct_body.append("\n%s::%s()%s\n{}" % (ss_name, ss_name, default_init_list))
1315 # Create slight variation of init and construct txt for copy constructor that takes a src object reference vs. struct ptr
1316 copy_construct_init = init_func_txt.replace('in_struct->', 'src.')
Mark Lobodzinski1d70bce2019-07-18 17:30:54 -06001317 copy_construct_txt = construct_txt.replace(' (in_struct->', ' (src.') # Exclude 'if' blocks from next line
1318 copy_construct_txt = construct_txt.replace(' (in_struct->', ' (src.') # Exclude 'if' blocks from next line
1319 copy_construct_txt = re.sub('(new \\w+)\\(in_struct->', '\\1(*src.', construct_txt) # Pass object to copy constructors
1320 copy_construct_txt = copy_construct_txt.replace('in_struct->', 'src.') # Modify remaining struct refs for src object
Petr Krause91f7a12017-12-14 20:57:36 +01001321 if item.name in custom_copy_txt:
1322 copy_construct_txt = custom_copy_txt[item.name]
Chris Forbesfb633832017-10-03 18:11:54 -07001323 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 -06001324 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 -07001325 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 -07001326 safe_struct_body.append("\n%s::~%s()\n{\n%s}" % (ss_name, ss_name, destruct_txt))
Petr Krause91f7a12017-12-14 20:57:36 +01001327 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 -07001328 # Copy initializer uses same txt as copy constructor but has a ptr and not a reference
1329 init_copy = copy_construct_init.replace('src.', 'src->')
1330 init_construct = copy_construct_txt.replace('src.', 'src->')
Mark Lobodzinski5cd08512017-09-12 09:50:25 -06001331 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 +01001332 if item.ifdef_protect is not None:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001333 safe_struct_body.append("#endif // %s\n" % item.ifdef_protect)
1334 return "\n".join(safe_struct_body)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001335 #
John Zulaufde972ac2017-10-26 12:07:05 -06001336 # Generate the type map
1337 def GenerateTypeMapHelperHeader(self):
1338 prefix = 'Lvl'
1339 fprefix = 'lvl_'
1340 typemap = prefix + 'TypeMap'
1341 idmap = prefix + 'STypeMap'
John Zulaufde972ac2017-10-26 12:07:05 -06001342 type_member = 'Type'
1343 id_member = 'kSType'
Mike Schuchardt97662b02017-12-06 13:31:29 -07001344 id_decl = 'static const VkStructureType '
Locke6b6b7382019-04-16 15:08:49 -06001345 generic_header = 'VkBaseOutStructure'
John Zulaufde972ac2017-10-26 12:07:05 -06001346 typename_func = fprefix + 'typename'
1347 idname_func = fprefix + 'stype_name'
1348 find_func = fprefix + 'find_in_chain'
John Zulauf65ac9d52018-01-23 11:20:50 -07001349 init_func = fprefix + 'init_struct'
John Zulaufde972ac2017-10-26 12:07:05 -06001350
1351 explanatory_comment = '\n'.join((
1352 '// These empty generic templates are specialized for each type with sType',
1353 '// members and for each sType -- providing a two way map between structure',
Mike Schuchardt97662b02017-12-06 13:31:29 -07001354 '// types and sTypes'))
John Zulaufde972ac2017-10-26 12:07:05 -06001355
1356 empty_typemap = 'template <typename T> struct ' + typemap + ' {};'
1357 typemap_format = 'template <> struct {template}<{typename}> {{\n'
John Zulaufde972ac2017-10-26 12:07:05 -06001358 typemap_format += ' {id_decl}{id_member} = {id_value};\n'
1359 typemap_format += '}};\n'
1360
1361 empty_idmap = 'template <VkStructureType id> struct ' + idmap + ' {};'
1362 idmap_format = ''.join((
1363 'template <> struct {template}<{id_value}> {{\n',
1364 ' typedef {typename} {typedef};\n',
John Zulaufde972ac2017-10-26 12:07:05 -06001365 '}};\n'))
1366
1367 # Define the utilities (here so any renaming stays consistent), if this grows large, refactor to a fixed .h file
1368 utilities_format = '\n'.join((
John Zulaufde972ac2017-10-26 12:07:05 -06001369 '// Find an entry of the given type in the pNext chain',
1370 'template <typename T> const T *{find_func}(const void *next) {{',
1371 ' const {header} *current = reinterpret_cast<const {header} *>(next);',
1372 ' const T *found = nullptr;',
1373 ' while (current) {{',
1374 ' if ({type_map}<T>::{id_member} == current->sType) {{',
1375 ' found = reinterpret_cast<const T*>(current);',
1376 ' current = nullptr;',
1377 ' }} else {{',
1378 ' current = current->pNext;',
1379 ' }}',
1380 ' }}',
1381 ' return found;',
1382 '}}',
John Zulauf65ac9d52018-01-23 11:20:50 -07001383 '',
1384 '// Init the header of an sType struct with pNext',
1385 'template <typename T> T {init_func}(void *p_next) {{',
1386 ' T out = {{}};',
1387 ' out.sType = {type_map}<T>::kSType;',
1388 ' out.pNext = p_next;',
1389 ' return out;',
1390 '}}',
1391 '',
1392 '// Init the header of an sType struct',
1393 'template <typename T> T {init_func}() {{',
1394 ' T out = {{}};',
1395 ' out.sType = {type_map}<T>::kSType;',
1396 ' return out;',
1397 '}}',
1398
Mike Schuchardt97662b02017-12-06 13:31:29 -07001399 ''))
John Zulaufde972ac2017-10-26 12:07:05 -06001400
1401 code = []
John Zulauf65ac9d52018-01-23 11:20:50 -07001402
1403 # Generate header
John Zulaufde972ac2017-10-26 12:07:05 -06001404 code.append('\n'.join((
1405 '#pragma once',
1406 '#include <vulkan/vulkan.h>\n',
1407 explanatory_comment, '',
1408 empty_idmap,
John Zulauf65ac9d52018-01-23 11:20:50 -07001409 empty_typemap, '')))
John Zulaufde972ac2017-10-26 12:07:05 -06001410
1411 # Generate the specializations for each type and stype
John Zulaufde972ac2017-10-26 12:07:05 -06001412 for item in self.structMembers:
1413 typename = item.name
1414 info = self.structTypes.get(typename)
1415 if not info:
1416 continue
1417
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +01001418 if item.ifdef_protect is not None:
John Zulaufde972ac2017-10-26 12:07:05 -06001419 code.append('#ifdef %s' % item.ifdef_protect)
1420
1421 code.append('// Map type {} to id {}'.format(typename, info.value))
1422 code.append(typemap_format.format(template=typemap, typename=typename, id_value=info.value,
Mike Schuchardt97662b02017-12-06 13:31:29 -07001423 id_decl=id_decl, id_member=id_member))
1424 code.append(idmap_format.format(template=idmap, typename=typename, id_value=info.value, typedef=type_member))
John Zulaufde972ac2017-10-26 12:07:05 -06001425
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +01001426 if item.ifdef_protect is not None:
John Zulaufde972ac2017-10-26 12:07:05 -06001427 code.append('#endif // %s' % item.ifdef_protect)
1428
John Zulauf65ac9d52018-01-23 11:20:50 -07001429 # Generate utilities for all types
1430 code.append('\n'.join((
1431 utilities_format.format(id_member=id_member, id_map=idmap, type_map=typemap,
1432 type_member=type_member, header=generic_header, typename_func=typename_func, idname_func=idname_func,
1433 find_func=find_func, init_func=init_func), ''
1434 )))
1435
John Zulaufde972ac2017-10-26 12:07:05 -06001436 return "\n".join(code)
1437
1438 #
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -07001439 # Create a helper file and return it as a string
1440 def OutputDestFile(self):
Mark Lobodzinski46d388f2016-12-28 10:46:26 -07001441 if self.helper_file_type == 'enum_string_header':
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -07001442 return self.GenerateEnumStringHelperHeader()
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001443 elif self.helper_file_type == 'safe_struct_header':
1444 return self.GenerateSafeStructHelperHeader()
1445 elif self.helper_file_type == 'safe_struct_source':
1446 return self.GenerateSafeStructHelperSource()
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -06001447 elif self.helper_file_type == 'object_types_header':
1448 return self.GenerateObjectTypesHelperHeader()
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -06001449 elif self.helper_file_type == 'extension_helper_header':
1450 return self.GenerateExtensionHelperHeader()
John Zulaufde972ac2017-10-26 12:07:05 -06001451 elif self.helper_file_type == 'typemap_helper_header':
1452 return self.GenerateTypeMapHelperHeader()
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -07001453 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001454 return 'Bad Helper File Generator Option %s' % self.helper_file_type