Announcements
Attention for Customers without Multi-Factor Authentication or Single Sign-On - OTP Verification rolls out April 2025. Read all about it here.

Change drawing section hatch layer according to material

oliver.tilbury
Advocate

Change drawing section hatch layer according to material

oliver.tilbury
Advocate
Advocate

Hi all,

 

I'd like to know if it is possible with iLogic or VBA code to automate the process of changing the layer for hatches on 2D drawing section views according to their material.

 

I found this forum discussion here but this talks about changing the view geometry lines and hidden lines according to material:

https://forums.autodesk.com/t5/inventor-programming-ilogic/assign-layers-to-materials/td-p/2871324

 

Whereas all I want to do is in effect select the hatch region and change it’s layer to the appropriate material layer.

We use many different materials and our company standard (in AutoCAD which I am trying to replicate as closely as possible in Inventor!) is to have a different hatch colour (layer) per material.

 

At the moment in Inventor I have the hatch styles set-up as I want in the Style and Standards Editor > Material Hatch Pattern Defaults tab so the correct hatch styles are used per material when taking section views. That’s working great!

 

I also have the layers set-up as I want. For example:

Layer Name / Colour:

'MDF' / Green

'Steel' / Blue

‘Solid Timber’ / Brown

 

My current process is to manually select each hatch region of a given material (E.G. all the hatch regions for MDF) and under the Annotate tab > Format > Layer drop down change the layer to the ‘MDF’ layer.

 

It would be a beautiful thing if this could be automated at the click of a button to do the above, either by:

  1. Selected view
  2. All views on a sheet
  3. Or all views on all sheets.

Even option 1. - just by one selected view at a time - would be amazing!

 

This would only apply to hatch regions that are ‘By Material’.

I.e. so if a hatch region in the Edit Hatch Pattern dialog (that you get when you double click / Right click a hatch region > Edit) has a check mark next to 'By Material' and the material is ‘MDF’, then the code will run to change the layer on which that hatch region resides to the MDF layer.

 

Hatch regions that are not 'By Material' would be ignored.

 

I guess the code would need to be edited to map the correct material to the correct layer.

 

If a layer does not exist for a material I think a pop up message would be best to say that that hatch region layer had not been changed and to prompt the user to make the appropriate layer (and necessary mapping addition to the code) and then run it again to mop-up that remaining hatch region and put it on the appropriate layer. Or I guess it could automatically create a new layer and have a pop up message alerting to the effect. Maybe that would be better actually! 

 

Really hoping this might be possible!

 

Many thanks in advance and kind regards,

 

Oliver

0 Likes
Reply
1,288 Views
21 Replies
Replies (21)

oliver.tilbury
Advocate
Advocate

Or if anybody knows if hatch selection can be called with iLogic or VBA code that would be a start. 🤔 😄

0 Likes

WCrihfield
Mentor
Mentor

Hi @oliver.tilbury.  This might be possible to make happen by code, but I have never attempted it before, so I do not have any example code for you to try at the moment.  How it is done may depend on what version/year of Inventor you have too.  I can point out a few things that may help though.  I have not tried the code below, but you can play around with it, and see if it is going in the right direction.  It is not complete yet.  Just something to maybe get you started towards where you want to go, and some ideas.

