Outils pour utilisateurs

Outils du site


issue115:inkscape

This month we'll be looking at the last of the filter primitives available in Inkscape 0.48, Diffuse Lighting and Specular Lighting. These are used to simulate the effect of lights shining on your objects, and constitute two thirds of the Phong reflection model. The third part, Ambient Lighting, refers to light that's present everywhere in an image rather than coming from a specific light source. There's no need for a specific filter for this part as it is formed by the fill and stroke colors of the objects in your image. Diffuse Light refers to the general light and shadow on an object that doesn't change significantly as you move your viewpoint. Specular Light, on the other hand, refers to the bright spots or reflections that shift and change as you move. Look at a shiny object near you and move your head around to see the difference – notice the specular highlights on edges and corners that move with you, and the diffuse shadows and glows of the main body of the object that remain largely unchanged. To begin, create an object or group to apply the filter to, and then add a Diffuse Lighting primitive in the usual way. There are a few parameters to modify, but mostly it's a case of moving sliders by trial-and-error in order to achieve the result you want.

Ce mois-ci, nous examinerons les dernières primitives de filtrage disponibles dans Inkscape 0.48, Lumière diffuse et Lumière spéculaire. Elles sont utilisées pour simuler l'effet de la lumière brillante sur vos objets et constituent les deux tiers du modèle de réflexion Phong. La troisième partie, Lumière ambiante, fait référence à la lumière qui est présente en tous points d'une image plutôt qu'à celle venant d'une source de lumière particulière. Il n'y a pas besoin d'un filtre spécifique pour cette partie, car elle est formée par les couleurs de remplissage et de contour des objets de votre image.

Lumière diffuse fait référence à l'éclairage et l'ombrage généraux sur un objet, qui ne se modifient pas significativement quand vous déplacez votre point de vue. Lumière spéculaire, au contraire, fait référence aux points et reflets brillants qui tournent et se déplacent quand vous bougez. Regardez un objet brillant près de vous et déplacez votre tête pour voir la différence : notez que les éclats réfléchis par les bords et les coins bougent avec vous et que les ombres et reflets diffus sur le corps principal de l'objet restent largement inchangés.

Pour commencer, créez un objet ou un groupe auquel appliquer le filtre et ajoutez ensuite la primitive Lumière diffuse de la façon habituelle. Il y a quelques paramètres modifiables, mais pour la plupart, il s'agit de déplacer les réglettes par tâtonnements de manière à obtenir le résultat que vous recherchez.

The first parameter to choose is the color of your light. This has a huge effect on the output of the filter, as the lighting effect completely replaces the original color of your objects, rather than mixing with the underlying hues. In the example that follows, all the text objects are teal (a blue-green color), but the color used in the filters is yellow. Notice that no teal appears in the output images. In practice, it's only the alpha channel of the input image that's used by this primitive – so it doesn't matter whether you connect it to the full Source Graphic or just the Source Alpha, the result will be the same. The alpha channel is used as a “bump map” to determine each pixel's position along the z-axis – more opaque areas protrude further from the background. The Surface Scale and Constant sliders can be used to scale and offset the alpha values in order to alter the apparent depth of the object. The Kernel Unit Length parameter can be largely ignored. It's not used by Inkscape, but may have an effect on other SVG viewers, where it's used to define the size of the pixel grid used for the filter calculations. I usually just leave it at zero.

Le premier paramètre à choisir est la couleur de la lumière. Celle-ci a un énorme effet sur la sortie du filtre, car l'effet d'éclairage remplace complètement la couleur originale de vos objets, plutôt que de se mélanger avec les teintes sous-jacentes. Dans l'exemple qui suit, tous les objets texte sont bleu sarcelle (une couleur bleu-vert), mais la couleur utilisée dans les filtres est jaune. Notez qu'aucun bleu sarcelle n'apparaît dans les images de sortie.

En pratique, seul le canal alpha de l'image d'entrée est utilisé par cette primitive ; aussi, le fait d'être connecté à la Source image ou à l'Opacité de la source n'a aucune importance : le résultat est le même. Le canal alpha est utilisé comme une « carte en relief » pour déterminer la position de chaque pixel le long de l'axe z ; les zones plus opaques ressortent du fond. Les réglettes Relief de surface et Constante peuvent être utilisées pour mettre à l'échelle et décaler les valeurs alpha de façon à modifier la profondeur apparente de l'objet.

