Tutorial Render with Blender/fr: Difference between revisions

From FreeCAD Documentation
(Created page with "Vous pouvez basculer entre la vue caméra et la fenêtre 3D en appuyant sur {{KEY|0}} dans le pavé numérique; appuyer sur {{KEY|F12}} rendra la vue de la caméra à tout mom...")
(Created page with "8.2. Si la caméra semble très petite dans la fenêtre 3D, allez dans le panneau {{incode|Properties}}, puis {{incode|Object Data}}, puis {{incode|Viewport Display}}, et déf...")
Line 146: Line 146:
Vous pouvez basculer entre la vue caméra et la fenêtre 3D en appuyant sur {{KEY|0}} dans le pavé numérique; appuyer sur {{KEY|F12}} rendra la vue de la caméra à tout moment.
Vous pouvez basculer entre la vue caméra et la fenêtre 3D en appuyant sur {{KEY|0}} dans le pavé numérique; appuyer sur {{KEY|F12}} rendra la vue de la caméra à tout moment.


8.2. If the camera looks very small in the 3D viewport, go to the {{incode|Properties}} panel, then {{incode|Object Data}}, then {{incode|Viewport Display}}, and set a larger value for the {{incode|Size}}, for example, {{incode|20 mm}}. Also activate the {{incode|Limits}} checkbox to see the clipping distance of the camera.
8.2. Si la caméra semble très petite dans la fenêtre 3D, allez dans le panneau {{incode|Properties}}, puis {{incode|Object Data}}, puis {{incode|Viewport Display}}, et définissez une valeur plus grande pour le {{incode|Size}}, par exemple, {{incode|20 mm}}. Cochez également la case {{incode|Limits}} pour voir la distance de coupure de la caméra.


