Outils pour utilisateurs

Outils du site


issue115:inkscape

Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

Prochaine révision
Révision précédente
issue115:inkscape [2016/11/29 09:13] – créée d52frissue115:inkscape [2016/12/03 10:09] (Version actuelle) auntiee
Ligne 1: Ligne 1:
-In this series of articles, I will be building a text-based application with Free Pascal, using its text-based interface for user interaction. This will be combined with other, more moderntechnologies such as database access using SQL and Web access with HTTPThe final aim of the project is to demonstrate how Pascal can be used to build a modern applicationwhile avoiding the overhead associated with a graphical interface that uses widget set such as GTK or Qt+**This month we'll be looking at the last of the filter primitives available in Inkscape 0.48Diffuse Lighting and Specular LightingThese are used to simulate the effect of lights shining on your objectsand 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 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.
  
-In the previous part of the series, we deviated a bit from Free Vision and went into the technical details on how to use the CURL library from Pascal to connect to an RSS feed on FCM’s content management systemAt this stagewe know how to connect to the server and download an XML file containing a list of recent articles published on the web page. In this partwe will see how to parse the XML code to retrieve the information we are aiming for: issue numbers and download URLs. We will then put it all together, and update the database our application uses with fresh data from the Web.+Diffuse Light refers to the general light and shadow on an object that doesn't change significantly as you move your viewpointSpecular Light, on the other handrefers 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.
  
-Understanding the XML language+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.**
  
-EXtended Meta Language (XML) is a simple text-based language that aims to structure data as a tree: each data element may have noneor several child nodesOn the other handeach element must have a single parent element - except for a single node in the entire treewhich is then called the root elementEach element should open with start tagsuch as <element>. The corresponding ending tag would be </element>+Ce mois-cinous examinerons les dernières primitives de filtrage disponibles dans Inkscape 0.48Lumiè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 partieLumiè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èreIl n'pas besoin d'un filtre spécifique pour cette partiecar elle est formée par les couleurs de remplissage et de contour des objets de votre image.
  
-Perhaps an example may helpIf we wish to codify a libraryfor instanceour root element will be the library itselfThis library may then contain an element defining its owner, and perhaps another giving the date on which the data set was compiled. Finally, we will need to create an element for each book in the library, giving its title and author.+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 vueLumière spéculaireau contrairefait référence aux points et reflets brillants qui tournent et se déplacent quand vous bougezRegardez 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.
  
-The beauty of this scheme is that it may easily be adapted for different purposes in flexible manner. For instancein the above example, one of the books has been marked with a genrewhile another has not.+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 quelques paramètres modifiablesmais pour la plupartil s'agit de déplacer les réglettes par tâtonnements de manière à obtenir le résultat que vous recherchez.
  
-Writing a program to transverse a data set in XML has its own challenges; luckily for us, the Free Pascal project has foreseen the use of a set of standard classes that may be implemented for our own purposesLet us write a simple program that reads in an XML fileand outputs on screen each element name in sequenceor its value if it is a text element that simply contains textTo begin with, let us include the standard and XML classes and define our variables (previous page, bottom right).+**The first parameter to choose is the color of your light. This has a huge effect on the output of the filteras the lighting effect completely replaces the original color of your objects, rather than mixing with the underlying huesIn the example that followsall the text objects are teal (a blue-green color)but the color used in the filters is yellowNotice that no teal appears in the output images.
  
-The TFileStream will be used to access the XML file on our local diskand make it available to a TXMLReader through an adaptor class, TXMLInputSource. The TXMLReaderSettings object is needed to pass parameters to the reader+In practice, it's only the alpha channel of the input image that'used by this primitive – so it doesn't matter whether you connect it to the full Source Graphic or just the Source Alphathe 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.
  
-We begin by configuring the settings, basically telling the reader to ignore supplementary whitespace (actual spaces, but also line breaks and tabulations)and to use XML namespaces if available - though we will not need them here:+The Kernel Unit Length parameter can be largely ignored. It's not used by Inkscape, but may have an effect on other SVG viewerswhere it's used to define the size of the pixel grid used for the filter calculations. I usually just leave it at zero.**
  
-settings := TXMLReaderSettings.Create; +Le premier paramètre à choisir est la couleur de la lumièreCelle-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-jacentesDans 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.
-  +
-settings.PreserveWhiteSpace := false; +
-  +
-settings.Namespaces := true;+
  
-We access the fileand create TXMLInputSource from the resulting stream:+En pratiqueseul 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'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.
  