Le paramètre Unité de longueur du kernel peut être largement ignoré. Il n'est pas utilisé par Inkscape, mais peut avoir de l'effet dans d'autres visionneuses SVG, où il sert à définir la taille de la grille des pixels utilisée pour les calculs de filtrage. Je le laisse habituellement à zéro.

Finally, it's time to choose the type of light source: Distant, Point, or Spot. The first indicates a light source that is an infinite distance from your object, such that all the rays of light that arrive are parallel to one another. The Azimuth parameter sets the location of the light source as an angle – 0° places it to the right of your object, with increasing values moving it clockwise around the image until 360° puts it back at the right again. Drag this slider to see the effect in real-time. The Elevation parameter sets the angle to the drawing plane: imagine a light sitting flush with your computer screen at 0° (casting low, dark shadows); as you move the slider towards 90°, the light swings out of the monitor, towards you, until it's directly over your objects; continue towards 180° and it carries on following the same arc until it's flush with the monitor on the opposite side of your image; any further values continue moving the light in a semicircle behind the monitor, and tend to not be particularly useful. Specifying two polar values like this defines a bearing in three-dimensional space. If you ever watch an episode of Star Trek where a crew member states their course as “249 mark 38,” this is what they're doing – just stating an azimuth and elevation to describe the direction the ship should head in. It always amazes me that they're able to judge those values to the nearest degree, but then I haven't had the benefit of a Starfleet Academy stellar cartography course!

Enfin, c'est le moment de choisir le type de source lumineuse : distante, ponctuelle ou spot. La première indique une source de lumière qui est à une distance infinie de l'objet, de telle sorte que tous les rayons lumineux incidents sont parallèles. Le paramètre Azimut règle la localisation de la source lumineuse avec un angle. 0° la place à droite de votre objet ; en augmentant les valeurs, elle tourne autour de l'image, dans le sens horaire, jusqu'à 360 ° où elle est de retour sur la droite. Tirez la réglette pour voir l'effet en temps réel. Le paramètre Élévation règle l'angle par rapport au plan du dessin : imaginez une lampe posée dans le plan de votre écran d'ordinateur (peu de relief, des ombres sombres) ; au fur et à mesure que vous déplacez la réglette vers 90 °, la lumière jaillit vers vous hors de l'écran, jusqu'à ce qu'elle soit pile au-dessus de vos objets. continuez vers 180 ° et elle parcourt le même arc jusqu'à être au niveau du moniteur de l'autre côté de votre image ; n'importe quelle valeur supérieure continue à déplacer l'éclairage en demi-cercle derrière le moniteur et ce n'est pas vraiment utile.

La spécification de deux valeurs angulaires comme cela définit une position sphérique dans l'espace à trois dimensions. Si avez déjà regardé un épisode de Star Trek où un membre de l'équipage annonce leur déplacement comme « 249 mark 48 », c'est ce qu'ils font : simplement définir un azimut et une élévation pour décrire la direction prise par le vaisseau. Ça m'amuse toujours de les voir capables de définir ces valeurs au degré près, mais c'est vrai que je n'ai pas bénéficié d'un cours de cartographie interstellaire à la Starfleet Academy !

With two polar values able to define a bearing, it only takes a third parameter, distance, to specify a particular point in space. When selecting the Point Light option, you might expect to see the same two sliders, joined by a third. But the SVG working group decided that defining a specific point in 3D should be done using Cartesian coordinates, so instead you have three anonymous fields with a single “Location” label, representing the location of the point light using x, y and z coordinates. There's no means to graphically pick an x and y location on the canvas, and the values are in terms of the coordinate system of the object being lit (which is not necessarily the same as a the coordinate system of the main drawing). So, yet again, it's down to some trial and error. Whereas the Distant Light, at its infinite distance from the scene, projects an even illumination, the Point Light is far more nuanced. It illuminates areas near to the light source more than those at a distance, leading to gradients in the final color.