Sub Main
	Dim oDDoc As DrawingDocument = TryCast(ThisDoc.Document, Inventor.DrawingDocument)
	If oDDoc Is Nothing Then Return
	Dim oView As DrawingView = ThisApplication.CommandManager.Pick(SelectionFilterEnum.kDrawingViewFilter, "Select a drawing view.")
	If oView Is Nothing Then Return
	Dim oDVHRs As DrawingViewHatchRegions = oView.HatchRegions
	If oDVHRs.Count = 0 Then Return
	For Each oDVHR As DrawingViewHatchRegion In oDVHRs
		If oDVHR.ByMaterial = True Then
			Dim sMaterialName As String = ""
			'maybe find out which material the model is currently set to here
			Dim oViewDoc As Inventor.Document = oView.ReferencedDocumentDescriptor.ReferencedDocument
			If TypeOf oViewDoc Is PartDocument Then
				Dim oPDoc As PartDocument = oViewDoc
				sMaterialName = oPDoc.ActiveMaterial.DisplayName
				'now get the Layer you want to use for this Material, one way or another
				Dim oMyLayer As Inventor.Layer = Nothing
				'probably need to have a NameValueMap or Dictionary (2 factor lists)
				'where material name and layer name are in pairs
				'then iterate through those, checking agains this material name, to get the layer name
				Try
					oMyLayer = oDDoc.StylesManager.Layers.Item("MyLayerName")
				Catch
					oMyLayer = oDDoc.StylesManager.Layers.Item(1).Copy("MyLayerName")
					'set the properties of this new layer now, before using it
				End Try
				'set the Layer of this hatch region in the view
				oDVHR.Layer = oMyLayer
			End If 'end of document type check (nothing if assembly)
		End If 'end of ByMaterial check
	Next 'oDVHR
	oView.Parent.Update
End Sub

 

Wesley Crihfield

EESignature

(Not an Autodesk Employee)

0 Likes

J-Camper
Advisor
Advisor

@oliver.tilbury,

I've been working on an add-in to allow solidbody level material assignments in Multi-solidbody parts, and some of the framework I have would be similar to what I think you need/want.  I took a couple things from that and added what would be needed to assign layers, as I was not changing layers.  See the Attached txt file. 

 

It currently has the user select the layer from a list to be assigned to each hatch region, by material.  You could write some mapping logic for your expected Materials and layers to automate that step.  I also have not included any clean up of un-mapped materials/Layers.

 

Let me know if you have any questions/issues.

0 Likes

oliver.tilbury
Advocate
Advocate

Hi Wesley,

 

Thanks very much for this.

 

Massively encouraging and exciting that there may be a way!

 

It was the end of the day here when I got your message and as it's now the weekend I won't be able to look at this properly until next week.

 

I can answer one of your questions though... I'm using Inventor Profesional 2024, latest release (can check the exact release number on Monday).

 

Thanks again!

 

Oliver

0 Likes

oliver.tilbury
Advocate
Advocate

Thank you very much for this @J-Camper.

 

Again, I'll take a proper look at this next week when back to work. 

 

Out of interest and as an aside: the add-in you've been working on - is that to assign different materials to different solid bodies in a multi body part? I believe that is not possible with Inventor out the box? 

I know Solidworks has this functionality. 

I work in bespoke furniture and that would be extremely handy to know more about / if there is some rabbit out of a hat to make this work! 

 

Thanks again for the reply and your code re. the material hatches. Will look at it all properly next week.

 

Oliver

 

 

0 Likes

J-Camper
Advisor
Advisor

@oliver.tilbury,

 

That's right, solidbody level materials are not a thing out of the box for Inventor.  I have wanted this functionality for a while, and started thinking of a way to implement it when Autodesk exposed HatchRegions to the API.  I work in a similar field, custom residential millwork/casework, so most of the overrides are to get a MDF/glass field panel in a solid wood door frame. 

I made get & set extension methods for a solidbody level attribute for the overridden material.  As far as Inventor knows, the solidbodies just have an attribute but this is enough for my team to store/get the information we need for shop drawings.  Currently I have these functions working:

  • Assign material to select solidbodies in a part
  • Calculate the mass of a part with respect to any overridden solidbody materials
  • Add/update material leaders to all hatch regions in select drawingviews
  • Override hatch patterns as needed in drawings
    • This one does require mapping hatch patterns to each material needed in the styles manager

I haven't built any functionality to interact from the assembly level, but they do work with ModelStates in parts.

0 Likes

oliver.tilbury
Advocate
Advocate

Hi @J-Camper , @WCrihfield,

 

I just wanted to message to say I have not forgotten about this thread!

 

I have been very busy over the last few weeks on getting a project completed to 'showcase' Inventor to my colleagues so have not had a chance to give proper time to working out this 'change hatch layer according to material' dilemma. 

 

