blob: e9d5f22dbbb2e97ab8a975160256ffd8f0f47857 [file] [log] [blame]
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -07001#!/usr/bin/python3 -i
2#
Mark Lobodzinski733f7f42017-01-10 11:42:22 -07003# Copyright (c) 2015-2017 The Khronos Group Inc.
4# Copyright (c) 2015-2017 Valve Corporation
5# Copyright (c) 2015-2017 LunarG, Inc.
6# Copyright (c) 2015-2017 Google Inc.
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -07007#
8# Licensed under the Apache License, Version 2.0 (the "License");
9# you may not use this file except in compliance with the License.
10# You may obtain a copy of the License at
11#
12# http://www.apache.org/licenses/LICENSE-2.0
13#
14# Unless required by applicable law or agreed to in writing, software
15# distributed under the License is distributed on an "AS IS" BASIS,
16# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17# See the License for the specific language governing permissions and
18# limitations under the License.
19#
20# Author: Mark Lobodzinski <mark@lunarg.com>
Mark Lobodzinskic67efd02017-01-04 09:16:00 -070021# Author: Tobin Ehlis <tobine@google.com>
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070022
23import os,re,sys
24import xml.etree.ElementTree as etree
25from generator import *
26from collections import namedtuple
Mark Lobodzinski62f71562017-10-24 13:41:18 -060027from common_codegen import *
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070028
29#
30# HelperFileOutputGeneratorOptions - subclass of GeneratorOptions.
31class HelperFileOutputGeneratorOptions(GeneratorOptions):
32 def __init__(self,
33 filename = None,
34 directory = '.',
35 apiname = None,
36 profile = None,
37 versions = '.*',
38 emitversions = '.*',
39 defaultExtensions = None,
40 addExtensions = None,
41 removeExtensions = None,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060042 emitExtensions = None,
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070043 sortProcedure = regSortFeatures,
44 prefixText = "",
45 genFuncPointers = True,
46 protectFile = True,
47 protectFeature = True,
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070048 apicall = '',
49 apientry = '',
50 apientryp = '',
51 alignFuncParam = 0,
52 library_name = '',
Mark Lobodzinski62f71562017-10-24 13:41:18 -060053 expandEnumerants = True,
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070054 helper_file_type = ''):
55 GeneratorOptions.__init__(self, filename, directory, apiname, profile,
56 versions, emitversions, defaultExtensions,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060057 addExtensions, removeExtensions, emitExtensions, sortProcedure)
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070058 self.prefixText = prefixText
59 self.genFuncPointers = genFuncPointers
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070060 self.protectFile = protectFile
61 self.protectFeature = protectFeature
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070062 self.apicall = apicall
63 self.apientry = apientry
64 self.apientryp = apientryp
65 self.alignFuncParam = alignFuncParam
66 self.library_name = library_name
67 self.helper_file_type = helper_file_type
68#
Mark Lobodzinski46d388f2016-12-28 10:46:26 -070069# HelperFileOutputGenerator - subclass of OutputGenerator. Outputs Vulkan helper files
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070070class HelperFileOutputGenerator(OutputGenerator):
Mark Lobodzinskia3cc3612017-01-03 13:25:10 -070071 """Generate helper file based on XML element attributes"""
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -070072 def __init__(self,
73 errFile = sys.stderr,
74 warnFile = sys.stderr,
75 diagFile = sys.stdout):
76 OutputGenerator.__init__(self, errFile, warnFile, diagFile)
77 # Internal state - accumulators for different inner block text
Mark Lobodzinski5380d132016-12-28 14:45:34 -070078 self.enum_output = '' # string built up of enum string routines
Mark Lobodzinski46d388f2016-12-28 10:46:26 -070079 # Internal state - accumulators for different inner block text
Mark Lobodzinski46d388f2016-12-28 10:46:26 -070080 self.structNames = [] # List of Vulkan struct typenames
81 self.structTypes = dict() # Map of Vulkan struct typename to required VkStructureType
Mark Lobodzinski46d388f2016-12-28 10:46:26 -070082 self.structMembers = [] # List of StructMemberData records for all Vulkan structs
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -060083 self.object_types = [] # List of all handle types
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -060084 self.debug_report_object_types = [] # Handy copy of debug_report_object_type enum data
Mark Young1ded24b2017-05-30 14:53:50 -060085 self.core_object_types = [] # Handy copy of core_object_type enum data
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -060086 self.device_extension_info = dict() # Dict of device extension name defines and ifdef values
87 self.instance_extension_info = dict() # Dict of instance extension name defines and ifdef values
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -060088
Mark Lobodzinski46d388f2016-12-28 10:46:26 -070089 # Named tuples to store struct and command data
90 self.StructType = namedtuple('StructType', ['name', 'value'])
Mark Lobodzinskic67efd02017-01-04 09:16:00 -070091 self.CommandParam = namedtuple('CommandParam', ['type', 'name', 'ispointer', 'isstaticarray', 'isconst', 'iscount', 'len', 'extstructs', 'cdecl'])
Mark Lobodzinski5380d132016-12-28 14:45:34 -070092 self.StructMemberData = namedtuple('StructMemberData', ['name', 'members', 'ifdef_protect'])
Petr Krause91f7a12017-12-14 20:57:36 +010093
94 self.custom_construct_params = {
95 # safe_VkGraphicsPipelineCreateInfo needs to know if subpass has color and\or depth\stencil attachments to use its pointers
96 'VkGraphicsPipelineCreateInfo' :
97 ', const bool uses_color_attachment, const bool uses_depthstencil_attachment',
98 # safe_VkPipelineViewportStateCreateInfo needs to know if viewport and scissor is dynamic to use its pointers
99 'VkPipelineViewportStateCreateInfo' :
100 ', const bool is_dynamic_viewports, const bool is_dynamic_scissors',
101 }
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700102 #
103 # Called once at the beginning of each run
104 def beginFile(self, genOpts):
105 OutputGenerator.beginFile(self, genOpts)
106 # User-supplied prefix text, if any (list of strings)
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700107 self.helper_file_type = genOpts.helper_file_type
108 self.library_name = genOpts.library_name
109 # File Comment
110 file_comment = '// *** THIS FILE IS GENERATED - DO NOT EDIT ***\n'
111 file_comment += '// See helper_file_generator.py for modifications\n'
112 write(file_comment, file=self.outFile)
113 # Copyright Notice
114 copyright = ''
115 copyright += '\n'
116 copyright += '/***************************************************************************\n'
117 copyright += ' *\n'
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700118 copyright += ' * Copyright (c) 2015-2017 The Khronos Group Inc.\n'
119 copyright += ' * Copyright (c) 2015-2017 Valve Corporation\n'
120 copyright += ' * Copyright (c) 2015-2017 LunarG, Inc.\n'
121 copyright += ' * Copyright (c) 2015-2017 Google Inc.\n'
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700122 copyright += ' *\n'
123 copyright += ' * Licensed under the Apache License, Version 2.0 (the "License");\n'
124 copyright += ' * you may not use this file except in compliance with the License.\n'
125 copyright += ' * You may obtain a copy of the License at\n'
126 copyright += ' *\n'
127 copyright += ' * http://www.apache.org/licenses/LICENSE-2.0\n'
128 copyright += ' *\n'
129 copyright += ' * Unless required by applicable law or agreed to in writing, software\n'
130 copyright += ' * distributed under the License is distributed on an "AS IS" BASIS,\n'
131 copyright += ' * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n'
132 copyright += ' * See the License for the specific language governing permissions and\n'
133 copyright += ' * limitations under the License.\n'
134 copyright += ' *\n'
135 copyright += ' * Author: Mark Lobodzinski <mark@lunarg.com>\n'
Mark Lobodzinskia9c963d2016-12-28 07:45:35 -0700136 copyright += ' * Author: Courtney Goeltzenleuchter <courtneygo@google.com>\n'
137 copyright += ' * Author: Tobin Ehlis <tobine@google.com>\n'
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600138 copyright += ' * Author: Chris Forbes <chrisforbes@google.com>\n'
John Zulaufde972ac2017-10-26 12:07:05 -0600139 copyright += ' * Author: John Zulauf<jzulauf@lunarg.com>\n'
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700140 copyright += ' *\n'
141 copyright += ' ****************************************************************************/\n'
142 write(copyright, file=self.outFile)
143 #
Mark Lobodzinskia3cc3612017-01-03 13:25:10 -0700144 # Write generated file content to output file
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700145 def endFile(self):
146 dest_file = ''
147 dest_file += self.OutputDestFile()
Mark Lobodzinskiafe10542017-01-03 13:22:44 -0700148 # Remove blank lines at EOF
149 if dest_file.endswith('\n'):
150 dest_file = dest_file[:-1]
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700151 write(dest_file, file=self.outFile);
152 # Finish processing in superclass
153 OutputGenerator.endFile(self)
154 #
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600155 # Override parent class to be notified of the beginning of an extension
156 def beginFeature(self, interface, emit):
157 # Start processing in superclass
158 OutputGenerator.beginFeature(self, interface, emit)
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600159 self.featureExtraProtect = GetFeatureProtect(interface)
160
Mark Lobodzinski31964ca2017-09-18 14:15:09 -0600161 if self.featureName == 'VK_VERSION_1_0' or self.featureName == 'VK_VERSION_1_1':
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600162 return
163 nameElem = interface[0][1]
164 name = nameElem.get('name')
165 if 'EXTENSION_NAME' not in name:
166 print("Error in vk.xml file -- extension name is not available")
167 if interface.get('type') == 'instance':
168 self.instance_extension_info[name] = self.featureExtraProtect
169 else:
170 self.device_extension_info[name] = self.featureExtraProtect
171 #
172 # Override parent class to be notified of the end of an extension
173 def endFeature(self):
174 # Finish processing in superclass
175 OutputGenerator.endFeature(self)
176 #
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700177 # Grab group (e.g. C "enum" type) info to output for enum-string conversion helper
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700178 def genGroup(self, groupinfo, groupName, alias):
179 OutputGenerator.genGroup(self, groupinfo, groupName, alias)
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700180 groupElem = groupinfo.elem
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700181 # For enum_string_header
182 if self.helper_file_type == 'enum_string_header':
Mike Schuchardtdf1e8dd2018-03-09 09:02:56 -0700183 value_set = set()
Mark Lobodzinski824ce642016-12-28 08:49:46 -0700184 for elem in groupElem.findall('enum'):
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700185 if elem.get('supported') != 'disabled' and elem.get('alias') == None:
Mike Schuchardtdf1e8dd2018-03-09 09:02:56 -0700186 value_set.add(elem.get('name'))
187 self.enum_output += self.GenerateEnumStringConversion(groupName, value_set)
Mark Young1ded24b2017-05-30 14:53:50 -0600188 elif self.helper_file_type == 'object_types_header':
189 if groupName == 'VkDebugReportObjectTypeEXT':
190 for elem in groupElem.findall('enum'):
191 if elem.get('supported') != 'disabled':
192 item_name = elem.get('name')
193 self.debug_report_object_types.append(item_name)
194 elif groupName == 'VkObjectType':
195 for elem in groupElem.findall('enum'):
196 if elem.get('supported') != 'disabled':
197 item_name = elem.get('name')
198 self.core_object_types.append(item_name)
199
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700200 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700201 # Called for each type -- if the type is a struct/union, grab the metadata
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700202 def genType(self, typeinfo, name, alias):
203 OutputGenerator.genType(self, typeinfo, name, alias)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700204 typeElem = typeinfo.elem
205 # If the type is a struct type, traverse the imbedded <member> tags generating a structure.
206 # Otherwise, emit the tag text.
207 category = typeElem.get('category')
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600208 if category == 'handle':
209 self.object_types.append(name)
210 elif (category == 'struct' or category == 'union'):
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700211 self.structNames.append(name)
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700212 self.genStruct(typeinfo, name, alias)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700213 #
214 # Generate a VkStructureType based on a structure typename
215 def genVkStructureType(self, typename):
216 # Add underscore between lowercase then uppercase
217 value = re.sub('([a-z0-9])([A-Z])', r'\1_\2', typename)
218 # Change to uppercase
219 value = value.upper()
220 # Add STRUCTURE_TYPE_
221 return re.sub('VK_', 'VK_STRUCTURE_TYPE_', value)
222 #
223 # Check if the parameter passed in is a pointer
224 def paramIsPointer(self, param):
225 ispointer = False
226 for elem in param:
227 if ((elem.tag is not 'type') and (elem.tail is not None)) and '*' in elem.tail:
228 ispointer = True
229 return ispointer
230 #
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700231 # Check if the parameter passed in is a static array
232 def paramIsStaticArray(self, param):
233 isstaticarray = 0
234 paramname = param.find('name')
235 if (paramname.tail is not None) and ('[' in paramname.tail):
236 isstaticarray = paramname.tail.count('[')
237 return isstaticarray
238 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700239 # Retrieve the type and name for a parameter
240 def getTypeNameTuple(self, param):
241 type = ''
242 name = ''
243 for elem in param:
244 if elem.tag == 'type':
245 type = noneStr(elem.text)
246 elif elem.tag == 'name':
247 name = noneStr(elem.text)
248 return (type, name)
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700249 # Extract length values from latexmath. Currently an inflexible solution that looks for specific
250 # patterns that are found in vk.xml. Will need to be updated when new patterns are introduced.
251 def parseLateXMath(self, source):
252 name = 'ERROR'
253 decoratedName = 'ERROR'
254 if 'mathit' in source:
Mark Lobodzinski36c33862017-02-13 10:15:53 -0700255 # Matches expressions similar to 'latexmath:[\lceil{\mathit{rasterizationSamples} \over 32}\rceil]'
256 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 -0700257 if not match or match.group(1) != match.group(4):
258 raise 'Unrecognized latexmath expression'
259 name = match.group(2)
mizhenc27f6c72017-03-31 09:08:16 -0600260 # Need to add 1 for ceiling function; otherwise, the allocated packet
261 # size will be less than needed during capture for some title which use
262 # this in VkPipelineMultisampleStateCreateInfo. based on ceiling function
263 # definition,it is '{0}%{1}?{0}/{1} + 1:{0}/{1}'.format(*match.group(2, 3)),
264 # its value <= '{}/{} + 1'.
265 if match.group(1) == 'ceil':
266 decoratedName = '{}/{} + 1'.format(*match.group(2, 3))
267 else:
268 decoratedName = '{}/{}'.format(*match.group(2, 3))
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700269 else:
Mark Lobodzinski36c33862017-02-13 10:15:53 -0700270 # Matches expressions similar to 'latexmath : [dataSize \over 4]'
Mark Young0f183a82017-02-28 09:58:04 -0700271 match = re.match(r'latexmath\s*\:\s*\[\s*(\w+)\s*\\over\s*(\d+)\s*\]', source)
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700272 name = match.group(1)
273 decoratedName = '{}/{}'.format(*match.group(1, 2))
274 return name, decoratedName
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700275 #
276 # Retrieve the value of the len tag
277 def getLen(self, param):
278 result = None
279 len = param.attrib.get('len')
280 if len and len != 'null-terminated':
281 # For string arrays, 'len' can look like 'count,null-terminated', indicating that we
282 # have a null terminated array of strings. We strip the null-terminated from the
283 # 'len' field and only return the parameter specifying the string count
284 if 'null-terminated' in len:
285 result = len.split(',')[0]
286 else:
287 result = len
Mark Lobodzinskif8f44fa2017-01-06 08:47:48 -0700288 if 'latexmath' in len:
289 param_type, param_name = self.getTypeNameTuple(param)
290 len_name, result = self.parseLateXMath(len)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700291 # Spec has now notation for len attributes, using :: instead of platform specific pointer symbol
292 result = str(result).replace('::', '->')
293 return result
294 #
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700295 # Check if a structure is or contains a dispatchable (dispatchable = True) or
296 # non-dispatchable (dispatchable = False) handle
297 def TypeContainsObjectHandle(self, handle_type, dispatchable):
298 if dispatchable:
299 type_key = 'VK_DEFINE_HANDLE'
300 else:
301 type_key = 'VK_DEFINE_NON_DISPATCHABLE_HANDLE'
302 handle = self.registry.tree.find("types/type/[name='" + handle_type + "'][@category='handle']")
303 if handle is not None and handle.find('type').text == type_key:
304 return True
305 # if handle_type is a struct, search its members
306 if handle_type in self.structNames:
307 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == handle_type), None)
308 if member_index is not None:
309 for item in self.structMembers[member_index].members:
310 handle = self.registry.tree.find("types/type/[name='" + item.type + "'][@category='handle']")
311 if handle is not None and handle.find('type').text == type_key:
312 return True
313 return False
314 #
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700315 # Generate local ready-access data describing Vulkan structures and unions from the XML metadata
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700316 def genStruct(self, typeinfo, typeName, alias):
317 OutputGenerator.genStruct(self, typeinfo, typeName, alias)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700318 members = typeinfo.elem.findall('.//member')
319 # Iterate over members once to get length parameters for arrays
320 lens = set()
321 for member in members:
322 len = self.getLen(member)
323 if len:
324 lens.add(len)
325 # Generate member info
326 membersInfo = []
327 for member in members:
328 # Get the member's type and name
329 info = self.getTypeNameTuple(member)
330 type = info[0]
331 name = info[1]
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700332 cdecl = self.makeCParamDecl(member, 1)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700333 # Process VkStructureType
334 if type == 'VkStructureType':
335 # Extract the required struct type value from the comments
336 # embedded in the original text defining the 'typeinfo' element
337 rawXml = etree.tostring(typeinfo.elem).decode('ascii')
338 result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml)
339 if result:
340 value = result.group(0)
341 else:
342 value = self.genVkStructureType(typeName)
343 # Store the required type value
344 self.structTypes[typeName] = self.StructType(name=name, value=value)
345 # Store pointer/array/string info
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700346 isstaticarray = self.paramIsStaticArray(member)
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700347 membersInfo.append(self.CommandParam(type=type,
348 name=name,
349 ispointer=self.paramIsPointer(member),
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700350 isstaticarray=isstaticarray,
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700351 isconst=True if 'const' in cdecl else False,
352 iscount=True if name in lens else False,
353 len=self.getLen(member),
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600354 extstructs=self.registry.validextensionstructs[typeName] if name == 'pNext' else None,
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700355 cdecl=cdecl))
Mark Lobodzinski5380d132016-12-28 14:45:34 -0700356 self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo, ifdef_protect=self.featureExtraProtect))
Mark Lobodzinski46d388f2016-12-28 10:46:26 -0700357 #
358 # Enum_string_header: Create a routine to convert an enumerated value into a string
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700359 def GenerateEnumStringConversion(self, groupName, value_list):
360 outstring = '\n'
361 outstring += 'static inline const char* string_%s(%s input_value)\n' % (groupName, groupName)
362 outstring += '{\n'
363 outstring += ' switch ((%s)input_value)\n' % groupName
364 outstring += ' {\n'
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -0700365 for item in value_list:
366 outstring += ' case %s:\n' % item
367 outstring += ' return "%s";\n' % item
368 outstring += ' default:\n'
369 outstring += ' return "Unhandled %s";\n' % groupName
370 outstring += ' }\n'
371 outstring += '}\n'
372 return outstring
373 #
Mark Lobodzinski64b432f2017-07-24 16:14:16 -0600374 # Tack on a helper which, given an index into a VkPhysicalDeviceFeatures structure, will print the corresponding feature name
375 def DeIndexPhysDevFeatures(self):
376 pdev_members = None
377 for name, members, ifdef in self.structMembers:
378 if name == 'VkPhysicalDeviceFeatures':
379 pdev_members = members
380 break
381 deindex = '\n'
Mark Young2ee6aea2018-02-21 15:30:27 -0700382 deindex += 'static inline const char * GetPhysDevFeatureString(uint32_t index) {\n'
Mark Lobodzinski64b432f2017-07-24 16:14:16 -0600383 deindex += ' const char * IndexToPhysDevFeatureString[] = {\n'
384 for feature in pdev_members:
385 deindex += ' "%s",\n' % feature.name
386 deindex += ' };\n\n'
387 deindex += ' return IndexToPhysDevFeatureString[index];\n'
388 deindex += '}\n'
389 return deindex
390 #
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700391 # Combine enum string helper header file preamble with body text and return
392 def GenerateEnumStringHelperHeader(self):
393 enum_string_helper_header = '\n'
394 enum_string_helper_header += '#pragma once\n'
395 enum_string_helper_header += '#ifdef _WIN32\n'
396 enum_string_helper_header += '#pragma warning( disable : 4065 )\n'
397 enum_string_helper_header += '#endif\n'
398 enum_string_helper_header += '\n'
399 enum_string_helper_header += '#include <vulkan/vulkan.h>\n'
400 enum_string_helper_header += '\n'
401 enum_string_helper_header += self.enum_output
Mark Lobodzinski64b432f2017-07-24 16:14:16 -0600402 enum_string_helper_header += self.DeIndexPhysDevFeatures()
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700403 return enum_string_helper_header
404 #
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -0700405 # Helper function for declaring a counter variable only once
406 def DeclareCounter(self, string_var, declare_flag):
407 if declare_flag == False:
408 string_var += ' uint32_t i = 0;\n'
409 declare_flag = True
410 return string_var, declare_flag
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -0700411 #
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700412 # Combine safe struct helper header file preamble with body text and return
413 def GenerateSafeStructHelperHeader(self):
414 safe_struct_helper_header = '\n'
415 safe_struct_helper_header += '#pragma once\n'
416 safe_struct_helper_header += '#include <vulkan/vulkan.h>\n'
417 safe_struct_helper_header += '\n'
418 safe_struct_helper_header += self.GenerateSafeStructHeader()
419 return safe_struct_helper_header
420 #
421 # safe_struct header: build function prototypes for header file
422 def GenerateSafeStructHeader(self):
423 safe_struct_header = ''
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700424 for item in self.structMembers:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700425 if self.NeedSafeStruct(item) == True:
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700426 safe_struct_header += '\n'
427 if item.ifdef_protect != None:
428 safe_struct_header += '#ifdef %s\n' % item.ifdef_protect
429 safe_struct_header += 'struct safe_%s {\n' % (item.name)
430 for member in item.members:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700431 if member.type in self.structNames:
432 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
433 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
434 if member.ispointer:
435 safe_struct_header += ' safe_%s* %s;\n' % (member.type, member.name)
436 else:
437 safe_struct_header += ' safe_%s %s;\n' % (member.type, member.name)
438 continue
439 if member.len is not None and (self.TypeContainsObjectHandle(member.type, True) or self.TypeContainsObjectHandle(member.type, False)):
440 safe_struct_header += ' %s* %s;\n' % (member.type, member.name)
441 else:
442 safe_struct_header += '%s;\n' % member.cdecl
Petr Krause91f7a12017-12-14 20:57:36 +0100443 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 -0600444 safe_struct_header += ' safe_%s(const safe_%s& src);\n' % (item.name, item.name)
Chris Forbesfb633832017-10-03 18:11:54 -0700445 safe_struct_header += ' safe_%s& operator=(const safe_%s& src);\n' % (item.name, item.name)
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700446 safe_struct_header += ' safe_%s();\n' % item.name
447 safe_struct_header += ' ~safe_%s();\n' % item.name
Petr Krause91f7a12017-12-14 20:57:36 +0100448 safe_struct_header += ' void initialize(const %s* in_struct%s);\n' % (item.name, self.custom_construct_params.get(item.name, ''))
449 safe_struct_header += ' void initialize(const safe_%s* src);\n' % (item.name)
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700450 safe_struct_header += ' %s *ptr() { return reinterpret_cast<%s *>(this); }\n' % (item.name, item.name)
451 safe_struct_header += ' %s const *ptr() const { return reinterpret_cast<%s const *>(this); }\n' % (item.name, item.name)
452 safe_struct_header += '};\n'
453 if item.ifdef_protect != None:
454 safe_struct_header += '#endif // %s\n' % item.ifdef_protect
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700455 return safe_struct_header
456 #
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600457 # Generate extension helper header file
458 def GenerateExtensionHelperHeader(self):
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600459
460 V_1_0_instance_extensions_promoted_to_core = [
461 'vk_khr_device_group_creation',
462 'vk_khr_external_memory_capabilities',
463 'vk_khr_external_fence_capabilities',
464 'vk_khr_external_semaphore_capabilities',
465 'vk_khr_get_physical_device_properties_2',
466 ]
467
468 V_1_0_device_extensions_promoted_to_core = [
469 'vk_khr_bind_memory_2',
470 'vk_khr_device_group',
471 'vk_khr_descriptor_update_template',
472 'vk_khr_sampler_ycbcr_conversion',
473 'vk_khr_get_memory_requirements_2',
474 'vk_khr_maintenance3',
475 'vk_khr_maintenance1',
476 'vk_khr_multiview',
477 'vk_khr_external_memory',
478 'vk_khr_external_semaphore',
479 'vk_khr_16bit_storage',
480 'vk_khr_external_fence',
481 'vk_khr_maintenance2',
482 'vk_khr_variable_pointers',
483 'vk_khr_dedicated_allocation',
484 ]
485
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600486 extension_helper_header = '\n'
487 extension_helper_header += '#ifndef VK_EXTENSION_HELPER_H_\n'
488 extension_helper_header += '#define VK_EXTENSION_HELPER_H_\n'
489 struct = '\n'
Tobin Ehlis84154d32017-06-09 15:46:14 -0600490 extension_helper_header += '#include <vulkan/vulkan.h>\n'
Tobin Ehlisd922d4c2017-06-14 09:43:04 -0600491 extension_helper_header += '#include <string.h>\n'
Tobin Ehlis84154d32017-06-09 15:46:14 -0600492 extension_helper_header += '#include <utility>\n'
493 extension_helper_header += '\n'
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600494 extension_helper_header += '\n'
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600495 extension_dict = dict()
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600496 promoted_ext_list = []
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600497 for type in ['Instance', 'Device']:
498 if type == 'Instance':
499 extension_dict = self.instance_extension_info
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600500 promoted_ext_list = V_1_0_instance_extensions_promoted_to_core
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600501 struct += 'struct InstanceExtensions { \n'
502 else:
503 extension_dict = self.device_extension_info
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600504 promoted_ext_list = V_1_0_device_extensions_promoted_to_core
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600505 struct += 'struct DeviceExtensions : public InstanceExtensions { \n'
506 for ext_name, ifdef in extension_dict.items():
507 bool_name = ext_name.lower()
508 bool_name = re.sub('_extension_name', '', bool_name)
509 struct += ' bool %s{false};\n' % bool_name
510 struct += '\n'
511 if type == 'Instance':
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600512 struct += ' uint32_t NormalizeApiVersion(uint32_t specified_version) {\n'
513 struct += ' uint32_t api_version = specified_version & ~VK_VERSION_PATCH(~0);\n'
514 struct += ' if (!(api_version == VK_API_VERSION_1_0) && !(api_version == VK_API_VERSION_1_1)) {\n'
515 struct += ' api_version = VK_API_VERSION_1_1;\n'
516 struct += ' }\n'
517 struct += ' return api_version;\n'
518 struct += ' }\n'
519 struct += '\n'
520
521 struct += ' uint32_t InitFromInstanceCreateInfo(uint32_t requested_api_version, const VkInstanceCreateInfo *pCreateInfo) {\n'
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600522 else:
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600523 struct += ' uint32_t InitFromDeviceCreateInfo(const InstanceExtensions *instance_extensions, uint32_t requested_api_version, const VkDeviceCreateInfo *pCreateInfo) {\n'
524 struct += '\n'
525
526 struct += ' static const std::vector<const char *> V_1_0_promoted_%s_extensions = {\n' % type.lower()
527 for ext_name in promoted_ext_list:
528 struct += ' %s_EXTENSION_NAME,\n' % ext_name.upper()
529 struct += ' };\n'
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600530 struct += '\n'
531 struct += ' static const std::pair<char const *, bool %sExtensions::*> known_extensions[]{\n' % type
532 for ext_name, ifdef in extension_dict.items():
533 if ifdef is not None:
534 struct += '#ifdef %s\n' % ifdef
535 bool_name = ext_name.lower()
536 bool_name = re.sub('_extension_name', '', bool_name)
537 struct += ' {%s, &%sExtensions::%s},\n' % (ext_name, type, bool_name)
538 if ifdef is not None:
539 struct += '#endif\n'
540 struct += ' };\n'
541 struct += '\n'
542 struct += ' // Initialize struct data\n'
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600543
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600544 for ext_name, ifdef in self.instance_extension_info.items():
545 bool_name = ext_name.lower()
546 bool_name = re.sub('_extension_name', '', bool_name)
547 if type == 'Device':
548 struct += ' %s = instance_extensions->%s;\n' % (bool_name, bool_name)
549 struct += '\n'
550 struct += ' for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {\n'
551 struct += ' for (auto ext : known_extensions) {\n'
552 struct += ' if (!strcmp(ext.first, pCreateInfo->ppEnabledExtensionNames[i])) {\n'
553 struct += ' this->*(ext.second) = true;\n'
554 struct += ' break;\n'
555 struct += ' }\n'
556 struct += ' }\n'
557 struct += ' }\n'
Mark Lobodzinskibfb7ab92017-10-27 13:22:23 -0600558 struct += ' uint32_t api_version = NormalizeApiVersion(requested_api_version);\n'
559 struct += ' if (api_version >= VK_API_VERSION_1_1) {\n'
560 struct += ' for (auto promoted_ext : V_1_0_promoted_%s_extensions) {\n' % type.lower()
561 struct += ' for (auto ext : known_extensions) {\n'
562 struct += ' if (!strcmp(ext.first, promoted_ext)) {\n'
563 struct += ' this->*(ext.second) = true;\n'
564 struct += ' break;\n'
565 struct += ' }\n'
566 struct += ' }\n'
567 struct += ' }\n'
568 struct += ' }\n'
569 struct += ' return api_version;\n'
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600570 struct += ' }\n'
571 struct += '};\n'
572 struct += '\n'
Mark Lobodzinskifc9451f2018-01-03 11:18:31 -0700573 # Output reference lists of instance/device extension names
574 struct += 'static const char * const k%sExtensionNames = \n' % type
575 for ext_name, ifdef in extension_dict.items():
576 if ifdef is not None:
577 struct += '#ifdef %s\n' % ifdef
578 struct += ' %s\n' % ext_name
579 if ifdef is not None:
580 struct += '#endif\n'
581 struct += ';\n\n'
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -0600582 extension_helper_header += struct
583 extension_helper_header += '\n'
584 extension_helper_header += '#endif // VK_EXTENSION_HELPER_H_\n'
585 return extension_helper_header
586 #
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600587 # Combine object types helper header file preamble with body text and return
588 def GenerateObjectTypesHelperHeader(self):
589 object_types_helper_header = '\n'
590 object_types_helper_header += '#pragma once\n'
591 object_types_helper_header += '\n'
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600592 object_types_helper_header += '#include <vulkan/vulkan.h>\n\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600593 object_types_helper_header += self.GenerateObjectTypesHeader()
594 return object_types_helper_header
595 #
596 # Object types header: create object enum type header file
597 def GenerateObjectTypesHeader(self):
Mark Young6ba8abe2017-11-09 10:37:04 -0700598 object_types_header = ''
599 object_types_header += '// Object Type enum for validation layer internal object handling\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600600 object_types_header += 'typedef enum VulkanObjectType {\n'
601 object_types_header += ' kVulkanObjectTypeUnknown = 0,\n'
602 enum_num = 1
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600603 type_list = [];
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600604
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600605 # Output enum definition as each handle is processed, saving the names to use for the conversion routine
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600606 for item in self.object_types:
607 fixup_name = item[2:]
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600608 enum_entry = 'kVulkanObjectType%s' % fixup_name
609 object_types_header += ' ' + enum_entry
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600610 object_types_header += ' = %d,\n' % enum_num
611 enum_num += 1
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600612 type_list.append(enum_entry)
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600613 object_types_header += ' kVulkanObjectTypeMax = %d,\n' % enum_num
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600614 object_types_header += '} VulkanObjectType;\n\n'
615
616 # Output name string helper
617 object_types_header += '// Array of object name strings for OBJECT_TYPE enum conversion\n'
Mark Lobodzinski8eb37422017-04-18 14:22:10 -0600618 object_types_header += 'static const char * const object_string[kVulkanObjectTypeMax] = {\n'
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600619 object_types_header += ' "Unknown",\n'
620 for item in self.object_types:
621 fixup_name = item[2:]
622 object_types_header += ' "%s",\n' % fixup_name
623 object_types_header += '};\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600624
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600625 # Output a conversion routine from the layer object definitions to the debug report definitions
Mark Lobodzinskiff92ff82017-04-11 15:31:51 -0600626 object_types_header += '\n'
Mark Young1ded24b2017-05-30 14:53:50 -0600627 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 -0600628 object_types_header += 'const VkDebugReportObjectTypeEXT get_debug_report_enum[] = {\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700629 object_types_header += ' VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, // kVulkanObjectTypeUnknown\n'
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600630 for object_type in type_list:
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600631 search_type = object_type.replace("kVulkanObjectType", "").lower()
Gabríel Arthúr Pétursson1a271d02018-03-18 17:34:01 +0000632 found = False
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600633 for vk_object_type in self.debug_report_object_types:
634 target_type = vk_object_type.replace("VK_DEBUG_REPORT_OBJECT_TYPE_", "").lower()
635 target_type = target_type[:-4]
636 target_type = target_type.replace("_", "")
637 if search_type == target_type:
Mark Lobodzinskiecf0ae12017-04-13 08:36:18 -0600638 object_types_header += ' %s, // %s\n' % (vk_object_type, object_type)
Gabríel Arthúr Pétursson1a271d02018-03-18 17:34:01 +0000639 found = True
Mark Lobodzinski4c51cd02017-04-04 12:07:38 -0600640 break
Gabríel Arthúr Pétursson1a271d02018-03-18 17:34:01 +0000641 if not found:
642 object_types_header += ' %s, // %s\n' % ("VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT", object_type)
643
Mark Lobodzinskiecf0ae12017-04-13 08:36:18 -0600644 object_types_header += '};\n'
Mark Young1ded24b2017-05-30 14:53:50 -0600645
646 # Output a conversion routine from the layer object definitions to the core object type definitions
647 object_types_header += '\n'
648 object_types_header += '// Helper array to get Official Vulkan VkObjectType enum from the internal layers version\n'
649 object_types_header += 'const VkObjectType get_object_type_enum[] = {\n'
Mark Young6ba8abe2017-11-09 10:37:04 -0700650 object_types_header += ' VK_OBJECT_TYPE_UNKNOWN, // kVulkanObjectTypeUnknown\n'
Mark Young1ded24b2017-05-30 14:53:50 -0600651 for object_type in type_list:
Mark Young1ded24b2017-05-30 14:53:50 -0600652 search_type = object_type.replace("kVulkanObjectType", "").lower()
653 for vk_object_type in self.core_object_types:
654 target_type = vk_object_type.replace("VK_OBJECT_TYPE_", "").lower()
655 target_type = target_type.replace("_", "")
656 if search_type == target_type:
657 object_types_header += ' %s, // %s\n' % (vk_object_type, object_type)
Mark Young1ded24b2017-05-30 14:53:50 -0600658 break
Mark Young1ded24b2017-05-30 14:53:50 -0600659 object_types_header += '};\n'
660
Mark Young6ba8abe2017-11-09 10:37:04 -0700661 # Create a function to convert from VkDebugReportObjectTypeEXT to VkObjectType
662 object_types_header += '\n'
663 object_types_header += '// Helper function to convert from VkDebugReportObjectTypeEXT to VkObjectType\n'
664 object_types_header += 'static VkObjectType convertDebugReportObjectToCoreObject(VkDebugReportObjectTypeEXT debug_report_obj){\n'
665 object_types_header += ' if (debug_report_obj == VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT) {\n'
666 object_types_header += ' return VK_OBJECT_TYPE_UNKNOWN;\n'
667 for core_object_type in self.core_object_types:
668 core_target_type = core_object_type.replace("VK_OBJECT_TYPE_", "").lower()
669 core_target_type = core_target_type.replace("_", "")
670 for dr_object_type in self.debug_report_object_types:
671 dr_target_type = dr_object_type.replace("VK_DEBUG_REPORT_OBJECT_TYPE_", "").lower()
672 dr_target_type = dr_target_type[:-4]
673 dr_target_type = dr_target_type.replace("_", "")
674 if core_target_type == dr_target_type:
675 object_types_header += ' } else if (debug_report_obj == %s) {\n' % dr_object_type
676 object_types_header += ' return %s;\n' % core_object_type
677 break
678 object_types_header += ' }\n'
679 object_types_header += ' return VK_OBJECT_TYPE_UNKNOWN;\n'
680 object_types_header += '}\n'
681
682 # Create a function to convert from VkObjectType to VkDebugReportObjectTypeEXT
683 object_types_header += '\n'
684 object_types_header += '// Helper function to convert from VkDebugReportObjectTypeEXT to VkObjectType\n'
685 object_types_header += 'static VkDebugReportObjectTypeEXT convertCoreObjectToDebugReportObject(VkObjectType core_report_obj){\n'
686 object_types_header += ' if (core_report_obj == VK_OBJECT_TYPE_UNKNOWN) {\n'
687 object_types_header += ' return VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT;\n'
688 for core_object_type in self.core_object_types:
689 core_target_type = core_object_type.replace("VK_OBJECT_TYPE_", "").lower()
690 core_target_type = core_target_type.replace("_", "")
691 for dr_object_type in self.debug_report_object_types:
692 dr_target_type = dr_object_type.replace("VK_DEBUG_REPORT_OBJECT_TYPE_", "").lower()
693 dr_target_type = dr_target_type[:-4]
694 dr_target_type = dr_target_type.replace("_", "")
695 if core_target_type == dr_target_type:
696 object_types_header += ' } else if (core_report_obj == %s) {\n' % core_object_type
697 object_types_header += ' return %s;\n' % dr_object_type
698 break
699 object_types_header += ' }\n'
700 object_types_header += ' return VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT;\n'
701 object_types_header += '}\n'
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -0600702 return object_types_header
703 #
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700704 # Determine if a structure needs a safe_struct helper function
705 # That is, it has an sType or one of its members is a pointer
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700706 def NeedSafeStruct(self, structure):
Mark Lobodzinski5c873842017-01-03 13:22:10 -0700707 if 'sType' == structure.name:
708 return True
709 for member in structure.members:
710 if member.ispointer == True:
711 return True
712 return False
713 #
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700714 # Combine safe struct helper source file preamble with body text and return
715 def GenerateSafeStructHelperSource(self):
716 safe_struct_helper_source = '\n'
717 safe_struct_helper_source += '#include "vk_safe_struct.h"\n'
718 safe_struct_helper_source += '#include <string.h>\n'
719 safe_struct_helper_source += '\n'
720 safe_struct_helper_source += self.GenerateSafeStructSource()
721 return safe_struct_helper_source
722 #
723 # safe_struct source -- create bodies of safe struct helper functions
724 def GenerateSafeStructSource(self):
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700725 safe_struct_body = []
Mark Lobodzinski560729b2017-03-06 08:59:14 -0700726 wsi_structs = ['VkXlibSurfaceCreateInfoKHR',
727 'VkXcbSurfaceCreateInfoKHR',
728 'VkWaylandSurfaceCreateInfoKHR',
729 'VkMirSurfaceCreateInfoKHR',
730 'VkAndroidSurfaceCreateInfoKHR',
731 'VkWin32SurfaceCreateInfoKHR'
732 ]
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700733 for item in self.structMembers:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700734 if self.NeedSafeStruct(item) == False:
735 continue
Mark Lobodzinski560729b2017-03-06 08:59:14 -0700736 if item.name in wsi_structs:
737 continue
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700738 if item.ifdef_protect != None:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700739 safe_struct_body.append("#ifdef %s\n" % item.ifdef_protect)
740 ss_name = "safe_%s" % item.name
741 init_list = '' # list of members in struct constructor initializer
742 default_init_list = '' # Default constructor just inits ptrs to nullptr in initializer
743 init_func_txt = '' # Txt for initialize() function that takes struct ptr and inits members
744 construct_txt = '' # Body of constuctor as well as body of initialize() func following init_func_txt
745 destruct_txt = ''
Petr Krause91f7a12017-12-14 20:57:36 +0100746
747 custom_construct_txt = {
748 # VkWriteDescriptorSet is special case because pointers may be non-null but ignored
749 'VkWriteDescriptorSet' :
750 ' switch (descriptorType) {\n'
751 ' case VK_DESCRIPTOR_TYPE_SAMPLER:\n'
752 ' case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:\n'
753 ' case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:\n'
754 ' case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:\n'
755 ' case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:\n'
756 ' if (descriptorCount && in_struct->pImageInfo) {\n'
757 ' pImageInfo = new VkDescriptorImageInfo[descriptorCount];\n'
758 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
759 ' pImageInfo[i] = in_struct->pImageInfo[i];\n'
760 ' }\n'
761 ' }\n'
762 ' break;\n'
763 ' case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:\n'
764 ' case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:\n'
765 ' case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:\n'
766 ' case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:\n'
767 ' if (descriptorCount && in_struct->pBufferInfo) {\n'
768 ' pBufferInfo = new VkDescriptorBufferInfo[descriptorCount];\n'
769 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
770 ' pBufferInfo[i] = in_struct->pBufferInfo[i];\n'
771 ' }\n'
772 ' }\n'
773 ' break;\n'
774 ' case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:\n'
775 ' case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:\n'
776 ' if (descriptorCount && in_struct->pTexelBufferView) {\n'
777 ' pTexelBufferView = new VkBufferView[descriptorCount];\n'
778 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
779 ' pTexelBufferView[i] = in_struct->pTexelBufferView[i];\n'
780 ' }\n'
781 ' }\n'
782 ' break;\n'
783 ' default:\n'
784 ' break;\n'
785 ' }\n',
Petr Kraus42f6f8d2017-12-17 17:37:33 +0100786 'VkShaderModuleCreateInfo' :
Petr Krause91f7a12017-12-14 20:57:36 +0100787 ' if (in_struct->pCode) {\n'
788 ' pCode = reinterpret_cast<uint32_t *>(new uint8_t[codeSize]);\n'
789 ' memcpy((void *)pCode, (void *)in_struct->pCode, codeSize);\n'
790 ' }\n',
791 # VkGraphicsPipelineCreateInfo is special case because its pointers may be non-null but ignored
792 'VkGraphicsPipelineCreateInfo' :
793 ' if (stageCount && in_struct->pStages) {\n'
794 ' pStages = new safe_VkPipelineShaderStageCreateInfo[stageCount];\n'
795 ' for (uint32_t i=0; i<stageCount; ++i) {\n'
796 ' pStages[i].initialize(&in_struct->pStages[i]);\n'
797 ' }\n'
798 ' }\n'
799 ' if (in_struct->pVertexInputState)\n'
800 ' pVertexInputState = new safe_VkPipelineVertexInputStateCreateInfo(in_struct->pVertexInputState);\n'
801 ' else\n'
802 ' pVertexInputState = NULL;\n'
803 ' if (in_struct->pInputAssemblyState)\n'
804 ' pInputAssemblyState = new safe_VkPipelineInputAssemblyStateCreateInfo(in_struct->pInputAssemblyState);\n'
805 ' else\n'
806 ' pInputAssemblyState = NULL;\n'
807 ' bool has_tessellation_stage = false;\n'
808 ' if (stageCount && pStages)\n'
809 ' for (uint32_t i=0; i<stageCount && !has_tessellation_stage; ++i)\n'
810 ' if (pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)\n'
811 ' has_tessellation_stage = true;\n'
812 ' if (in_struct->pTessellationState && has_tessellation_stage)\n'
813 ' pTessellationState = new safe_VkPipelineTessellationStateCreateInfo(in_struct->pTessellationState);\n'
814 ' else\n'
815 ' pTessellationState = NULL; // original pTessellationState pointer ignored\n'
816 ' bool has_rasterization = in_struct->pRasterizationState ? !in_struct->pRasterizationState->rasterizerDiscardEnable : false;\n'
817 ' if (in_struct->pViewportState && has_rasterization) {\n'
818 ' bool is_dynamic_viewports = false;\n'
819 ' bool is_dynamic_scissors = false;\n'
820 ' if (in_struct->pDynamicState && in_struct->pDynamicState->pDynamicStates) {\n'
821 ' for (uint32_t i = 0; i < in_struct->pDynamicState->dynamicStateCount && !is_dynamic_viewports; ++i)\n'
822 ' if (in_struct->pDynamicState->pDynamicStates[i] == VK_DYNAMIC_STATE_VIEWPORT)\n'
823 ' is_dynamic_viewports = true;\n'
824 ' for (uint32_t i = 0; i < in_struct->pDynamicState->dynamicStateCount && !is_dynamic_scissors; ++i)\n'
825 ' if (in_struct->pDynamicState->pDynamicStates[i] == VK_DYNAMIC_STATE_SCISSOR)\n'
826 ' is_dynamic_scissors = true;\n'
827 ' }\n'
828 ' pViewportState = new safe_VkPipelineViewportStateCreateInfo(in_struct->pViewportState, is_dynamic_viewports, is_dynamic_scissors);\n'
829 ' } else\n'
830 ' pViewportState = NULL; // original pViewportState pointer ignored\n'
831 ' if (in_struct->pRasterizationState)\n'
832 ' pRasterizationState = new safe_VkPipelineRasterizationStateCreateInfo(in_struct->pRasterizationState);\n'
833 ' else\n'
834 ' pRasterizationState = NULL;\n'
835 ' if (in_struct->pMultisampleState && has_rasterization)\n'
836 ' pMultisampleState = new safe_VkPipelineMultisampleStateCreateInfo(in_struct->pMultisampleState);\n'
837 ' else\n'
838 ' pMultisampleState = NULL; // original pMultisampleState pointer ignored\n'
839 ' // needs a tracked subpass state uses_depthstencil_attachment\n'
840 ' if (in_struct->pDepthStencilState && has_rasterization && uses_depthstencil_attachment)\n'
841 ' pDepthStencilState = new safe_VkPipelineDepthStencilStateCreateInfo(in_struct->pDepthStencilState);\n'
842 ' else\n'
843 ' pDepthStencilState = NULL; // original pDepthStencilState pointer ignored\n'
844 ' // needs a tracked subpass state usesColorAttachment\n'
845 ' if (in_struct->pColorBlendState && has_rasterization && uses_color_attachment)\n'
846 ' pColorBlendState = new safe_VkPipelineColorBlendStateCreateInfo(in_struct->pColorBlendState);\n'
847 ' else\n'
848 ' pColorBlendState = NULL; // original pColorBlendState pointer ignored\n'
849 ' if (in_struct->pDynamicState)\n'
850 ' pDynamicState = new safe_VkPipelineDynamicStateCreateInfo(in_struct->pDynamicState);\n'
851 ' else\n'
852 ' pDynamicState = NULL;\n',
853 # VkPipelineViewportStateCreateInfo is special case because its pointers may be non-null but ignored
854 'VkPipelineViewportStateCreateInfo' :
855 ' if (in_struct->pViewports && !is_dynamic_viewports) {\n'
856 ' pViewports = new VkViewport[in_struct->viewportCount];\n'
857 ' memcpy ((void *)pViewports, (void *)in_struct->pViewports, sizeof(VkViewport)*in_struct->viewportCount);\n'
858 ' }\n'
859 ' else\n'
860 ' pViewports = NULL;\n'
861 ' if (in_struct->pScissors && !is_dynamic_scissors) {\n'
862 ' pScissors = new VkRect2D[in_struct->scissorCount];\n'
863 ' memcpy ((void *)pScissors, (void *)in_struct->pScissors, sizeof(VkRect2D)*in_struct->scissorCount);\n'
864 ' }\n'
865 ' else\n'
866 ' pScissors = NULL;\n',
Petr Kraus42f6f8d2017-12-17 17:37:33 +0100867 # VkDescriptorSetLayoutBinding is special case because its pImmutableSamplers pointer may be non-null but ignored
868 'VkDescriptorSetLayoutBinding' :
869 ' const bool sampler_type = in_struct->descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER || in_struct->descriptorType == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;\n'
870 ' if (descriptorCount && in_struct->pImmutableSamplers && sampler_type) {\n'
871 ' pImmutableSamplers = new VkSampler[descriptorCount];\n'
872 ' for (uint32_t i=0; i<descriptorCount; ++i) {\n'
873 ' pImmutableSamplers[i] = in_struct->pImmutableSamplers[i];\n'
874 ' }\n'
875 ' }\n',
Petr Krause91f7a12017-12-14 20:57:36 +0100876 }
877
878 custom_copy_txt = {
879 # VkGraphicsPipelineCreateInfo is special case because it has custom construct parameters
880 'VkGraphicsPipelineCreateInfo' :
881 ' if (stageCount && src.pStages) {\n'
882 ' pStages = new safe_VkPipelineShaderStageCreateInfo[stageCount];\n'
883 ' for (uint32_t i=0; i<stageCount; ++i) {\n'
884 ' pStages[i].initialize(&src.pStages[i]);\n'
885 ' }\n'
886 ' }\n'
887 ' if (src.pVertexInputState)\n'
888 ' pVertexInputState = new safe_VkPipelineVertexInputStateCreateInfo(*src.pVertexInputState);\n'
889 ' else\n'
890 ' pVertexInputState = NULL;\n'
891 ' if (src.pInputAssemblyState)\n'
892 ' pInputAssemblyState = new safe_VkPipelineInputAssemblyStateCreateInfo(*src.pInputAssemblyState);\n'
893 ' else\n'
894 ' pInputAssemblyState = NULL;\n'
895 ' bool has_tessellation_stage = false;\n'
896 ' if (stageCount && pStages)\n'
897 ' for (uint32_t i=0; i<stageCount && !has_tessellation_stage; ++i)\n'
898 ' if (pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStages[i].stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)\n'
899 ' has_tessellation_stage = true;\n'
900 ' if (src.pTessellationState && has_tessellation_stage)\n'
901 ' pTessellationState = new safe_VkPipelineTessellationStateCreateInfo(*src.pTessellationState);\n'
902 ' else\n'
903 ' pTessellationState = NULL; // original pTessellationState pointer ignored\n'
904 ' bool has_rasterization = src.pRasterizationState ? !src.pRasterizationState->rasterizerDiscardEnable : false;\n'
905 ' if (src.pViewportState && has_rasterization) {\n'
906 ' pViewportState = new safe_VkPipelineViewportStateCreateInfo(*src.pViewportState);\n'
907 ' } else\n'
908 ' pViewportState = NULL; // original pViewportState pointer ignored\n'
909 ' if (src.pRasterizationState)\n'
910 ' pRasterizationState = new safe_VkPipelineRasterizationStateCreateInfo(*src.pRasterizationState);\n'
911 ' else\n'
912 ' pRasterizationState = NULL;\n'
913 ' if (src.pMultisampleState && has_rasterization)\n'
914 ' pMultisampleState = new safe_VkPipelineMultisampleStateCreateInfo(*src.pMultisampleState);\n'
915 ' else\n'
916 ' pMultisampleState = NULL; // original pMultisampleState pointer ignored\n'
917 ' if (src.pDepthStencilState && has_rasterization)\n'
918 ' pDepthStencilState = new safe_VkPipelineDepthStencilStateCreateInfo(*src.pDepthStencilState);\n'
919 ' else\n'
920 ' pDepthStencilState = NULL; // original pDepthStencilState pointer ignored\n'
921 ' if (src.pColorBlendState && has_rasterization)\n'
922 ' pColorBlendState = new safe_VkPipelineColorBlendStateCreateInfo(*src.pColorBlendState);\n'
923 ' else\n'
924 ' pColorBlendState = NULL; // original pColorBlendState pointer ignored\n'
925 ' if (src.pDynamicState)\n'
926 ' pDynamicState = new safe_VkPipelineDynamicStateCreateInfo(*src.pDynamicState);\n'
927 ' else\n'
928 ' pDynamicState = NULL;\n',
929 # VkPipelineViewportStateCreateInfo is special case because it has custom construct parameters
930 'VkPipelineViewportStateCreateInfo' :
931 ' if (src.pViewports) {\n'
932 ' pViewports = new VkViewport[src.viewportCount];\n'
933 ' memcpy ((void *)pViewports, (void *)src.pViewports, sizeof(VkViewport)*src.viewportCount);\n'
934 ' }\n'
935 ' else\n'
936 ' pViewports = NULL;\n'
937 ' if (src.pScissors) {\n'
938 ' pScissors = new VkRect2D[src.scissorCount];\n'
939 ' memcpy ((void *)pScissors, (void *)src.pScissors, sizeof(VkRect2D)*src.scissorCount);\n'
940 ' }\n'
941 ' else\n'
942 ' pScissors = NULL;\n',
943 }
944
Mike Schuchardt81485762017-09-04 11:38:42 -0600945 custom_destruct_txt = {'VkShaderModuleCreateInfo' :
946 ' if (pCode)\n'
947 ' delete[] reinterpret_cast<const uint8_t *>(pCode);\n' }
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700948
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700949 for member in item.members:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700950 m_type = member.type
951 if member.type in self.structNames:
952 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
953 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
954 m_type = 'safe_%s' % member.type
955 if member.ispointer and 'safe_' not in m_type and self.TypeContainsObjectHandle(member.type, False) == False:
956 # 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 -0700957 if m_type in ['void', 'char']:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700958 # For these exceptions just copy initial value over for now
959 init_list += '\n %s(in_struct->%s),' % (member.name, member.name)
960 init_func_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700961 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700962 default_init_list += '\n %s(nullptr),' % (member.name)
963 init_list += '\n %s(nullptr),' % (member.name)
964 init_func_txt += ' %s = nullptr;\n' % (member.name)
965 if 'pNext' != member.name and 'void' not in m_type:
Mark Lobodzinski51160a12017-01-18 11:05:48 -0700966 if not member.isstaticarray and (member.len is None or '/' in member.len):
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700967 construct_txt += ' if (in_struct->%s) {\n' % member.name
968 construct_txt += ' %s = new %s(*in_struct->%s);\n' % (member.name, m_type, member.name)
969 construct_txt += ' }\n'
970 destruct_txt += ' if (%s)\n' % member.name
971 destruct_txt += ' delete %s;\n' % member.name
Mark Lobodzinskie20e4562017-01-03 11:14:26 -0700972 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -0700973 construct_txt += ' if (in_struct->%s) {\n' % member.name
974 construct_txt += ' %s = new %s[in_struct->%s];\n' % (member.name, m_type, member.len)
975 construct_txt += ' memcpy ((void *)%s, (void *)in_struct->%s, sizeof(%s)*in_struct->%s);\n' % (member.name, member.name, m_type, member.len)
976 construct_txt += ' }\n'
977 destruct_txt += ' if (%s)\n' % member.name
978 destruct_txt += ' delete[] %s;\n' % member.name
979 elif member.isstaticarray or member.len is not None:
980 if member.len is None:
981 # Extract length of static array by grabbing val between []
982 static_array_size = re.match(r"[^[]*\[([^]]*)\]", member.cdecl)
983 construct_txt += ' for (uint32_t i=0; i<%s; ++i) {\n' % static_array_size.group(1)
984 construct_txt += ' %s[i] = in_struct->%s[i];\n' % (member.name, member.name)
985 construct_txt += ' }\n'
986 else:
987 # Init array ptr to NULL
988 default_init_list += '\n %s(nullptr),' % member.name
989 init_list += '\n %s(nullptr),' % member.name
990 init_func_txt += ' %s = nullptr;\n' % member.name
991 array_element = 'in_struct->%s[i]' % member.name
992 if member.type in self.structNames:
993 member_index = next((i for i, v in enumerate(self.structMembers) if v[0] == member.type), None)
994 if member_index is not None and self.NeedSafeStruct(self.structMembers[member_index]) == True:
995 array_element = '%s(&in_struct->safe_%s[i])' % (member.type, member.name)
996 construct_txt += ' if (%s && in_struct->%s) {\n' % (member.len, member.name)
997 construct_txt += ' %s = new %s[%s];\n' % (member.name, m_type, member.len)
998 destruct_txt += ' if (%s)\n' % member.name
999 destruct_txt += ' delete[] %s;\n' % member.name
1000 construct_txt += ' for (uint32_t i=0; i<%s; ++i) {\n' % (member.len)
1001 if 'safe_' in m_type:
1002 construct_txt += ' %s[i].initialize(&in_struct->%s[i]);\n' % (member.name, member.name)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001003 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001004 construct_txt += ' %s[i] = %s;\n' % (member.name, array_element)
1005 construct_txt += ' }\n'
1006 construct_txt += ' }\n'
1007 elif member.ispointer == True:
1008 construct_txt += ' if (in_struct->%s)\n' % member.name
1009 construct_txt += ' %s = new %s(in_struct->%s);\n' % (member.name, m_type, member.name)
1010 construct_txt += ' else\n'
1011 construct_txt += ' %s = NULL;\n' % member.name
1012 destruct_txt += ' if (%s)\n' % member.name
1013 destruct_txt += ' delete %s;\n' % member.name
1014 elif 'safe_' in m_type:
1015 init_list += '\n %s(&in_struct->%s),' % (member.name, member.name)
1016 init_func_txt += ' %s.initialize(&in_struct->%s);\n' % (member.name, member.name)
1017 else:
1018 init_list += '\n %s(in_struct->%s),' % (member.name, member.name)
1019 init_func_txt += ' %s = in_struct->%s;\n' % (member.name, member.name)
1020 if '' != init_list:
1021 init_list = init_list[:-1] # hack off final comma
1022 if item.name in custom_construct_txt:
1023 construct_txt = custom_construct_txt[item.name]
Mike Schuchardt81485762017-09-04 11:38:42 -06001024 if item.name in custom_destruct_txt:
1025 destruct_txt = custom_destruct_txt[item.name]
Petr Krause91f7a12017-12-14 20:57:36 +01001026 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 -07001027 if '' != default_init_list:
1028 default_init_list = " :%s" % (default_init_list[:-1])
1029 safe_struct_body.append("\n%s::%s()%s\n{}" % (ss_name, ss_name, default_init_list))
1030 # Create slight variation of init and construct txt for copy constructor that takes a src object reference vs. struct ptr
1031 copy_construct_init = init_func_txt.replace('in_struct->', 'src.')
1032 copy_construct_txt = construct_txt.replace(' (in_struct->', ' (src.') # Exclude 'if' blocks from next line
1033 copy_construct_txt = copy_construct_txt.replace('(in_struct->', '(*src.') # Pass object to copy constructors
1034 copy_construct_txt = copy_construct_txt.replace('in_struct->', 'src.') # Modify remaining struct refs for src object
Petr Krause91f7a12017-12-14 20:57:36 +01001035 if item.name in custom_copy_txt:
1036 copy_construct_txt = custom_copy_txt[item.name]
Chris Forbesfb633832017-10-03 18:11:54 -07001037 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 -06001038 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 -07001039 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 -07001040 safe_struct_body.append("\n%s::~%s()\n{\n%s}" % (ss_name, ss_name, destruct_txt))
Petr Krause91f7a12017-12-14 20:57:36 +01001041 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 -07001042 # Copy initializer uses same txt as copy constructor but has a ptr and not a reference
1043 init_copy = copy_construct_init.replace('src.', 'src->')
1044 init_construct = copy_construct_txt.replace('src.', 'src->')
Mark Lobodzinski5cd08512017-09-12 09:50:25 -06001045 safe_struct_body.append("\nvoid %s::initialize(const %s* src)\n{\n%s%s}" % (ss_name, ss_name, init_copy, init_construct))
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001046 if item.ifdef_protect != None:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001047 safe_struct_body.append("#endif // %s\n" % item.ifdef_protect)
1048 return "\n".join(safe_struct_body)
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001049 #
John Zulaufde972ac2017-10-26 12:07:05 -06001050 # Generate the type map
1051 def GenerateTypeMapHelperHeader(self):
1052 prefix = 'Lvl'
1053 fprefix = 'lvl_'
1054 typemap = prefix + 'TypeMap'
1055 idmap = prefix + 'STypeMap'
John Zulaufde972ac2017-10-26 12:07:05 -06001056 type_member = 'Type'
1057 id_member = 'kSType'
Mike Schuchardt97662b02017-12-06 13:31:29 -07001058 id_decl = 'static const VkStructureType '
John Zulaufde972ac2017-10-26 12:07:05 -06001059 generic_header = prefix + 'GenericHeader'
1060 typename_func = fprefix + 'typename'
1061 idname_func = fprefix + 'stype_name'
1062 find_func = fprefix + 'find_in_chain'
John Zulauf65ac9d52018-01-23 11:20:50 -07001063 init_func = fprefix + 'init_struct'
John Zulaufde972ac2017-10-26 12:07:05 -06001064
1065 explanatory_comment = '\n'.join((
1066 '// These empty generic templates are specialized for each type with sType',
1067 '// members and for each sType -- providing a two way map between structure',
Mike Schuchardt97662b02017-12-06 13:31:29 -07001068 '// types and sTypes'))
John Zulaufde972ac2017-10-26 12:07:05 -06001069
1070 empty_typemap = 'template <typename T> struct ' + typemap + ' {};'
1071 typemap_format = 'template <> struct {template}<{typename}> {{\n'
John Zulaufde972ac2017-10-26 12:07:05 -06001072 typemap_format += ' {id_decl}{id_member} = {id_value};\n'
1073 typemap_format += '}};\n'
1074
1075 empty_idmap = 'template <VkStructureType id> struct ' + idmap + ' {};'
1076 idmap_format = ''.join((
1077 'template <> struct {template}<{id_value}> {{\n',
1078 ' typedef {typename} {typedef};\n',
John Zulaufde972ac2017-10-26 12:07:05 -06001079 '}};\n'))
1080
1081 # Define the utilities (here so any renaming stays consistent), if this grows large, refactor to a fixed .h file
1082 utilities_format = '\n'.join((
1083 '// Header "base class" for pNext chain traversal',
1084 'struct {header} {{',
1085 ' VkStructureType sType;',
1086 ' const {header} *pNext;',
1087 '}};',
1088 '',
1089 '// Find an entry of the given type in the pNext chain',
1090 'template <typename T> const T *{find_func}(const void *next) {{',
1091 ' const {header} *current = reinterpret_cast<const {header} *>(next);',
1092 ' const T *found = nullptr;',
1093 ' while (current) {{',
1094 ' if ({type_map}<T>::{id_member} == current->sType) {{',
1095 ' found = reinterpret_cast<const T*>(current);',
1096 ' current = nullptr;',
1097 ' }} else {{',
1098 ' current = current->pNext;',
1099 ' }}',
1100 ' }}',
1101 ' return found;',
1102 '}}',
John Zulauf65ac9d52018-01-23 11:20:50 -07001103 '',
1104 '// Init the header of an sType struct with pNext',
1105 'template <typename T> T {init_func}(void *p_next) {{',
1106 ' T out = {{}};',
1107 ' out.sType = {type_map}<T>::kSType;',
1108 ' out.pNext = p_next;',
1109 ' return out;',
1110 '}}',
1111 '',
1112 '// Init the header of an sType struct',
1113 'template <typename T> T {init_func}() {{',
1114 ' T out = {{}};',
1115 ' out.sType = {type_map}<T>::kSType;',
1116 ' return out;',
1117 '}}',
1118
Mike Schuchardt97662b02017-12-06 13:31:29 -07001119 ''))
John Zulaufde972ac2017-10-26 12:07:05 -06001120
1121 code = []
John Zulauf65ac9d52018-01-23 11:20:50 -07001122
1123 # Generate header
John Zulaufde972ac2017-10-26 12:07:05 -06001124 code.append('\n'.join((
1125 '#pragma once',
1126 '#include <vulkan/vulkan.h>\n',
1127 explanatory_comment, '',
1128 empty_idmap,
John Zulauf65ac9d52018-01-23 11:20:50 -07001129 empty_typemap, '')))
John Zulaufde972ac2017-10-26 12:07:05 -06001130
1131 # Generate the specializations for each type and stype
John Zulaufde972ac2017-10-26 12:07:05 -06001132 for item in self.structMembers:
1133 typename = item.name
1134 info = self.structTypes.get(typename)
1135 if not info:
1136 continue
1137
1138 if item.ifdef_protect != None:
1139 code.append('#ifdef %s' % item.ifdef_protect)
1140
1141 code.append('// Map type {} to id {}'.format(typename, info.value))
1142 code.append(typemap_format.format(template=typemap, typename=typename, id_value=info.value,
Mike Schuchardt97662b02017-12-06 13:31:29 -07001143 id_decl=id_decl, id_member=id_member))
1144 code.append(idmap_format.format(template=idmap, typename=typename, id_value=info.value, typedef=type_member))
John Zulaufde972ac2017-10-26 12:07:05 -06001145
1146 if item.ifdef_protect != None:
1147 code.append('#endif // %s' % item.ifdef_protect)
1148
John Zulauf65ac9d52018-01-23 11:20:50 -07001149 # Generate utilities for all types
1150 code.append('\n'.join((
1151 utilities_format.format(id_member=id_member, id_map=idmap, type_map=typemap,
1152 type_member=type_member, header=generic_header, typename_func=typename_func, idname_func=idname_func,
1153 find_func=find_func, init_func=init_func), ''
1154 )))
1155
John Zulaufde972ac2017-10-26 12:07:05 -06001156 return "\n".join(code)
1157
1158 #
Mark Lobodzinski7ada59c2016-12-27 11:11:54 -07001159 # Create a helper file and return it as a string
1160 def OutputDestFile(self):
Mark Lobodzinski46d388f2016-12-28 10:46:26 -07001161 if self.helper_file_type == 'enum_string_header':
Mark Lobodzinski1a2f1a32016-12-28 15:41:15 -07001162 return self.GenerateEnumStringHelperHeader()
Mark Lobodzinskie20e4562017-01-03 11:14:26 -07001163 elif self.helper_file_type == 'safe_struct_header':
1164 return self.GenerateSafeStructHelperHeader()
1165 elif self.helper_file_type == 'safe_struct_source':
1166 return self.GenerateSafeStructHelperSource()
Mark Lobodzinski7cb7da32017-04-03 16:58:04 -06001167 elif self.helper_file_type == 'object_types_header':
1168 return self.GenerateObjectTypesHelperHeader()
Mark Lobodzinskiaf86c382017-06-01 07:42:13 -06001169 elif self.helper_file_type == 'extension_helper_header':
1170 return self.GenerateExtensionHelperHeader()
John Zulaufde972ac2017-10-26 12:07:05 -06001171 elif self.helper_file_type == 'typemap_helper_header':
1172 return self.GenerateTypeMapHelperHeader()
Mark Lobodzinski71f1ea12016-12-29 10:23:47 -07001173 else:
Mark Lobodzinskic67efd02017-01-04 09:16:00 -07001174 return 'Bad Helper File Generator Option %s' % self.helper_file_type
Mark Lobodzinskif36e58b2016-12-29 14:04:15 -07001175