-f := TFileStream.Create('test.xml', fmOpenRead);+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 SVGoù il sert à définir la taille de la grille des pixels utilisée pour les calculs de filtrage. Je le laisse habituellement à zéro.
  
-input := TXMLInputSource.Create(f);+**Finally, it's time to choose the type of light sourceDistant, Point, or SpotThe 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.
  
-Now (shown above) we can create our TXMLTextReader, and have it parse each element encountered.+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 inIt 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!**
  
-Finallylet’s not forget to close the file stream neatly:+Enfinc'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.
  
-f.Free;+La spécification de deux valeurs angulaires comme cela définit une position sphérique dans l'espace à trois dimensionsSi 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 !
  
-The code for the complete program is available at this link: http://pastebin.com/PtciSAQb +**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.
  
-Parsing our RSS feed in XML+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.**
  
-In the last part of this serieswe obtained the RSS for Full Circle Magazine using the CURL libraryThis is piece of XML datawith the following structureIt has been cleaned up bit to showcase relevant elements (shown below).+Avec deux valeurs polaires capables de définir une position sphériqueil suffit d'un troisième paramètre, la distance, pour spécifier un point dans l'espaceEn 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 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 zIl n'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.
  
-Sowhat we want to do is isolate individual <title> elementsandwithin each element, the corresponding <link>We have on the one hand a routine from CURL that fetches the contents of a URL, and produces a readable Stream. On the other hand, we have an XML parser that can parse a writable Stream. The link is obvious: we now need a mechanism to pipe data from the first stream into the second, and, in Free Pascal, this mechanism is a piped stream. Let’s do it. First, we will need a double set of variables (next pagetop right).+Alors que la Lumière distanteà une distance infinie de la scèneprojette une illumination uniformela Lumière ponctuelle est bien plus nuancéeElle illumine plus les zones près de la source lumineuse que celles à distanceentraînant des nuances dans la couleur finale.
  
-The first set are those used for the CURL library, the second will be the input and output streams to be parsed together, and the third set is for the XML parser. Finallythe two strings and associated boolean variables will be needed to link each element (of type ntElement) with its associated value (type ntText) - which is not the element itself, but a sub-element inserted inside the parent elementUnfortunately, this textual element is not always in the first position among the element’s childrenso a rather convoluted set of flags (the boolean variables) must be used to detect them.+**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 targetwith 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.
  
-We will not go over either the use of the CURL library, that has been described in the previous part of this seriesor over the XML parser. We will concentrate instead on the use of the piped streams. We will create the two streams together:+This example shows the three types of light in use on some text objectsall of which are actually blue as their base color!
  
-  CreatePipeStreams (inPipeoutPipe);+You'll notice how “flat” all of these are. Because the bump map is created from the alpha channel of the input imageand 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.**
  
-The CURL library can then be created using the outPipe section, to which it will write the data obtained from the Internet: +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ônede la source vers la cibleavec 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.
-  curl_easy_setopt(hCurl,CURLOPT_WRITEDATA,[Pointer(outPipe)]);+
  
-The XML reader’s input will be connected to the inPipe sectionfrom which it will read back the bytes:+Cet exemple montre l'utilisation des trois types d'éclairage sur des objets textequi ont vraiment tous le bleu comme couleur de base !
  
-  input := TXMLInputSource.Create(inPipe);+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.
  
-Finally, the XML reader’s main loop can be configured to detect title/link pairs. For the time beingthey will simply be output on screen (shown bottom right).+**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 firstthe 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).
  
-The complete program can be found at this link: http://pastebin.com/ciVGXvy6 .+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 modelFor each channel of each pixel, the Arithmetic operator performs the following calculation:
  
-Integrating XML parsing into our Free Vision application+result = (K1×i1×i2) + (K2×i1) + (K3×i2) + K4
  
-At this stage, we have on the one hand a working Free Vision applicationthat consults its internal SQLite database of FCM issues and gives the result in scrolling list on screenOn the other hand, we have a mechanism to connect to the Internet and update the database. Now, we need to connect the twoso that the database is updated before the data is shown to the user.+Where K1-4 are constants set in the UI, and i1 and i2 represent the values from pair of input imagesBy setting K1 to 1.0 and all the other constants to 0this equation simplifies down to:
  
-Perhaps the most elegant way of doing this - and the least expensive in terms of writing code - is to create a new Dialog type. Called TUpDateDialog, it will be shown on screen just before TDisplaySQLDialog is created. So, in the main application’s HandleEvent procedure, we have what's shown on the next page, top right.+result = i1×i2**
  