Avec deux valeurs polaires capables de définir une position sphérique, il suffit d'un troisième paramètre, la distance, pour spécifier un point dans l'espace. En sélectionnant l'option Lumière ponctuelle, vous pouvez vous attendre à voir les deux mêmes réglettes, associées à une troisième. Mais le groupe de travail SVG a décidé que la définition d'un point particulier en 3D devait être faite en utilisant les coordonnées cartésiennes ; aussi, à la place, vous avez trois champs anonymes avec une étiquette unique « Localisation », représentant la position du point par les coordonnées x, y et z. Il n'y a aucun moyen de choisir une localisation x,y sur le canevas et les valeurs sont en fonction du système de coordonnées de l'objet éclairé (qui n'est pas nécessairement le même que celui du dessin principal). Ainsi, une fois encore, c'est une cause de tâtonnements.

Alors que la Lumière distante, à une distance infinie de la scène, projette une illumination uniforme, la Lumière ponctuelle est bien plus nuancée. Elle illumine plus les zones près de la source lumineuse que celles à distance, entraînant des nuances dans la couleur finale.

The Spot Light option is even more precise in its effect. This requires two sets of coordinates – one to specify the location of the light, and the other to define the direction it's pointing in (which is actually achieved by specifying the point in space it's aiming at). The light is projected in a cone from the source to the target, with an additional two sliders to set the characteristics of that cone: the Specular Exponent sets how focused the light is, whilst the Cone Angle defines the shape of the cone. The cone has a hard edge to it; any points outside it will not be illuminated at all, so you will need additional filter steps if you want a softer edge. This example shows the three types of light in use on some text objects, all of which are actually blue as their base color! You'll notice how “flat” all of these are. Because the bump map is created from the alpha channel of the input image, and our input image has alpha values of only 0 and 255, there’s no scope for gentle transitions in height. If you want a softer edge to your lighting you'll need to introduce some variety in the alpha channel. The easiest way to do this is by using a Gaussian Blur primitive to the input image.

L'option Lumière spot est encore plus précise dans son effet. Elle requiert deux jeux de coordonnées : l'un pour spécifier la position de la lumière et l'autre pour définir la direction vers laquelle elle pointe (ce qui est en fait réalisé en spécifiant le point de l'espace qu'elle vise). La lumière est projetée dans un cône, de la source vers la cible, avec deux réglettes additionnelles pour ajuster les caractéristiques de ce cône : l'Exposant spéculaire définit la concentration du faisceau, tandis que l'Angle du cône définit la forme de celui-ci. Le cône est à bord vif ; tout point en dehors n'est pas du tout illuminé. Vous aurez donc besoin d'étapes de filtrage supplémentaires si vous voulez une bordure plus progressive.

Cet exemple montre l'utilisation des trois types d'éclairage sur des objets texte, qui ont vraiment tous le bleu comme couleur de base !

Vous noterez comme ils ont tous l'air « plats ». Parce que l'embossage est créé à partir du canal alpha de l'image d'entrée, et que les valeurs alpha de notre image d'entrée sont uniquement 0 et 255, il n'y aucune possibilité pour des hauteurs variables. Si vous voulez adoucir le bord de votre éclairage, vous aurez besoin d'introduire un peu de variété dans le canal alpha. La façon la plus facile de le faire est d'utiliser une primitive Flou gaussien sur l'image d'entrée.

Just adding a blur will tend to spread the edge of your text outwards as well as inwards (second image in the next example). For a more pronounced effect, it's often worth using a Morphology filter to erode the input image before you blur it. By thinning your objects first, the full extent of the blur can be kept inside the boundaries of the original shapes (third image). If you then add a Composite filter, set to “In”, to the output of your lighting primitive, you can clip the result to give you something more like the rounded text you were probably looking for (fourth image). Still we're left with that yellow color from the lighting filter. This is where the “Arithmetic” option of the Composite filter comes in (re-read part 50 if you need a refresher on this primitive). The output from the Diffuse Light filter is intended to be multiplied with the source image in order to overlay the lighting effect onto the underlying objects, but rather than providing a nice, obvious shortcut to this operation, the Inkscape UI just exposes the parameters of the underlying SVG model. For each channel of each pixel, the Arithmetic operator performs the following calculation: result = (K1×i1×i2) + (K2×i1) + (K3×i2) + K4 Where K1-4 are constants set in the UI, and i1 and i2 represent the values from a pair of input images. By setting K1 to 1.0 and all the other constants to 0, this equation simplifies down to: result = i1×i2

Le simple ajout d'un flou tendra à disperser le bord de votre texte à l'intérieur comme à l'extérieur (seconde image de l'exemple). Pour un effet plus prononcé, il est souvent pas mal d'utiliser un filtre Morphologie qui érode l'image d'entrée avant de la flouter. En affinant d'abord vos objets, l'extension complète du flou peut être contenue dans les limites des formes d'origine (troisième image). Si, alors, vous ajoutez un filtre Composite, réglé sur « In », à la sortie de la primitive Éclairage, vous pouvez rogner le résultat pour que vous ayez quelque chose plus proche du texte arrondi que, sans doute, vous souhaitiez (quatrième image).