I tried the above codes very quickly shortly after you sent them but to be totally honest I don't know what I'm doing so have little ability to adapt and develop the code to get it to do what I want.

 

I'm trying to watch YouTube videos to help learn iLogic and am dabbling with code snippets I'm finding online to achieve simpler tasks but who knows when I'll be able to just write code form my fingertips. That's the dream! 

 

Anyway - thanks again and hopefully I can look at this again soon(ish!),

 

Oliver

0 Likes

oliver.tilbury
Advocate
Advocate

Hi @WCrihfield , @J-Camper,

 

I'm once again trying to make some code that will cycle though all the hatch regions in a section view and assign them to the correct layer depending on the material.

 

I'm really banging my head against the wall here as haven't been able to make either of your codes work I'm afraid. 

 

I have no doubt this is a me issue rather then the code but even if I paste in specific material and layer names, nothing is happing. 

 

I've also tried copying in some of your code into this code here by @brianM328K but again to no avail.

 

I have a section through an assembly with numerous parts with various materials. Of course it would be good if the code eventually works for drawings of just simple single part sections but for now drawings sectioning full assemblies with sub-parts with different materials is what I am really trying to process.

 

Am I missing something simple in either of your codes to get them to start to working for me?

 

Thanks MASSIVELY in advance for any further help you can give.

 

 

Oliver

 

0 Likes

J-Camper
Advisor
Advisor

@oliver.tilbury,

What kind of error message do you get when you run the code I posted?

Can you post your current attempt?

0 Likes

oliver.tilbury
Advocate
Advocate

Hi @J-Camper,

 

I'm getting this error message:

 

Error on line 138 in rule: Hatch Layers, in document: Table Assembly

Public member 'ActiveMaterial' on type 'AssemblyDocument' not found.

 

 

Is the code set up to handle sections through assemblies?

 

Thank you.

0 Likes

J-Camper
Advisor
Advisor

@oliver.tilbury 

 

Yes it is set up to handle sections of assemblies.  I believe I also ran into errors there when I started playing with assembly level cut features.  The solid bodies would no longer return back to part level and were stuck in assembly level.  I could not find a way to get material from bodies that were affected this way, so I simply filter them out.

 

We don't use assembly cut features as standard so it is not an issue for me, but if you do use them regularly then you will have to try to dig deeper than i did.

 

If you just want to ignore those solids then you can add these lines just above Line 138:

 

		If Not HatchBody.IsSolid Then Continue For
		If HatchBody.Name = String.Empty Then Continue For 'Added for assembly cuts?
		If HatchBody.Parent.Document.DocumentType <> DocumentTypeEnum.kPartDocumentObject Then Continue For 'Added for assembly cuts also?

 

You likely don't need them all, but i added each as i was trying to narrow down how to avoid the affected solid bodies, and left them in as they did not conflict with anything else.

0 Likes

oliver.tilbury
Advocate
Advocate

Hi @J-Camper,

 

Thanks for that. Yes that is staring to get it to work now but it's not changing the layers for all the hatch regions for some reason 🤔. It's also changing some hatch regions of a material but not all (i.e. it changed a couple of the hatch regions with the associated material 'MDF' to the MDF layer but not all of them).

 

To be totally honest I don't really understand the issue you are explaining in your previous message.

 

I have thought of another way to tackle this problem though! 🤞

 

If some of the difficulty is in accessing the part material associated with the hatch region (1 ↓) - is it (?), then it may actually be better in any case to set the hatch layer according to the hatch pattern name (2 ↓) as I have created custom hatch patterns for all my standard materials so that I could control the angle and scale better for each hatch style per material as found the controls in the Style and Standards Manger a little bit limited. 

 

olivertilbury_0-1734086194962.png

 

As mentioned previously, I liked the look of the code I found on this tread and was wondering if some of this principle could be taken to iterate through all the hatch regions and if the hatch pattern name = 'PatternMaterial1' then the layer will = 'LayerMaterial1'.

 

I have VERY crudely blundered through that code, taken out the extra bits and shoe-horned in a sketch-out of what I think the method could be. 

 