-The TUpdateDialog will need no outside inputssince it will always be using the same target URL to connect to the Internetand local database filename to append any data found on new issues of FCMThis Dialog will just need a constructor that builds itand sets off the process:+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 objetsl'extension complète du flou peut être contenue dans les limites des formes d'origine (troisième image)Sialors, 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 :
  
-  TUpdateDialog object(TDialog) +résultat = (K1×i1×i2(K2×i1+ (K3×i2) + K4
- constructor Init (FileName : String)+
-  end; +
-  PUpdateDialog = ^TUpdateDialog;+
  
-This constructor procedure will need a whole lot of variables, but they can be classified into separate categoriesWe will need: +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éeEn réglant K1 à 1.0 et toutes les autres constantes à 0l'équation se simplifie en :
-• A TRect and PLabel to set up this Dialog on screen; this is the Free Vision part. +
-• A URL and PCurl to get to the Internet and retrieve a stream accessing FCM’s feed. +
-• Two pipesto set up the connection between the incoming stream from the Internet, and an outgoing stream towards the XML reader. +
-• The XML reader itself, associated settings, and several variables to identify each new issue’s identification code (e.g. ‘111’), title (‘Full Circle Magazine #111’) and download link. +
-• A handler for the SQLite connection to the local database.+
  
-So, have a look at the code  shown bottom right.+résultat = i1xi2 
  
-Most of the code will not be reproduced here, since it is in essence a mashup of that written in our previous part and the beginning of this one. Salient points would include the use of a Regular Expression parser (regexp) in order to parse the titles from the XML stream, identifying which contain the text identifying a new issue of FCM. We are looking for something such as ‘#109’, ‘#110’, ‘#111’..., so basically a pound sign ‘#’ followed by a series of digits. This can be made systematic with the following code: 
  
-re := TRegExpr.Create;+**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.
  
-re.Expression := '#[0-9]*'; +Now we have an illuminated object whose base color has an effect on the outputThis is obviously much more flexible than the simple “In” operatorwhich 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” operatordon'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.
-  +
-We can now use ‘re’ as a regular expression reader in the following wayto identify if the next value found by the XML reader contains the expression we are looking for. If soit can be isolated and used to prime the issue code for insertion into the database (shown bottm left).+
  
-Now, all we need to do is determinefor each issue announcement found in the XML streamif this issue is already inside our database. To so dowe will need to get back to the SQLite driver, and search the existing issues with the same identifying code. If a match is not foundthis issue is a new one and needs to be appended to the existing table (shown top right).+Moving on to the Specular Light filterthings look pretty similar in the filter UI. There's one additional parameterbut otherwise it's all the same as for the Diffuse Light primitive. That extra parameter is “Exponent” whichaccording to the SVG spec and the Inkscape tooltip, is used to make the specular lighting more “shiny”.**
  
-Once the XML code has been completely parsedwe can alter the label on the Dialog to notify the user of how many new issues of FCM have been found. In my casemy database had been initialized by hand with issues 108109 and 110. I launched the applicationand several new issues were detected from the XML feed: previous issue 107and newer issue 111. This last one was identified twicesince two different posts on FCM’s feed referenced this issuebut was inserted only once into the database.+Autrement ditune simple multiplication des valeurs d'entrée, ce qui est exactement ce que nous voulonsEn changeant l'opérateur « In » dans la chaîne de filtres précédente par « Arithmétique »et en ajustant les constantes à 1000la sortie est dans un ton vertrésultat d'une lumière jaune brillant sur un objet bleu sarcelle.
  
-  msgLabel^.Text := NewStr('Found + IntToStr(newItems) + new issues...'); +Maintenant, nous avons un objet illuminé dont la couleur de base a un effet sur la sortieC'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ésultatSi 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.
-  +
- DrawView;+
  
-The finalized application’s code can be found here: http://pastebin.com/H422xg3V .+En passant au filtre Lumière spéculaire, le contenu de l'interface utilisateur paraît très similaireIl 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.
  
-In this part of the serieswe put our complete application together using Free Vision for the user interfaceSQLite to create local data, and CURL and XML to retrieve fresh data from an RSS feed from the Web to update our database. In the next part, we will see various ways in which our application can run on Raspberry Pi.+**Unlike Diffuse Lightthis filter results in an image with mixed alpha values. Watch out for thisas seemingly bright reflections might actually just be 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 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.1480407229.txt.gz · Dernière modification : 2016/11/29 09:13 de d52fr