Et malgré tout, nous conservons la couleur jaune venant du filtre Éclairage. C'est ici que l'option « Arithmétique » du filtre Composite est utile (relisez la partie 50 si vous avez besoin de rafraîchissement sur cette primitive). La sortie du filtre Lumière diffuse est destinée à être multipliée à l'image source pour superposer l'effet lumineux sur les objets sous-jacents ; mais, plutôt que de fournir un bon raccourci évident pour cette opération, l'interface utilisateur d'Inkscape offre juste les paramètres du modèle SVG sous-jacent. Pour chaque canal de chaque pixel, l'opérateur Arithmétique réalise le calcul suivant :

résultat = (K1×i1×i2) + (K2×i1) + (K3×i2) + K4

où K1-4 sont les constantes réglées dans l'interface et où i1 et i2 représentent les valeurs de deux images d'entrée. En réglant K1 à 1.0 et toutes les autres constantes à 0, l'équation se simplifie en :

résultat = i1xi2

In other words, a simple multiplication of input values, which is exactly what we want. Changing the “In” operator in the previous filter chain to “Arithmetic”, and setting the constants to 1, 0, 0, 0 results in a green-looking output – the result of shining yellow light on a teal object. Now we have an illuminated object whose base color has an effect on the output. This is obviously much more flexible than the simple “In” operator, which would have us changing the lighting color in the filter itself every time we want to alter the result. If you're worried about losing the “clipping” effect of the “In” operator, don't be: the multiplication operator also applies to the alpha channel, so all those areas in the source image with alpha=0 will result in transparent pixels in the output as well. Moving on to the Specular Light filter, things look pretty similar in the filter UI. There's one additional parameter, but otherwise it's all the same as for the Diffuse Light primitive. That extra parameter is “Exponent” which, according to the SVG spec and the Inkscape tooltip, is used to make the specular lighting more “shiny”.

Autrement dit, une simple multiplication des valeurs d'entrée, ce qui est exactement ce que nous voulons. En changeant l'opérateur « In » dans la chaîne de filtres précédente par « Arithmétique », et en ajustant les constantes à 1, 0, 0, 0, la sortie est dans un ton vert, résultat d'une lumière jaune brillant sur un objet bleu sarcelle.

Maintenant, nous avons un objet illuminé dont la couleur de base a un effet sur la sortie. C'est évidemment beaucoup plus souple qu'un simple opérateur « In », qui nous obligerait à changer la lumière d'éclairage dans le filtre lui-même chaque fois que nous voulons modifier le résultat. Si vous êtes inquiet de la perte de l'effet de découpe de l'opérateur « In », rassurez-vous : l'opérateur de multiplication s'applique aussi au canal alpha, de telle sorte que toutes les zones de l'image source où alpha=0 auront aussi des pixels transparents dans l'image de sortie.

En passant au filtre Lumière spéculaire, le contenu de l'interface utilisateur paraît très similaire. Il y a un paramètre supplémentaire, mais, autrement, c'est identique à la primitive Lumière diffuse. Le paramètre en plus est « Exposant », qui, d'après la spécification SVG et les conseils d'Inkscape, est utilisé pour rendre plus brillante la lumière spéculaire.

Unlike Diffuse Light, this filter results in an image with mixed alpha values. Watch out for this, as seemingly bright reflections might actually just be a white background showing through! In the following image you can see that effect quite clearly on the first and second examples, where bright white “reflections” to the left of the filtered text are exposed as holes in the alpha channel once the yellow background is added behind them. Note that I've used a red Point Light in these examples, but still with teal text as the original object. The four images above show the effect of the Specular Light filter on the plain text, then on an eroded version of the same. I didn't add a Gaussian Blur this time, as I wanted the specular reflections to be sharp and clear. Cranking up the Exponent value in the third image gets close to an output that just shows the highlights, which can then be added back to the original source image again using another Composite Primitive (fourth image). This time the “Arithmetic” mode is used again, but with values of 0, 1, 1, 0 – which has the effect of reducing the equation down to: result = i1+i2

Contrairement à la Lumière diffuse, ce filtre produit une image avec des valeurs alpha variées. Faites attention, car des réflexions semblant brillantes pourraient n'être réellement que le fond blanc qui transparaît ! Dans l'image suivante, vous pouvez voir cet effet très clairement sur les premier et second exemples, où les réflexions blanches « brillantes », à gauche du texte filtré, sont transformées en trous dans le canal alpha une fois qu'un fond jaune a été ajouté. Notez que j'ai utilisé une Lumière ponctuelle rouge dans ces exemples, mais toujours avec le texte bleu sarcelle comme objet d'origine.