The key parts of this coding abomination being:

 

olivertilbury_1-1734086888214.png

 

I know this is an affront to all things coding but I'm hoping there is a way through here and sure there must be a good solution to this.

Maybe over Christmas I can have some time to start following some proper coding iLogic / VB.net courses tutorials as finding it very frustrating not understanding the anatomy of how code interacts with the program. 😬 I think I can just chop things in but of course this never works! 😭

 

Thanks again.

 

 

 

 

0 Likes

J-Camper
Advisor
Advisor

@oliver.tilbury,

So inside the assembly environment you can sketch and create "Cut" features, like extrusions.  From my testing, whenever you create a cut feature that affects a Part Occurrence in the Assembly,  it creates an assembly level "Result" SurfaceBody object for every body in the affected part.  This assembly level body overrides all references and does not allow access to the original part level body.  This means that we lose the API reference to the material since the Assembly body will not have access to a material property through it's component definition.  Inventor still knows internally what the material is because the hatch region will be correct in the drawing, but they way I currently dig back from hatch region to material property is obstructed by the existence of the "Result" Body in the assembly level.

If you do modify your models at the assembly level like i mentioned above, and the error message shares leads me to believe, then in makes sense that some regions are skipped.  The three lines i posted to add skip the "Result" bodies at the assembly level. 

If you do not modify your bodies at the assembly level, but my posted code was still returning an AssemblyComponentDefinition from the "HatchBody" ObjectVariable, then I would really like to look closer at your working set.  I have not found a way to get this error other than what i mentioned above, so I would like to make my code more robust if there are other situations in which it can occur.

I will separate this part of my response to keep the post smaller and reply to your request for help with the code you posted just after this.

0 Likes

J-Camper
Advisor
Advisor

@oliver.tilbury,

I would suggest building a NameValueMap to "Link" the Pattern names to Layer names then you can loop through and check the pattern name against the map and set the value accordingly.  Like this:

Sub Main
'[	*** Checks DWG is active ***
	If ThisApplication.ActiveDocumentType <> DocumentTypeEnum.kDrawingDocumentObject Then
	MsgBox("A Drawing Document must be active for this rule to work. Exiting.",vbCritical, "Wrong Document Type")
	Exit Sub
	End If
']

'[Prep only done once:
'DocumentReference:
Dim dDoc As DrawingDocument = ThisApplication.ActiveDocument
'Collection Of Layers
Dim ActiveDrawingLayers As ObjectCollection = ThisApplication.TransientObjects.CreateObjectCollection(dDoc.StylesManager.Layers)
'Build a name value map to link the Pattern names to layer names
Dim HatchLayerMap As NameValueMap = ThisApplication.TransientObjects.CreateNameValueMap
HatchLayerMap.Add("PTN - MDF", "Material - MDF")
HatchLayerMap.Add("PTN - BIRCH PLY", "Material - Birch Ply")
HatchLayerMap.Add("PTN - STAINLESS STEEL", "Material - Stainless Steel")
'Repeat to build your entire library
']


'[	*** Select a view to adjust ***
View:
	Dim oView As DrawingView = ThisApplication.CommandManager.Pick(SelectionFilterEnum.kDrawingViewFilter, "Select a View to Edit.")
		If oView Is Nothing Then
		Exit Sub
		End If
']
'[	*** Set Perameters ***
On Error GoTo ErrorMsg
	If oView.ViewType = DrawingViewTypeEnum.kSectionDrawingViewType Then
	Dim oSecView As SectionDrawingView = oView
		If oSecView.HatchRegions.Count > 0 Then

'[	*** Set Hatch Layer according to hatch pattern name***

