Poradnik: Renderowanie z Blenderem

From FreeCAD Documentation
Revision as of 15:39, 4 June 2021 by Kaktus (talk | contribs) (Created page with "11. Ustaw iluminację świata. W panelu {{incode|Properties}} przejdź do {{incode|World}} i ustaw {{incode|Color}} na wartość jasnoniebiesko-szarą, {{incode|RGB (0.358, 0....")
Ćwiczenie
Temat
Renderowanie
Poziom trudności
średniozaawansowany
Czas wykonania
60 minut
Autorzy
vocx
Wersja FreeCAD
0.18 lub nowszy
Pliki z przykładami
brak
Zobacz również
-

Wprowadzenie

Ten poradnik prezentuje jak stworzyć wyrenderowany obraz w programie Blender, zaczynając od części lub zespołu stworzonego w programie FreeCAD. Zakłada on, że użytkownik stworzył już część w programie FreeCAD, lub zaimportował ją do niego. Następnie część ta jest eksportowana do Blendera w celu wyrenderowania.

Przedstawia renderowanie w Blenderze 2.80 z wykorzystaniem zarówno renderera EEVEE jak i Cycles. Demonstruje różne polecenia środowiska Python, które mogą być użyte by wykonać działania szybciej, zarówno w programie FreeCAD jak i Blender.

Podobny opis tego procesu jest zaprezentowany w serii filmów, Renderuj modele Solidworks i FreeCAD w Blenderze, autorstwa Joko Engineering.

Uwaga: szybszym sposobem na renderowanie modeli w blenderze bez opuszczania programu FreeCAD może być Projekt Render



FreeCAD

1. Stwórz złożenie, używając zawartości ze środowiska Caęść lub Projekt Części, albo dowolnego innego środowiska, które tworzy obiekty brył, na przykład Architektura. Przypisz kolory lub materiały poszczególnym zawartościom tworzącym złożenie, w przybliżeniu odpowiadające kolorowi, który chcesz uzyskać w renderingu.

Złożenie trzech brył stworzonych w programie FreeCAD, z przypisanymi kolorami lub materiałami.

2. Jeśli twój model jest bardzo szczegółowy, upewnij się, że wartość WIDOKOdchyłka zawartości jest ustawiona na niską wielkość, pomiędzy 0.1 a 0.01, lub nawet mniejszą. Im niższa jest ta wartość, tym bardziej szczegółowa będzie wyeksportowana siatka, a co za tym idzie, tym lepsza będzie jakość otrzymanego renderu.

Właściwość odchylenia zawartości utworzonych w programie FreeCAD. Wartość odchylenia musi być małe, aby można było eksportować części z dobrą rozdzielczością.

3. Wybierz środowisko Part, kolejnie z menu Plik → Eksport, lub naciśnij klawisze Ctrl + E, i wyeksportować jako OBJ.

Alternatywnie, eksport może być wykonany z konsoli Python. Zdefiniuj listę obiektów, które mają być wyeksportowane i użyj funkcji eksportującej z nazwą pliku.

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

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

Uwaga: podczas eksportu do OBJ, tworzone są dwa pliki. Pierwszy zawiera informacje o siatce, assembly.obj, drugi zawiera definicję materiałów, która w większości przypadków zawiera tylko kolor, assembly.mtl.

Uwaga 2: Jeśli wynikowy plik OBJ wydaje się być pusty, być może trzeba będzie wyeksportować poszczególne zawartości. W takim przypadku należy zaznaczyć każdą z nich pod częścią i powtórzyć eksport.

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

Przygotowanie modelu

4. Otwórz Blendera. Zmień panel Oś czasu na konsolę Python (Shift + F4). To pomoże Ci wprowadzać komendy i widzieć wyniki. Możesz podzielić ten panel tak, aby po jednej stronie pozostała konsola, a po drugiej panel Info, pozwoli ci to zobaczyć działanie kodu po kliknięciu w interfejs.

Upewnij się, że używasz renderera EEVEE. W panelu Properties przejdź do Render, i dla Render Engine wybierz Eevee.

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

5. Zaimportuj plik modelu z menu, Pilik → Import → Wavefront (.obj).

Alternatywnie, import można wykonać z poziomu konsoli Python.

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

6. Zmień skalę.

Jeśli zawartości wydają się być bardzo duże, może być konieczna zmiana jednostek, aby obiekty były wyświetlane w odpowiedniej skali.

W panelu Properties przejdź do Scene, Units i wybierz odpowiednie ustawienia Unit System, Unit Scale i Length.

Dla małych części, możesz chcieć zachować długość na Millimeters, a skalę na 0.001. W przypadku większych części, na przykład modelu budynku, może być konieczne ustawienie tych wartości na Meters i 0.001. W razie potrzeby wypróbuj inne wartości skali.

Może to być ustawione również z poziomu Python console.

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