Les quatre images ci-dessus montrent l'effet du filtre Lumière spéculaire sur un texte uni, puis sur la version érodée du même. Cette fois, je n'ai pas ajouté un filtre Flou gaussien, car je voulais que les réflexions spéculaires soient franches et claires. En remontant la valeur d'Exposant dans la troisième image, la sortie s'approche de la seule vision des éclats, qui peuvent alors être ajoutés à nouveau à l'image source d'origine en utilisant une autre primitive Composite (quatrième image).

Cette fois-ci, le mode « Arithmétique » est utilisé à nouveau, mais les valeurs sont 0, 1, 1, 0, ce qui a pour effet de réduire l'équation à :

résultat = i1+i2

This primitive therefore adds the reflections to the original image, which is the recommended approach from the SVG specification. Note, however, that a little background opacity has also sneaked through, so you might want to apply another Composite Filter, set to “In”, to ensure that the result is clipped to the shape of your original objects. Finally it's time to combine both lighting filters to produce a fully lit object, with both diffuse and specular light. Once again, the original text is teal, so the yellow diffuse light gives it a green appearance – but you can also see the glinting highlights from the red light source of the specular filter making an appearance. The full filter chain for this effect isn't too complex if you take it one step at a time. First the Morphology primitive erodes the text of the Source Graphic a little, with the output from that going straight into the Specular Lighting primitive, to give those sharp, red highlights. The Morphology output also goes to a Gaussian Blur to soften the image before it's used in the Diffuse Lighting primitive.

Par conséquent, cette primitive ajoute les réflexions à l'image d'origine, ce qui est l'approche recommandée par la spécification SVG. Notez, cependant, qu'une légère opacité du fond est apparue ; aussi, vous pourriez vouloir ajouter un autre filtre Composite, réglé sur « In », pour assurer que le résultat est détouré à la taille des objets d'origine.

Enfin, il est temps de combiner les deux filtres d'éclairage pour produire une image parfaitement éclairée, avec les deux lumières diffuse et spéculaire. Une fois encore, le texte originel est bleu sarcelle et la lumière diffuse jaune lui donne une apparence verte, mais vous pouvez aussi voir apparaître les reflets scintillants de la source lumineuse rouge du filtre spéculaire.

La chaîne de filtrage complète pour cet effet n'est pas trop compliquée si vous la faites étape par étape. En premier, la primitive Morphologie érode un peu le texte de l'image source et sa sortie va directement dans l'entrée de la primitive Lumière spéculaire pour obtenir des reflets nets et rouges. La sortie de Morphologie entre aussi dans un Flou gaussien pour adoucir l'image avant qu'elle soit utilisée dans une primitive Lumière diffuse.

From there, it's just a matter of combining everything together: the first Composite filter (“Arithmetic” mode: 1, 0, 0, 0) multiplies the Source Graphic with the output from the Diffuse Lighting. The second Composite (“Arithmetic” mode: 0, 1, 1, 0) adds in the Specular Lighting highlights. Although the result is almost perfect, there was a slightly visible background, albeit with a low alpha value. A third Composite filter (“In” mode) simply tidies everything up a bit. Although they're no match for real raytracing or 3D modelling, the lighting effects in SVG can be useful for adding a little pseudo-depth to your images. This needn't be anything as obvious as the 3D text presented here: just a little highlighting can turn an otherwise bland texture into something far more interesting, or make your objects stand out from the background. As usual, the best way to find out what can be done with them is simply to experiment.

De là, il s'agit juste de tout combiner ensemble : le premier filtre Composite (mode « Arithmétique » : 1, 0, 0, 0) multiplie la source image avec la sortie d'Éclairage diffus. Le second Composite (mode « Arithmétique » : 0, 1, 1, 0) ajoute les accentuations de l'Éclairage spéculaire. Bien que le résultat soit presque parfait, le fond est légèrement visible, nonobstant une valeur alpha faible. Un troisième filtre Composite (mode « In ») arrange le tout un petit peu.

Bien que ce ne soit pas un vrai rayonnement ou un modelage 3D, les effets d'éclairage de SVG peuvent être utiles pour ajouter une fausse épaisseur à vos objets. Nul besoin d'être aussi évident que le texte 3D présenté ici : un simple reflet peut juste transformer une texture particulièrement fade en quelque chose de beaucoup plus intéressant, ou faire ressortir vos objets du fond. Comme d'habitude, la meilleure solution pour découvrir ce qui peut être fait avec eux est de les expérimenter.

issue115/inkscape.txt · Dernière modification : 2016/12/03 10:09 de auntiee