{{Code|code=
{{Code|code=

Revision as of 10:17, 17 January 2021

Other languages:
Tutoriel
Thème
Rendering
Niveau
Intermédiaire
Temps d'exécution estimé
60 minutes
Auteurs
vocx
Version de FreeCAD
0.18 ou ultérieure
Fichiers exemples
none
Voir aussi
None

Introduction

Ce tutoriel montre comment produire une image rendue dans Blender, à partir d'une pièce ou d'un assemblage créé avec FreeCAD. Il suppose que l'utilisateur a déjà créé la pièce dans FreeCAD, ou l'a importée dedans. Ensuite, cette partie est exportée vers Blender pour le rendu.

Il produit un rendu avec Blender 2.80 avec les moteurs de rendu EEVEE et Cycles. Il montre diverses commandes Python qui peuvent être utilisées pour effectuer des actions plus rapidement à la fois dans FreeCAD et Blender.

Une description similaire de ce processus est décrite dans une série de vidéos, Render Solidworks and FreeCAD Models in Blender par Joko Engineering.

Remarque: un moyen plus rapide de rendre des modèles dans Blender sans quitter FreeCAD peut être réalisé via module de rendus



FreeCAD

1. Créez un assemblage en utilisant des corps de l'atelier Part ou atelier PartDesign, ou de tout autre atelier produisant des objets solides, par exemple, l'atelier Arch . Attribuez des couleurs ou des matériaux aux corps individuels qui composent l'assemblage, en correspondant approximativement à la couleur souhaitée dans votre rendu.

Assemblage de trois corps créés dans FreeCAD avec des couleurs ou des matériaux choisis.

2. Si votre modèle est très détaillé, assurez-vous que la valeur VueDeviation du corps est défini sur une valeur basse comprise entre 0.1 et 00.1 voire moins. Plus cette valeur est basse, plus le maillage exporté sera détaillé et donc meilleure sera la qualité du rendu.

Propriété de déviation des corps créés dans FreeCAD. L'écart doit être faible pour pouvoir exporter les pièces avec une bonne résolution.

3. Sélectionnez Part, puis Fichier → Exporter, ou appuyez sur Ctrl + E, et exportez-le sous Wavefront OBJ.

Alternativement, l'exportation peut être effectuée depuis la console Python. Définissez une liste d'objets à exporter et utilisez la fonction d'exportation avec un nom de fichier.

import importOBJ
objs = FreeCAD.ActiveDocument.getObjectsByLabel("Part")[0]

importOBJ.export(objs, "/home/user/assembly.obj")

Remarque: lors de l'exportation vers OBJ, deux fichiers sont créés; le premier contient les informations du maillage lui-même, assembly.obj; le second contient la définition des matériaux, qui dans la plupart des cas est juste la couleur, assembly.mtl.

Remarque 2: si le fichier OBJ résultant semble vide, vous devrez peut-être exporter les corps individuels. Dans ce cas, sélectionnez chacun des corps sous la pièce et répétez l'exportation.

import importOBJ
objs = [FreeCAD.ActiveDocument.getObjectsByLabel("Body.base")[0],
FreeCAD.ActiveDocument.getObjectsByLabel("Body.bolt")[0],
FreeCAD.ActiveDocument.getObjectsByLabel("Body.bolt.big")[0]]

importOBJ.export(objs, "/home/user/assembly.obj")

Blender

Préparez le modèle

4. Ouvrez Blender. Changez le panneau Timeline dans une console Python (Shift+F4). Cela vous aidera à saisir des commandes et à voir les résultats. Vous pouvez diviser ce panneau, pour garder la console d'un côté, et faire de l'autre division un panneau Info; cela vous permettra de voir le code des actions en cliquant sur l'interface.

Assurez-vous que vous utilisez le moteur de rendu EEVEE. Dans le panneau Properties, allez dans Render, et pour Render Engine sélectionnez Eevee.

bpy.context.scene.render.engine = 'BLENDER_EEVEE'

5. Importez le fichier de modèle à partir du menu, Fichier → Importer → Wavefront (.obj).

Alternativement, l'importation peut être effectuée à partir de la console Python.

obj_file = "/home/user/assembly.obj"
bpy.ops.import_scene.obj(filepath=obj_file)

6. Modifiez l'échelle.

Si les corps semblent très grands, vous devrez peut-être changer les unités pour que les objets apparaissent à la bonne échelle.

Dans le panneau Properties, allez dans Scene, Units, et sélectionnez le Unit System, Unit Scale, et Length.

Pour les petites pièces, vous pouvez conserver la longueur à Millimeters et l'échelle à 0.001. Pour les pièces plus volumineuses, par exemple le modèle d'un bâtiment, vous devrez peut-être définir ces valeurs sur Meters et 0.001. Essayez d'autres valeurs d'échelle si nécessaire.

Cela peut également être défini depuis la console Python.

bpy.context.scene.unit_settings.length_unit = 'MILLIMETERS'
# or bpy.context.scene.unit_settings.length_unit = 'METERS'
bpy.context.scene.unit_settings.scale_length = 0.001

Remarque: changer l'échelle et les unités de la scène n'est nécessaire que si vous souhaitez travailler avec des objets à leurs dimensions réelles. Si vous souhaitez simplement rendre votre scène rapidement, vous pouvez omettre tout ajustement.

6.1. Si vous effectuez un zoom arrière et que la vue coupe les pièces importées, vous devrez peut-être ajuster les valeurs des vignettes de la vue.

Appuyez sur N pour afficher le panneau auxiliaire; Accédez à la section View et définissez End sur une valeur élevée, par exemple 1E6 mm ou 1000 m.

6.2. Si vous le souhaitez, ajustez également la taille de la grille; allez à Overlays, puis Guides, et définissez Scale de la grille sur 0.001.

7. Réglez la rotation des objets.

Une fois importés, les objets peuvent apparaître pivotés autour de l'un des axes, par exemple à 90 degrés autour de l'axe X. Appuyez sur N pour afficher le panneau auxiliaire; sélectionnez un objet, accédez à la section Transform et définissez Rotation sur dans chaque champ. Faites ceci pour chaque objet.

Cela peut être automatisé par un petit script qui définit simplement la rotation de chaque corps importé à zéro, à l'exception des objets à l'intérieur du tuple fixed_objs. Cela peut être utile si vous importez des objets dans une scène existante où d'autres objets sont déjà dans leurs bonnes positions.

fixed_objs = ('Camera', 'Cube', 'Light')

for obj in bpy.data.objects:
    if any(s for s in fixed_objs if s in obj.name):
        print('%s %s  [[No change]]' % (obj.name, obj.rotation_euler))
        continue
    else:
        obj.rotation_euler = (0, 0, 0)
        print('%s %s  ... rotated' % (obj.name, obj.rotation_euler))

Assemblage créé dans FreeCAD importé dans Blender; le modèle a été tourné et les unités de la scène ont été ajustées pour correspondre aux objets importés.

Préparez la caméra de la scène

8. Réglez la caméra dans la bonne position.

Ajustez la fenêtre pour regarder le modèle dans l'orientation souhaitée, puis appuyez sur Ctrl+Alt+0 (pavé numérique), ou utilisez le menu Affichage → Aligner la vue → Aligner la caméra active sur la vue.

8.1. Si vous ne voyez rien dans la vue de la caméra, vous devrez peut-être ajuster le découpage. En sélectionnant la caméra dans Outliner, allez dans le panneau Properties, puis Object Data, puis Lens, puis définissez Clip End à une valeur élevée, par exemple 1E3 mm ou 1000 m.

bpy.context.object.data.clip_end = 1e+03

Si vous pouvez voir l'objet à travers la vue de la caméra, vous pouvez maintenant rendre rapidement le modèle en appuyant sur F12, ce qui ouvrira Image Editor avec le résultat. Appuyez sur Echap pour quitter et revenir à 3D Viewport.

Premier rendu de l'assemblage dans Blender, avec la caméra avec un découpage correct mais sans éclairage

Vous pouvez basculer entre la vue caméra et la fenêtre 3D en appuyant sur 0 dans le pavé numérique; appuyer sur F12 rendra la vue de la caméra à tout moment.

8.2. Si la caméra semble très petite dans la fenêtre 3D, allez dans le panneau Properties, puis Object Data, puis Viewport Display, et définissez une valeur plus grande pour le Size, par exemple, 20 mm. Cochez également la case Limits pour voir la distance de coupure de la caméra.

bpy.context.object.data.display_size = 20
bpy.context.object.data.show_limits = True

Prepare the lighting of the scene

9. Select the light in the Outliner, go to the Properties panel, then Object Data, then press on Sun, and set the Strength to 5.0.

bpy.context.object.data.type = 'SUN'
bpy.context.object.data.energy = 5

This will turn the light into a Sun lamp. This type of lamp emits an infinite number of parallel light rays that all arrive to the scene with a fixed angle.

You may position the Sun lamp anywhere on the viewport above your model so that you define the direction of the rays of light. For a Sun lamp it doesn't matter how close or far you place the lamp, only the direction of the rays, which are defined by the rotation of the Light object.

bpy.context.active_object.location = (150, 100, 100)
bpy.context.active_object.rotation_euler = (0.6, 0.05, 1.88)

Press F12 again to see a preliminary render of the model.

Render of the assembly in Blender with a Sun lamp added that emits parallel light rays with a fixed angle

More setup: floor, global lighting, reflections, and soft shadows

10. Add a floor plane. Press Shift+A then choose Mesh, Plane, and give it dimensions about 10 times larger than your model. This mesh object will serve as a floor plane or table top on which the model is standing. Also move the plane a bit down so that it does not intersect the model; -1 mm below the object is enough.

bpy.ops.mesh.primitive_plane_add(size=1500, view_align=False, enter_editmode=False, location=(0, 0, -1))

11. Set the world illumination. In the Properties panel go to World, and set Color to a light blue-gray value, RGB (0.358, 0.512, 0.527), and set the Strength to 0.3.

12. Set reflections and shadows. The EEVEE renderer of Blender produces fast renders by deactivating most effects initially. In order to obtain better images, some options need to be made active.

Go to the Properties panel, then Render, and check Screen Space Reflections. In the Shadows section, also check Soft Shadows.

bpy.context.scene.eevee.use_ssr = True
bpy.context.scene.eevee.use_soft_shadows = True

Set the materials of the objects

13. Turn the Python Console panel into a Shader Editor panel (Shift+F3).

13.1. Select the ground plane, go to the Properties panel, then Material, and click on New. In the Shader Editor a Principled BSDF node should appear. Give it a beige Base Color RGB (0.318, 0.267, 0.187), turn the Metallic slider to 0.000, and the Roughness to 1.000.

Principled BSDF shader used in Blender to simulate a variety of materials ranging from shiny metals to rough and opaque solids.

13.2. Select each of the parts of the model, and adjust the respective Principled BSDF material node. For metallic parts, turn the Metallic property all the way to 1.000. Adjust the value of Roughness to be between 0.2 and 0.7. The closer to 0.000 the Roughness is, the more reflective (mirror-like) it will appear.

For non metals, like plastics, wood and textiles, set the Metallic slider all the way to 0.000, and adjust the value of Roughness to between 0.4 and 1.0.

In general, metals are naturally smooth and therefore their roughness value is small, making them very reflective (shiny). Other materials are microscopically rough, and therefore do not reflect as much light, making them opaque.

14. Test different combinations of materials until they look acceptable. Press Z and then 8 (numerical pad) to enter Rendered mode; in this mode, the EEVEE renderer shows in real time in the 3D viewport how the final image will look like. Use Z to open the pie menu and switch back to Solid mode (Z 6), or go to LookDev mode (Z 2), a mode which adds different types of lighting to the scene to test the appearance of the materials.

Press F12 to render the view through the camera and check the quality of the image.

Rendering and saving

15. If your model looks reasonably well with the EEVEE renderer you can already save the image by going to Image → Save As or pressing Shift+S in the Image Editor.

Rendered assembly produced with Blender EEVEE; all materials use the Principled BSDF shader; only one Sun lamp is used, with some ambient background light.

16. If you want to improve the quality of the image, try the Cycles renderer.

Go to the Properties panel, then Render, and for Render Engine select Cycles. With the Cycles renderer, Blender will refine the image gradually until a number of iterations have passed. Every time the viewport changes the recalculation restarts.

bpy.context.scene.render.engine = 'CYCLES'

16.1. Adjust the sampling rate. Go to the Properties panel, then Render, then in the Sampling section select an appropriate number for Render and Viewport.

For the Viewport a small number of samples, in the range of 32 to 128, is generally enough to obtain a good preview of the image. For the final image, set Render to a higher number, from 128 to 2000, depending on the complexity and amount of details on the scene.

Press F12 to render the final view through the camera. Depending on your graphics card (GPU) the image should take several more seconds, or minutes, to render with Cycles than with EEVEE, but the quality of the image should be better.

17. When you are satisfied with the quality of the rendering, in the Image Editor go to Image → Save As or press Shift+S.

Rendered assembly produced with Blender Cycles; all options, materials, and lights that were used with EEVEE were kept for use with Cycles.

Rendering from the command line

18. If the scene has been completely finished, you may wish to render from outside Blender, from the operating system's command line. This can be useful to batch render different scenes in a remote system. Both EEVEE and Cycles are supported.

blender -b assembly.blend -E BLENDER_EEVEE -o //assembly_EEVEE_#### -t 3 -F PNG -x 1 -f 1
blender -b assembly.blend -E CYCLES -o //assembly_CYCLES_#### -t 3 -F PNG -x 1 -f 1

This specifies that rendering should happen in the background with -b; the rendering engine is chosen with -E; the output filename is selected with -o; the double forward slash // indicates a path relative to the input file; the hash mark # is used to indicate the frame number, padded with zeroes if necessary, for example, 0001; the number of CPU threads used in rendering is chosen with -t 3; the output file format is indicated with -F, and the -x 1 option adds automatically the extension to the name; the final option is -f 1 which indicates that only the first frame will be rendered, which is the normal case for a static scene; for animations use the -a switch to produce an image for each frame, which can then be assembled to produce a video file.

Importing plugin

Creating the intermediate Wavefront mesh (.obj) and then importing it into Blender will work in most situations. However, there is also the option of importing the FreeCAD file (.FCStd) directly into Blender by means of a plugin.

This is a Blender plugin; for it to work, Blender needs to be able to import FreeCAD as a module from the Python Console.

import FreeCAD

This is only possible if both Blender and FreeCAD are compiled against the same pythonX.Y (major and minor) version. For example, if Blender is compiled against Python 3.7, FreeCAD must be compiled against a Python 3.7 version as well. If FreeCAD is compiled against another version, for example, Python 2.7.15 or Python 3.6.7, the plugin will not work. The micro version number (third number) does not matter, that is, the plugin should work if one software is compiled against Python 3.7.5 and the other against Python 3.7.8.

In addition, the FreeCAD precompiled Python module, FreeCAD.so on Linux and FreeCAD.pyd on Windows, should be in the Python path used by Blender to import modules. This path can be set up in different ways, depending on the operating system and Python distribution.

In Blender you can see all paths searched by inspecting the sys.path variable. The FreeCAD module should be found in any of those directories.

import sys
print(sys.path)
  • A copy or symbolic link inside one of those directories could be created pointing to the FreeCAD module.
ln -s /usr/lib/freecad/lib/FreeCAD.so $HOME/.config/blender/2.80/scripts/addons

ln -s /usr/lib/freecad/lib/FreeCAD.so $HOME/.local/lib/python3.7/site-packages
  • Another possibility is adding the module directly into the path inside Blender.
import sys
sys.path.append("/usr/lib/freecad/lib/FreeCAD.so")

Final notes

EEVEE is not a physically accurate renderer, however its main strength is that it is a real time engine so it is able to produce quick renderings directly in the 3D viewport. In many cases these images have enough quality for final production, which means it is possible to obtain a good result in a very short time. In cases where complex light interactions are desired (reflections, refractions, volumetric light, and caustics) EEVEE is more limited, and requires some options and tricks to work around some of these limitations.

On the other hand, Cycles is a true raytracing renderer which means it is more accurate at calculating light paths in a scene. Cycles is the recommended renderer when the best quality is desired (photorealistic results), at the cost of more rendering time.

Both renderers can be used to leverage the advantages of each. In many cases the scene can be quickly prepared and tested with EEVEE to obtain preliminary renderings; then the same scene can be used with minor changes with Cycles in order to produce a higher quality, final rendering. In particular, when a scene that was setup with EEVEE will be used with Cycles, the lights may need to be adjusted in value and position as both renderers treat light in different ways.

Obtaining good results is highly dependent on the rendering options, the materials, and the lighting. The Principled BSDF material shader is a generic solution that works well for many cases, however, to produce truly photorealistic results, the use of texture maps and normal maps, along with careful lighting of the scene is still very important. Template:Tutorials navi/fr