Uwaga: Zmiana skali i jednostek sceny jest konieczna tylko wtedy, gdy chcesz pracować z obiektami w ich prawdziwych wymiarach. Jeśli chcesz tylko szybko wyrenderować scenę, możesz pominąć wszelkie regulacje.

6.1. W przypadku pomniejszenia, gdy widok przycina importowane części, może być konieczne dostosowanie wartości przycinania widoku.

Naciśnij klawisz N, aby wyświetlić panel pomocniczy. Przejdź do sekcji View i ustaw End na dużą wartość, na przykład 1E6 mm lub 1000 m.

6.2. Jeśli chcesz, możesz również dostosować rozmiar siatki. Przejdź do Overlays, następnie Guides i ustaw Scale dla tej siatki na 0.001.

7. Ustal obrót obiektów.

Po zaimportowaniu obiekty mogą być obrócone wokół wybranej osi, na przykład o 90 stopni wokół osi X. Naciśnij klawisz N, aby wyświetlić panel pomocniczy. Wybierz obiekt, przejdź do sekcji Transform i ustaw Rotation na w każdym polu. Zrób to dla każdego obiektu.

Można to zautomatyzować za pomocą małego skryptu, który po prostu ustawia rotację każdego importowanego ciała na zero, z wyjątkiem obiektów wewnątrz tupli fixed_objs. Może to być przydatne, jeśli importujesz obiekty do istniejącej sceny, gdzie inne obiekty są już we właściwych pozycjach.

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))

Zespół stworzony w programie FreeCAD zaimportowany do Blendera; model został obrócony, a jednostki sceny dopasowane do zaimportowanych obiektów.

Przygotuj ujęcie kadru

8. Ustaw ujęcie widoku we właściwej pozycji.

Dostosuj rzutnię, aby spojrzeć na model w żądanej orientacji, a następnie naciśnij klawisze Ctrl + Alt + 0 (klawiatura numeryczna), albo użyj opcji z menu View → Align View → Align Active Camera to View.

8.1. Jeśli w ujęciu widoku nic nie widać, być może trzeba dostosować przycięcie. Zaznaczając kamerę w Outliner, przejdź do panelu Properties, następnie Object Data, potem Lens, a następnie ustaw Clip End na dużą wartość, na przykład 1E3 mm lub 1000 m.

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

Jeśli widzisz obiekt w ujęciu widoku, możesz teraz szybko wyrenderować model, naciskając F12, co spowoduje otwarcie Image Editor z wynikiem. Naciśnij Esc, aby wyjść i powrócić do 3D Viewport.

Pierwszy render montażu w Blenderze, z ujęciem z poprawnym clippingiem, ale bez oświetlenia

Możesz przełączać się między ujęciem widoku a rzutnią 3D, naciskając klawisz 0 na klawiaturze numerycznej. Naciśnięcie klawisza F12 spowoduje wyświetlenie widoku z kamery w dowolnym momencie.

8.2. Jeśli ujęcie wygląda na bardzo małe w rzutni 3D, przejdź do panelu Properties, następnie Object Data, potem Viewport Display i ustaw większą wartość dla pola Size, na przykład 20 mm. Włącz także pole wyboru Limits, aby zobaczyć odległość obcinania ujęcia widoku.

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

Przygotuj oświetlenie sceny

9. Zaznacz światło w Outliner, przejdź do panelu Properties, następnie Object Data, naciśnij na Sun i ustaw Strength na 5.0.

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

Spowoduje to przekształcenie światła w lampę słoneczną. Ten typ lampy emituje nieskończoną liczbę równoległych promieni świetlnych, które docierają do sceny pod stałym kątem.

Możesz umieścić lampę słoneczną w dowolnym miejscu rzutni nad swoim modelem, tak aby określić kierunek promieni świetlnych. Dla lampy słonecznej nie ma znaczenia jak blisko lub daleko umieścisz lampę, tylko kierunek promieni, które są definiowane przez rotację obiektu Light.

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

Naciśnij ponownie klawisz F12, aby zobaczyć wstępny render modelu.

Render złożenia w Blenderze z dodaną lampą słoneczną, która emituje równoległe promienie świetlne o stałym kącie

Więcej ustawień: podłoga, oświetlenie globalne, odbicia i miękkie cienie

10. Dodaj płaszczyznę podłogi. Naciśnij klawisze Shift+A, a następnie wybierz Mesh, Plane i nadaj mu wymiary około 10 razy większe niż twój model. Ten obiekt będzie służył jako płaszczyzna podłogi lub blat stołu, na którym stoi model. Przesuń również płaszczyznę nieco w dół, tak aby nie przecinała modelu. Wystarczy -1 mm poniżej obiektu.

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

11. Ustaw iluminację świata. W panelu Properties przejdź do World i ustaw Color na wartość jasnoniebiesko-szarą, RGB (0.358, 0.512, 0.527), a także ustaw Strength na 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/pl