ChangeHatchLayer:
On Error Resume Next 'I don't like doing this because it hides errors
			For Each oHR As DrawingViewHatchRegion In oSecView.HatchRegions
				Dim PatternLayer As Inventor.Layer = Nothing
				For i = 1 To HatchLayerMap.Count
					If HatchLayerMap.Name(i) <> oHR.Pattern.Name Then Continue For
					For Each DL As Inventor.Layer In ActiveDrawingLayers
						If DL.Name <> HatchLayerMap.Value(HatchLayerMap.Name(i)) Then Continue For
						PatternLayer = DL
						Exit For
					Next
					Exit For
				Next
				If PatternLayer Is Nothing Then Logger.Debug("Pattern Name: " & oHR.Pattern.Name & " was not mapped to a Layer") : Continue For
				oHR.Layer = PatternLayer
			Next
		End If
	End If
				'*** ROUTINE END ***
']
'Normal Exit :
Exit Sub

'[	*** Error message ***
ErrorMsg :
	MessageBox.Show("An Error Has Occured. Now exiting", "Hatch Properties",MessageBoxButtons.OK, MessageBoxIcon.Error)
'	GoTo Options
	Exit Sub
	

']
End Sub
'[	*** Furtrher Options ***
					
					'oHR.Angle					'Read/Write - Double
					'oHR.ByMaterial				'Read/Write - Boolean
					'oHR.Color					'Read/Write - Color object
					'oHR.DoublePattern			'Read/Write - Boolean
					'oHR.HatchAreas				'Read Only - DrawingViewHatchAreas object
					'oHR.Layer					'Read/Write - Layer object
					'oHR.LineWeight				'Read/Write - Double
					'oHR.Pattern				'Read/Write - DrawingHatchPattern object
					'oHR.Pattern = oDDoc.DrawingHatchPatternsManager.Item("ANSI 31")
					'oHR.Scale					'Read/Write - Double
					'oHR.Shift					'Read/Write - Double
					'oHR.Visible				'Read/Write - Boolean
']

I tried to leave as much of the code the way you had it previously, even though i would have done things differently.  I added asection at the top to build the map and collect the available drawing layers, then i modified the section you highlighted to use the map.  I was not able to fully test this since I don't have the patterns/layers you have but I think it should work fine

Let me know if you have any questions or if it is not working as intended

oliver.tilbury
Advocate
Advocate

Hi @J-Camper 

 

Ok. But are we talking cross purposes here?

 

I'm not doing assembly level cut features to create section views (not sure why I'd do that).

 

But am instead talking about creating 2D section elevations in a DWG Inventor drawing using the normal section tool:

 

olivertilbury_0-1734103167695.png

 

Are we talking cross purposes or am I confused  - again?! 🙂

 

Cheers

 

0 Likes

oliver.tilbury
Advocate
Advocate

My last message in response to your first message above.

 

About to look at the above with the latest code next! 🙂

0 Likes

J-Camper
Advisor
Advisor

not in the drawing, in the assembly:

JCamper_0-1734103472770.png

*Edit:
everyone of the SurfaceBodies in everyone of the occurrences affected by that assembly level cut feature will now return as an assembly level SurfaceBody with no API link to the original Part Body.

 

0 Likes

oliver.tilbury
Advocate
Advocate

Ok. So I think we are talking cross purposes to some extent. 😂

 

So do you take assembly level cuts and then use these to get your section elevation views in 2D drawings? 🤔

 

I occasionally do this but only really to create fancy 3D partially-sectioned views for use in 2D drawing layout perspective views.

 

Regular 2D section elevations I would simply use the drawing section tool (and other related tools like Breakout views) to create my section elevations and details on the 2D drawing layouts.

 

 

Cheers 

0 Likes

oliver.tilbury
Advocate
Advocate

@J-Camper 

 

Wow! It works! 😁

 

I just tried your code, added a few of my actual hatch pattern and layer names and it works perfectly! 👏👏👏🙌

 

Really - thank you!

 

I have to finish soon but will add to this to build out the full library and maybe bring back in some of the code you had before (like where it asks if you want to process the hatches on a single view, a sheet or the entire drawing document which I really liked).

 

Appreciate this may not be the only, or even the best way, to do this and not how you would normally go about it but it works so that's made my day / month / year! 

 

One question on this, on line 47 you comment 'I don't like doing this because it hides errors.

What does that mean in practice?

 

Thanks again! 

 

 

 

 

 

 

0 Likes