Fix T44048: freestyle lines in Cycles are in the wrong color space.
[blender.git] / source / blender / freestyle / intern / blender_interface / BlenderStrokeRenderer.cpp
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * ***** END GPL LICENSE BLOCK *****
19  */
20
21 /** \file blender/freestyle/intern/blender_interface/BlenderStrokeRenderer.cpp
22  *  \ingroup freestyle
23  */
24
25 #include "BlenderStrokeRenderer.h"
26
27 #include "../application/AppConfig.h"
28 #include "../stroke/Canvas.h"
29
30 extern "C" {
31 #include "MEM_guardedalloc.h"
32
33 #include "RNA_access.h"
34 #include "RNA_types.h"
35
36 #include "DNA_camera_types.h"
37 #include "DNA_listBase.h"
38 #include "DNA_linestyle_types.h"
39 #include "DNA_material_types.h"
40 #include "DNA_meshdata_types.h"
41 #include "DNA_mesh_types.h"
42 #include "DNA_object_types.h"
43 #include "DNA_screen_types.h"
44 #include "DNA_scene_types.h"
45
46 #include "BKE_customdata.h"
47 #include "BKE_depsgraph.h"
48 #include "BKE_global.h"
49 #include "BKE_library.h" /* free_libblock */
50 #include "BKE_material.h"
51 #include "BKE_mesh.h"
52 #include "BKE_node.h"
53 #include "BKE_object.h"
54 #include "BKE_scene.h"
55
56 #include "BLI_ghash.h"
57 #include "BLI_listbase.h"
58 #include "BLI_math_color.h"
59 #include "BLI_math_vector.h"
60 #include "BLI_utildefines.h"
61
62 #include "RE_pipeline.h"
63
64 #include "render_types.h"
65 }
66
67 #include <limits.h>
68
69 namespace Freestyle {
70
71 const char *BlenderStrokeRenderer::uvNames[] = {"along_stroke", "along_stroke_tips"};
72
73 BlenderStrokeRenderer::BlenderStrokeRenderer(Render *re, int render_count) : StrokeRenderer()
74 {
75         freestyle_bmain = re->freestyle_bmain;
76
77         // for stroke mesh generation
78         _width = re->winx;
79         _height = re->winy;
80
81         old_scene = re->scene;
82
83         char name[MAX_ID_NAME - 2];
84         BLI_snprintf(name, sizeof(name), "FRS%d_%s", render_count, re->scene->id.name + 2);
85         freestyle_scene = BKE_scene_add(freestyle_bmain, name);
86         freestyle_scene->r.cfra = old_scene->r.cfra;
87         freestyle_scene->r.mode = old_scene->r.mode &
88                                   ~(R_EDGE_FRS | R_SHADOW | R_SSS | R_PANORAMA | R_ENVMAP | R_MBLUR | R_BORDER);
89         freestyle_scene->r.xsch = re->rectx; // old_scene->r.xsch
90         freestyle_scene->r.ysch = re->recty; // old_scene->r.ysch
91         freestyle_scene->r.xasp = 1.0f; // old_scene->r.xasp;
92         freestyle_scene->r.yasp = 1.0f; // old_scene->r.yasp;
93         freestyle_scene->r.tilex = old_scene->r.tilex;
94         freestyle_scene->r.tiley = old_scene->r.tiley;
95         freestyle_scene->r.size = 100; // old_scene->r.size
96         //freestyle_scene->r.maximsize = old_scene->r.maximsize; /* DEPRECATED */
97         freestyle_scene->r.ocres = old_scene->r.ocres;
98         freestyle_scene->r.color_mgt_flag = 0; // old_scene->r.color_mgt_flag;
99         freestyle_scene->r.scemode = old_scene->r.scemode & ~(R_SINGLE_LAYER | R_NO_FRAME_UPDATE | R_MULTIVIEW);
100         freestyle_scene->r.flag = old_scene->r.flag;
101         freestyle_scene->r.threads = old_scene->r.threads;
102         freestyle_scene->r.border.xmin = old_scene->r.border.xmin;
103         freestyle_scene->r.border.ymin = old_scene->r.border.ymin;
104         freestyle_scene->r.border.xmax = old_scene->r.border.xmax;
105         freestyle_scene->r.border.ymax = old_scene->r.border.ymax;
106         strcpy(freestyle_scene->r.pic, old_scene->r.pic);
107         freestyle_scene->r.safety.xmin = old_scene->r.safety.xmin;
108         freestyle_scene->r.safety.ymin = old_scene->r.safety.ymin;
109         freestyle_scene->r.safety.xmax = old_scene->r.safety.xmax;
110         freestyle_scene->r.safety.ymax = old_scene->r.safety.ymax;
111         freestyle_scene->r.osa = old_scene->r.osa;
112         freestyle_scene->r.filtertype = old_scene->r.filtertype;
113         freestyle_scene->r.gauss = old_scene->r.gauss;
114         freestyle_scene->r.dither_intensity = old_scene->r.dither_intensity;
115         BLI_strncpy(freestyle_scene->r.engine, old_scene->r.engine, sizeof(freestyle_scene->r.engine));
116         freestyle_scene->r.im_format.planes = R_IMF_PLANES_RGBA; 
117         freestyle_scene->r.im_format.imtype = R_IMF_IMTYPE_PNG;
118
119         if (G.debug & G_DEBUG_FREESTYLE) {
120                 printf("%s: %d thread(s)\n", __func__, BKE_render_num_threads(&freestyle_scene->r));
121         }
122
123         // Render layer
124         SceneRenderLayer *srl = (SceneRenderLayer *)freestyle_scene->r.layers.first;
125         srl->layflag = SCE_LAY_SOLID | SCE_LAY_ZTRA;
126
127         BKE_scene_set_background(freestyle_bmain, freestyle_scene);
128
129         // Camera
130         Object *object_camera = BKE_object_add(freestyle_bmain, freestyle_scene, OB_CAMERA, NULL);
131         DAG_relations_tag_update(freestyle_bmain);
132
133         Camera *camera = (Camera *)object_camera->data;
134         camera->type = CAM_ORTHO;
135         camera->ortho_scale = max(re->rectx, re->recty);
136         camera->clipsta = 0.1f;
137         camera->clipend = 100.0f;
138
139         _z_delta = 0.00001f;
140         _z = camera->clipsta + _z_delta;
141
142         object_camera->loc[0] = re->disprect.xmin + 0.5f * re->rectx;
143         object_camera->loc[1] = re->disprect.ymin + 0.5f * re->recty;
144         object_camera->loc[2] = 1.0f;
145
146         freestyle_scene->camera = object_camera;
147
148         // Reset serial mesh ID (used for BlenderStrokeRenderer::NewMesh())
149         _mesh_id = 0xffffffff;
150
151         // Check if the rendering engine uses new shading nodes
152         _use_shading_nodes = BKE_scene_use_new_shading_nodes(freestyle_scene);
153
154         // Create a bNodeTree-to-Material hash table
155         if (_use_shading_nodes)
156                 _nodetree_hash = BLI_ghash_ptr_new("BlenderStrokeRenderer::_nodetree_hash");
157         else
158                 _nodetree_hash = NULL;
159 }
160
161 BlenderStrokeRenderer::~BlenderStrokeRenderer()
162 {
163         // The freestyle_scene object is not released here.  Instead,
164         // the scene is released in free_all_freestyle_renders() in
165         // source/blender/render/intern/source/pipeline.c, after the
166         // compositor has finished.
167
168         // release objects and data blocks
169         for (Base *b = (Base *)freestyle_scene->base.first; b; b = b->next) {
170                 Object *ob = b->object;
171                 void *data = ob->data;
172                 char *name = ob->id.name;
173 #if 0
174                 if (G.debug & G_DEBUG_FREESTYLE) {
175                         cout << "removing " << name[0] << name[1] << ":" << (name+2) << endl;
176                 }
177 #endif
178                 switch (ob->type) {
179                 case OB_MESH:
180                         BKE_libblock_free(freestyle_bmain, ob);
181                         BKE_libblock_free(freestyle_bmain, data);
182                         break;
183                 case OB_CAMERA:
184                         BKE_libblock_free(freestyle_bmain, ob);
185                         BKE_libblock_free(freestyle_bmain, data);
186                         freestyle_scene->camera = NULL;
187                         break;
188                 default:
189                         cerr << "Warning: unexpected object in the scene: " << name[0] << name[1] << ":" << (name + 2) << endl;
190                 }
191         }
192         BLI_freelistN(&freestyle_scene->base);
193
194         // release materials
195         Link *lnk = (Link *)freestyle_bmain->mat.first;
196
197         while (lnk)
198         {
199                 Material *ma = (Material*)lnk;
200                 // We want to retain the linestyle mtexs, so let's detach them first
201                 for (int a = 0; a < MAX_MTEX; a++) {
202                         if (ma->mtex[a]) {
203                                 ma->mtex[a] = NULL;
204                         }
205                         else {
206                                 break; // Textures are ordered, no empty slots between two textures
207                         }
208                 }
209                 lnk = lnk->next;
210                 BKE_libblock_free(freestyle_bmain, ma);
211         }
212
213         if (_use_shading_nodes)
214                 BLI_ghash_free(_nodetree_hash, NULL, NULL);
215
216         FreeStrokeGroups();
217 }
218
219 float BlenderStrokeRenderer::get_stroke_vertex_z(void) const
220 {
221         float z = _z;
222         BlenderStrokeRenderer *self = const_cast<BlenderStrokeRenderer *>(this);
223         if (!(_z < _z_delta * 100000.0f))
224                 self->_z_delta *= 10.0f;
225         self->_z += _z_delta;
226         return -z;
227 }
228
229 unsigned int BlenderStrokeRenderer::get_stroke_mesh_id(void) const
230 {
231         unsigned mesh_id = _mesh_id;
232         BlenderStrokeRenderer *self = const_cast<BlenderStrokeRenderer *>(this);
233         self->_mesh_id--;
234         return mesh_id;
235 }
236
237 Material* BlenderStrokeRenderer::GetStrokeShader(Main *bmain, bNodeTree *iNodeTree, bool do_id_user)
238 {
239         Material *ma = BKE_material_add(bmain, "stroke_shader");
240         bNodeTree *ntree;
241         bNode *output_linestyle = NULL;
242         bNodeSocket *fromsock, *tosock;
243         PointerRNA fromptr, toptr;
244         NodeShaderAttribute *storage;
245
246         if (iNodeTree) {
247                 // make a copy of linestyle->nodetree
248                 ntree = ntreeCopyTree_ex(iNodeTree, bmain, do_id_user);
249
250                 // find the active Output Line Style node
251                 for (bNode *node = (bNode *)ntree->nodes.first; node; node = node->next) {
252                         if (node->type == SH_NODE_OUTPUT_LINESTYLE && (node->flag & NODE_DO_OUTPUT)) {
253                                 output_linestyle = node;
254                                 break;
255                         }
256                 }
257         }
258         else {
259                 ntree = ntreeAddTree(NULL, "stroke_shader", "ShaderNodeTree");
260         }
261         ma->nodetree = ntree;
262         ma->use_nodes = 1;
263
264         bNode *input_attr_color = nodeAddStaticNode(NULL, ntree, SH_NODE_ATTRIBUTE);
265         input_attr_color->locx = 0.0f;
266         input_attr_color->locy = -200.0f;
267         storage = (NodeShaderAttribute *)input_attr_color->storage;
268         BLI_strncpy(storage->name, "Color", sizeof(storage->name));
269
270         bNode *mix_rgb_color = nodeAddStaticNode(NULL, ntree, SH_NODE_MIX_RGB);
271         mix_rgb_color->custom1 = MA_RAMP_BLEND; // Mix
272         mix_rgb_color->locx = 200.0f;
273         mix_rgb_color->locy = -200.0f;
274         tosock = (bNodeSocket *)BLI_findlink(&mix_rgb_color->inputs, 0); // Fac
275         RNA_pointer_create((ID *)ntree, &RNA_NodeSocket, tosock, &toptr);
276         RNA_float_set(&toptr, "default_value", 0.0f);
277
278         bNode *input_attr_alpha = nodeAddStaticNode(NULL, ntree, SH_NODE_ATTRIBUTE);
279         input_attr_alpha->locx = 400.0f;
280         input_attr_alpha->locy = 300.0f;
281         storage = (NodeShaderAttribute *)input_attr_alpha->storage;
282         BLI_strncpy(storage->name, "Alpha", sizeof(storage->name));
283
284         bNode *mix_rgb_alpha = nodeAddStaticNode(NULL, ntree, SH_NODE_MIX_RGB);
285         mix_rgb_alpha->custom1 = MA_RAMP_BLEND; // Mix
286         mix_rgb_alpha->locx = 600.0f;
287         mix_rgb_alpha->locy = 300.0f;
288         tosock = (bNodeSocket *)BLI_findlink(&mix_rgb_alpha->inputs, 0); // Fac
289         RNA_pointer_create((ID *)ntree, &RNA_NodeSocket, tosock, &toptr);
290         RNA_float_set(&toptr, "default_value", 0.0f);
291
292         bNode *shader_emission = nodeAddStaticNode(NULL, ntree, SH_NODE_EMISSION);
293         shader_emission->locx = 400.0f;
294         shader_emission->locy = -200.0f;
295
296         bNode *input_light_path = nodeAddStaticNode(NULL, ntree, SH_NODE_LIGHT_PATH);
297         input_light_path->locx = 400.0f;
298         input_light_path->locy = 100.0f;
299
300         bNode *mix_shader_color = nodeAddStaticNode(NULL, ntree, SH_NODE_MIX_SHADER);
301         mix_shader_color->locx = 600.0f;
302         mix_shader_color->locy = -100.0f;
303
304         bNode *shader_transparent = nodeAddStaticNode(NULL, ntree, SH_NODE_BSDF_TRANSPARENT);
305         shader_transparent->locx = 600.0f;
306         shader_transparent->locy = 100.0f;
307
308         bNode *mix_shader_alpha = nodeAddStaticNode(NULL, ntree, SH_NODE_MIX_SHADER);
309         mix_shader_alpha->locx = 800.0f;
310         mix_shader_alpha->locy = 100.0f;
311
312         bNode *output_material = nodeAddStaticNode(NULL, ntree, SH_NODE_OUTPUT_MATERIAL);
313         output_material->locx = 1000.0f;
314         output_material->locy = 100.0f;
315
316         fromsock = (bNodeSocket *)BLI_findlink(&input_attr_color->outputs, 0); // Color
317         tosock = (bNodeSocket *)BLI_findlink(&mix_rgb_color->inputs, 1); // Color1
318         nodeAddLink(ntree, input_attr_color, fromsock, mix_rgb_color, tosock);
319
320         fromsock = (bNodeSocket *)BLI_findlink(&mix_rgb_color->outputs, 0); // Color
321         tosock = (bNodeSocket *)BLI_findlink(&shader_emission->inputs, 0); // Color
322         nodeAddLink(ntree, mix_rgb_color, fromsock, shader_emission, tosock);
323
324         fromsock = (bNodeSocket *)BLI_findlink(&shader_emission->outputs, 0); // Emission
325         tosock = (bNodeSocket *)BLI_findlink(&mix_shader_color->inputs, 2); // Shader (second)
326         nodeAddLink(ntree, shader_emission, fromsock, mix_shader_color, tosock);
327
328         fromsock = (bNodeSocket *)BLI_findlink(&input_light_path->outputs, 0); // In Camera Ray
329         tosock = (bNodeSocket *)BLI_findlink(&mix_shader_color->inputs, 0); // Fac
330         nodeAddLink(ntree, input_light_path, fromsock, mix_shader_color, tosock);
331
332         fromsock = (bNodeSocket *)BLI_findlink(&mix_rgb_alpha->outputs, 0); // Color
333         tosock = (bNodeSocket *)BLI_findlink(&mix_shader_alpha->inputs, 0); // Fac
334         nodeAddLink(ntree, mix_rgb_alpha, fromsock, mix_shader_alpha, tosock);
335
336         fromsock = (bNodeSocket *)BLI_findlink(&input_attr_alpha->outputs, 0); // Color
337         tosock = (bNodeSocket *)BLI_findlink(&mix_rgb_alpha->inputs, 1); // Color1
338         nodeAddLink(ntree, input_attr_alpha, fromsock, mix_rgb_alpha, tosock);
339
340         fromsock = (bNodeSocket *)BLI_findlink(&shader_transparent->outputs, 0); // BSDF
341         tosock = (bNodeSocket *)BLI_findlink(&mix_shader_alpha->inputs, 1); // Shader (first)
342         nodeAddLink(ntree, shader_transparent, fromsock, mix_shader_alpha, tosock);
343
344         fromsock = (bNodeSocket *)BLI_findlink(&mix_shader_color->outputs, 0); // Shader
345         tosock = (bNodeSocket *)BLI_findlink(&mix_shader_alpha->inputs, 2); // Shader (second)
346         nodeAddLink(ntree, mix_shader_color, fromsock, mix_shader_alpha, tosock);
347
348         fromsock = (bNodeSocket *)BLI_findlink(&mix_shader_alpha->outputs, 0); // Shader
349         tosock = (bNodeSocket *)BLI_findlink(&output_material->inputs, 0); // Surface
350         nodeAddLink(ntree, mix_shader_alpha, fromsock, output_material, tosock);
351
352         if (output_linestyle) {
353                 bNodeSocket *outsock;
354                 bNodeLink *link;
355
356                 mix_rgb_color->custom1 = output_linestyle->custom1; // blend_type
357                 mix_rgb_color->custom2 = output_linestyle->custom2; // use_clamp
358
359                 outsock = (bNodeSocket *)BLI_findlink(&output_linestyle->inputs, 0); // Color
360                 tosock = (bNodeSocket *)BLI_findlink(&mix_rgb_color->inputs, 2); // Color2
361                 link = (bNodeLink *)BLI_findptr(&ntree->links, outsock, offsetof(bNodeLink, tosock));
362                 if (link) {
363                         nodeAddLink(ntree, link->fromnode, link->fromsock, mix_rgb_color, tosock);
364                 }
365                 else {
366                         float color[4];
367                         RNA_pointer_create((ID *)ntree, &RNA_NodeSocket, outsock, &fromptr);
368                         RNA_pointer_create((ID *)ntree, &RNA_NodeSocket, tosock, &toptr);
369                         RNA_float_get_array(&fromptr, "default_value", color);
370                         RNA_float_set_array(&toptr, "default_value", color);
371                 }
372
373                 outsock = (bNodeSocket *)BLI_findlink(&output_linestyle->inputs, 1); // Color Fac
374                 tosock = (bNodeSocket *)BLI_findlink(&mix_rgb_color->inputs, 0); // Fac
375                 link = (bNodeLink *)BLI_findptr(&ntree->links, outsock, offsetof(bNodeLink, tosock));
376                 if (link) {
377                         nodeAddLink(ntree, link->fromnode, link->fromsock, mix_rgb_color, tosock);
378                 }
379                 else {
380                         RNA_pointer_create((ID *)ntree, &RNA_NodeSocket, outsock, &fromptr);
381                         RNA_pointer_create((ID *)ntree, &RNA_NodeSocket, tosock, &toptr);
382                         RNA_float_set(&toptr, "default_value", RNA_float_get(&fromptr, "default_value"));
383                 }
384
385                 outsock = (bNodeSocket *)BLI_findlink(&output_linestyle->inputs, 2); // Alpha
386                 tosock = (bNodeSocket *)BLI_findlink(&mix_rgb_alpha->inputs, 2); // Color2
387                 link = (bNodeLink *)BLI_findptr(&ntree->links, outsock, offsetof(bNodeLink, tosock));
388                 if (link) {
389                         nodeAddLink(ntree, link->fromnode, link->fromsock, mix_rgb_alpha, tosock);
390                 }
391                 else {
392                         float color[4];
393                         RNA_pointer_create((ID *)ntree, &RNA_NodeSocket, outsock, &fromptr);
394                         RNA_pointer_create((ID *)ntree, &RNA_NodeSocket, tosock, &toptr);
395                         color[0] = color[1] = color[2] = RNA_float_get(&fromptr, "default_value");
396                         color[3] = 1.0f;
397                         RNA_float_set_array(&toptr, "default_value", color);
398                 }
399
400                 outsock = (bNodeSocket *)BLI_findlink(&output_linestyle->inputs, 3); // Alpha Fac
401                 tosock = (bNodeSocket *)BLI_findlink(&mix_rgb_alpha->inputs, 0); // Fac
402                 link = (bNodeLink *)BLI_findptr(&ntree->links, outsock, offsetof(bNodeLink, tosock));
403                 if (link) {
404                         nodeAddLink(ntree, link->fromnode, link->fromsock, mix_rgb_alpha, tosock);
405                 }
406                 else {
407                         RNA_pointer_create((ID *)ntree, &RNA_NodeSocket, outsock, &fromptr);
408                         RNA_pointer_create((ID *)ntree, &RNA_NodeSocket, tosock, &toptr);
409                         RNA_float_set(&toptr, "default_value", RNA_float_get(&fromptr, "default_value"));
410                 }
411
412                 for (bNode *node = (bNode *)ntree->nodes.first; node; node = node->next) {
413                         if (node->type == SH_NODE_UVALONGSTROKE) {
414                                 // UV output of the UV Along Stroke node
415                                 bNodeSocket *sock = (bNodeSocket *)BLI_findlink(&node->outputs, 0);
416
417                                 // add new UV Map node
418                                 bNode *input_uvmap = nodeAddStaticNode(NULL, ntree, SH_NODE_UVMAP);
419                                 input_uvmap->locx = node->locx - 200.0f;
420                                 input_uvmap->locy = node->locy;
421                                 NodeShaderUVMap *storage = (NodeShaderUVMap *)input_uvmap->storage;
422                                 if (node->custom1 & 1) { // use_tips
423                                         BLI_strncpy(storage->uv_map, uvNames[1], sizeof(storage->uv_map));
424                                 }
425                                 else {
426                                         BLI_strncpy(storage->uv_map, uvNames[0], sizeof(storage->uv_map));
427                                 }
428                                 fromsock = (bNodeSocket *)BLI_findlink(&input_uvmap->outputs, 0); // UV
429
430                                 // replace links from the UV Along Stroke node by links from the UV Map node
431                                 for (bNodeLink *link = (bNodeLink *)ntree->links.first; link; link = link->next) {
432                                         if (link->fromnode == node && link->fromsock == sock) {
433                                                 nodeAddLink(ntree, input_uvmap, fromsock, link->tonode, link->tosock);
434                                         }
435                                 }
436                                 nodeRemSocketLinks(ntree, sock);
437                         }
438                 }
439         }
440
441         nodeSetActive(ntree, output_material);
442         ntreeUpdateTree(bmain, ntree);
443
444         return ma;
445 }
446
447 void BlenderStrokeRenderer::RenderStrokeRep(StrokeRep *iStrokeRep) const
448 {
449         RenderStrokeRepBasic(iStrokeRep);
450 }
451
452 void BlenderStrokeRenderer::RenderStrokeRepBasic(StrokeRep *iStrokeRep) const
453 {
454         if (_use_shading_nodes) {
455                 bNodeTree *nt = iStrokeRep->getNodeTree();
456                 Material *ma = (Material *)BLI_ghash_lookup(_nodetree_hash, nt);
457                 if (!ma) {
458                         ma = BlenderStrokeRenderer::GetStrokeShader(freestyle_bmain, nt, false);
459                         BLI_ghash_insert(_nodetree_hash, nt, ma);
460                 }
461
462                 if (STREQ(freestyle_scene->r.engine, RE_engine_id_CYCLES)) {
463                         PointerRNA scene_ptr, freestyle_scene_ptr;
464                         RNA_pointer_create(NULL, &RNA_Scene, old_scene, &scene_ptr);
465                         RNA_pointer_create(NULL, &RNA_Scene, freestyle_scene, &freestyle_scene_ptr);
466
467                         PointerRNA cycles_ptr = RNA_pointer_get(&scene_ptr, "cycles");
468                         PointerRNA freestyle_cycles_ptr = RNA_pointer_get(&freestyle_scene_ptr, "cycles");
469
470                         int flag;
471                         RNA_STRUCT_BEGIN(&freestyle_cycles_ptr, prop)
472                         {
473                                 flag = RNA_property_flag(prop);
474                                 if (flag & PROP_HIDDEN)
475                                         continue;
476                                 RNA_property_copy(&freestyle_cycles_ptr, &cycles_ptr, prop, -1);
477                         }
478                         RNA_STRUCT_END;
479
480                         RNA_boolean_set(&freestyle_cycles_ptr, "film_transparent", 1);
481                 }
482
483                 iStrokeRep->setMaterial(ma);
484         }
485         else {
486                 bool has_mat = false;
487                 int a = 0;
488
489                 // Look for a good existing material
490                 for (Link *lnk = (Link *)freestyle_bmain->mat.first; lnk; lnk = lnk->next) {
491                         Material *ma = (Material*)lnk;
492                         bool texs_are_good = true;
493                         // as soon as textures differ it's not the right one
494                         for (int a = 0; a < MAX_MTEX; a++) {
495                                 if (ma->mtex[a] != iStrokeRep->getMTex(a)) {
496                                         texs_are_good = false;
497                                         break;
498                                 }
499                         }
500
501                         if (texs_are_good) {
502                                 iStrokeRep->setMaterial(ma);
503                                 has_mat = true;
504                                 break; // if textures are good, no need to search anymore
505                         }
506                 }
507
508                 // If still no material, create one
509                 if (!has_mat) {
510                         Material *ma = BKE_material_add(freestyle_bmain, "stroke_material");
511                         DAG_relations_tag_update(freestyle_bmain);
512                         ma->mode |= MA_VERTEXCOLP;
513                         ma->mode |= MA_TRANSP;
514                         ma->mode |= MA_SHLESS;
515                         ma->vcol_alpha = 1;
516
517                         // Textures
518                         while (iStrokeRep->getMTex(a)) {
519                                 ma->mtex[a] = (MTex *)iStrokeRep->getMTex(a);
520
521                                 // We'll generate both with tips and without tips
522                                 // coordinates, on two different UV layers.
523                                 if (ma->mtex[a]->texflag & MTEX_TIPS)  {
524                                         BLI_strncpy(ma->mtex[a]->uvname, uvNames[1], sizeof(ma->mtex[a]->uvname));
525                                 }
526                                 else {
527                                         BLI_strncpy(ma->mtex[a]->uvname, uvNames[0], sizeof(ma->mtex[a]->uvname));
528                                 }
529                                 a++;
530                         }
531
532                         iStrokeRep->setMaterial(ma);
533                 }
534         }
535
536         const vector<Strip*>& strips = iStrokeRep->getStrips();
537         const bool hasTex = iStrokeRep->hasTex();
538         int totvert = 0, totedge = 0, totpoly = 0, totloop = 0;
539         int visible_faces, visible_segments;
540         for (vector<Strip*>::const_iterator s = strips.begin(), send = strips.end(); s != send; ++s) {
541                 Strip::vertex_container& strip_vertices = (*s)->vertices();
542
543                 // count visible faces and strip segments
544                 test_strip_visibility(strip_vertices, &visible_faces, &visible_segments);
545                 if (visible_faces == 0)
546                         continue;
547
548                 totvert += visible_faces + visible_segments * 2;
549                 totedge += visible_faces * 2 + visible_segments;
550                 totpoly += visible_faces;
551                 totloop += visible_faces * 3;
552         }
553
554         BlenderStrokeRenderer *self = const_cast<BlenderStrokeRenderer *>(this); // FIXME
555         vector<StrokeGroup*> *groups = hasTex ? &self->texturedStrokeGroups : &self->strokeGroups;
556         StrokeGroup *group;
557         if (groups->empty() || !(groups->back()->totvert + totvert < MESH_MAX_VERTS &&
558             groups->back()->totcol + 1 < MAXMAT))
559         {
560                 group = new StrokeGroup;
561                 groups->push_back(group);
562         }
563         else {
564                 group = groups->back();
565         }
566         group->strokes.push_back(iStrokeRep);
567         group->totvert += totvert;
568         group->totedge += totedge;
569         group->totpoly += totpoly;
570         group->totloop += totloop;
571         group->totcol++;
572 }
573
574 // Check if the triangle is visible (i.e., within the render image boundary)
575 bool BlenderStrokeRenderer::test_triangle_visibility(StrokeVertexRep *svRep[3]) const
576 {
577         int xl, xu, yl, yu;
578         Vec2r p;
579
580         xl = xu = yl = yu = 0;
581         for (int i = 0; i < 3; i++) {
582                 p = svRep[i]->point2d();
583                 if (p[0] < 0.0)
584                         xl++;
585                 else if (p[0] > _width)
586                         xu++;
587                 if (p[1] < 0.0)
588                         yl++;
589                 else if (p[1] > _height)
590                         yu++;
591         }
592         return !(xl == 3 || xu == 3 || yl == 3 || yu == 3);
593 }
594
595 // Check the visibility of faces and strip segments.
596 void BlenderStrokeRenderer::test_strip_visibility(Strip::vertex_container& strip_vertices,
597         int *visible_faces, int *visible_segments) const
598 {
599         const int strip_vertex_count = strip_vertices.size();
600         Strip::vertex_container::iterator v[3];
601         StrokeVertexRep *svRep[3];
602         bool visible;
603
604         // iterate over all vertices and count visible faces and strip segments
605         // (note: a strip segment is a series of visible faces, while two strip
606         // segments are separated by one or more invisible faces)
607         v[0] = strip_vertices.begin();
608         v[1] = v[0] + 1;
609         v[2] = v[0] + 2;
610         *visible_faces = *visible_segments = 0;
611         visible = false;
612         for (int n = 2; n < strip_vertex_count; n++, v[0]++, v[1]++, v[2]++) {
613                 svRep[0] = *(v[0]);
614                 svRep[1] = *(v[1]);
615                 svRep[2] = *(v[2]);
616                 if (test_triangle_visibility(svRep)) {
617                         (*visible_faces)++;
618                         if (!visible)
619                                 (*visible_segments)++;
620                         visible = true;
621                 }
622                 else {
623                         visible = false;
624                 }
625         }
626 }
627
628 // Release allocated memory for stroke groups
629 void BlenderStrokeRenderer::FreeStrokeGroups()
630 {
631         vector<StrokeGroup*>::const_iterator it, itend;
632
633         for (it = strokeGroups.begin(), itend = strokeGroups.end();
634              it != itend; ++it)
635         {
636                 delete (*it);
637         }
638         for (it = texturedStrokeGroups.begin(), itend = texturedStrokeGroups.end();
639              it != itend; ++it)
640         {
641                 delete (*it);
642         }
643 }
644
645 // Build a scene populated by mesh objects representing stylized strokes
646 int BlenderStrokeRenderer::GenerateScene()
647 {
648         vector<StrokeGroup*>::const_iterator it, itend;
649
650         for (it = strokeGroups.begin(), itend = strokeGroups.end();
651              it != itend; ++it)
652         {
653                 GenerateStrokeMesh(*it, false);
654         }
655         for (it = texturedStrokeGroups.begin(), itend = texturedStrokeGroups.end();
656              it != itend; ++it)
657         {
658                 GenerateStrokeMesh(*it, true);
659         }
660         return get_stroke_count();
661 }
662
663 // Return the number of strokes
664 int BlenderStrokeRenderer::get_stroke_count() const
665 {
666         return strokeGroups.size() + texturedStrokeGroups.size();
667 }
668
669 // Build a mesh object representing a group of stylized strokes
670 void BlenderStrokeRenderer::GenerateStrokeMesh(StrokeGroup *group, bool hasTex)
671 {
672 #if 0
673         Object *object_mesh = BKE_object_add(freestyle_bmain, freestyle_scene, OB_MESH);
674         DAG_relations_tag_update(freestyle_bmain);
675 #else
676         Object *object_mesh = NewMesh();
677 #endif
678         Mesh *mesh = (Mesh *)object_mesh->data;
679
680         mesh->totvert = group->totvert;
681         mesh->totedge = group->totedge;
682         mesh->totpoly = group->totpoly;
683         mesh->totloop = group->totloop;
684         mesh->totcol = group->totcol;
685
686         mesh->mvert = (MVert *)CustomData_add_layer(&mesh->vdata, CD_MVERT, CD_CALLOC, NULL, mesh->totvert);
687         mesh->medge = (MEdge *)CustomData_add_layer(&mesh->edata, CD_MEDGE, CD_CALLOC, NULL, mesh->totedge);
688         mesh->mpoly = (MPoly *)CustomData_add_layer(&mesh->pdata, CD_MPOLY, CD_CALLOC, NULL, mesh->totpoly);
689         mesh->mloop = (MLoop *)CustomData_add_layer(&mesh->ldata, CD_MLOOP, CD_CALLOC, NULL, mesh->totloop);
690
691         MVert *vertices = mesh->mvert;
692         MEdge *edges = mesh->medge;
693         MPoly *polys = mesh->mpoly;
694         MLoop *loops = mesh->mloop;
695         MLoopUV *loopsuv[2] = { NULL };
696
697         if (hasTex) {
698                 // First UV layer
699                 CustomData_add_layer_named(&mesh->pdata, CD_MTEXPOLY, CD_CALLOC, NULL, mesh->totpoly, uvNames[0]);
700                 CustomData_add_layer_named(&mesh->ldata, CD_MLOOPUV, CD_CALLOC, NULL, mesh->totloop, uvNames[0]);
701                 CustomData_set_layer_active(&mesh->pdata, CD_MTEXPOLY, 0);
702                 CustomData_set_layer_active(&mesh->ldata, CD_MLOOPUV, 0);
703                 BKE_mesh_update_customdata_pointers(mesh, true);
704                 loopsuv[0] = mesh->mloopuv;
705
706                 // Second UV layer
707                 CustomData_add_layer_named(&mesh->pdata, CD_MTEXPOLY, CD_CALLOC, NULL, mesh->totpoly, uvNames[1]);
708                 CustomData_add_layer_named(&mesh->ldata, CD_MLOOPUV, CD_CALLOC, NULL, mesh->totloop, uvNames[1]);
709                 CustomData_set_layer_active(&mesh->pdata, CD_MTEXPOLY, 1);
710                 CustomData_set_layer_active(&mesh->ldata, CD_MLOOPUV, 1);
711                 BKE_mesh_update_customdata_pointers(mesh, true);
712                 loopsuv[1] = mesh->mloopuv;
713         }
714
715         // colors and transparency (the latter represented by grayscale colors)
716         MLoopCol *colors = (MLoopCol *)CustomData_add_layer_named(&mesh->ldata, CD_MLOOPCOL, CD_CALLOC, NULL, mesh->totloop, "Color");
717         MLoopCol *transp = (MLoopCol *)CustomData_add_layer_named(&mesh->ldata, CD_MLOOPCOL, CD_CALLOC, NULL, mesh->totloop, "Alpha");
718         mesh->mloopcol = colors;
719
720         mesh->mat = (Material **)MEM_mallocN(sizeof(Material *) * mesh->totcol, "MaterialList");
721
722         ////////////////////
723         //  Data copy
724         ////////////////////
725
726         int vertex_index = 0, edge_index = 0, loop_index = 0, material_index = 0;
727         int visible_faces, visible_segments;
728         bool visible;
729         Strip::vertex_container::iterator v[3];
730         StrokeVertexRep *svRep[3];
731         Vec2r p;
732
733         for (vector<StrokeRep*>::const_iterator it = group->strokes.begin(), itend = group->strokes.end();
734              it != itend; ++it)
735         {
736                 mesh->mat[material_index] = (*it)->getMaterial();
737
738                 vector<Strip*>& strips = (*it)->getStrips();
739                 for (vector<Strip*>::const_iterator s = strips.begin(), send = strips.end(); s != send; ++s) {
740                         Strip::vertex_container& strip_vertices = (*s)->vertices();
741                         int strip_vertex_count = strip_vertices.size();
742
743                         // count visible faces and strip segments
744                         test_strip_visibility(strip_vertices, &visible_faces, &visible_segments);
745                         if (visible_faces == 0)
746                                 continue;
747
748                         v[0] = strip_vertices.begin();
749                         v[1] = v[0] + 1;
750                         v[2] = v[0] + 2;
751
752                         visible = false;
753
754                         // Note: Mesh generation in the following loop assumes stroke strips
755                         // to be triangle strips.
756                         for (int n = 2; n < strip_vertex_count; n++, v[0]++, v[1]++, v[2]++) {
757                                 svRep[0] = *(v[0]);
758                                 svRep[1] = *(v[1]);
759                                 svRep[2] = *(v[2]);
760                                 if (!test_triangle_visibility(svRep)) {
761                                         visible = false;
762                                 }
763                                 else {
764                                         if (!visible) {
765                                                 // first vertex
766                                                 vertices->co[0] = svRep[0]->point2d()[0];
767                                                 vertices->co[1] = svRep[0]->point2d()[1];
768                                                 vertices->co[2] = get_stroke_vertex_z();
769                                                 vertices->no[0] = 0;
770                                                 vertices->no[1] = 0;
771                                                 vertices->no[2] = SHRT_MAX;
772                                                 ++vertices;
773                                                 ++vertex_index;
774
775                                                 // second vertex
776                                                 vertices->co[0] = svRep[1]->point2d()[0];
777                                                 vertices->co[1] = svRep[1]->point2d()[1];
778                                                 vertices->co[2] = get_stroke_vertex_z();
779                                                 vertices->no[0] = 0;
780                                                 vertices->no[1] = 0;
781                                                 vertices->no[2] = SHRT_MAX;
782                                                 ++vertices;
783                                                 ++vertex_index;
784
785                                                 // first edge
786                                                 edges->v1 = vertex_index - 2;
787                                                 edges->v2 = vertex_index - 1;
788                                                 ++edges;
789                                                 ++edge_index;
790                                         }
791                                         visible = true;
792
793                                         // vertex
794                                         vertices->co[0] = svRep[2]->point2d()[0];
795                                         vertices->co[1] = svRep[2]->point2d()[1];
796                                         vertices->co[2] = get_stroke_vertex_z();
797                                         vertices->no[0] = 0;
798                                         vertices->no[1] = 0;
799                                         vertices->no[2] = SHRT_MAX;
800                                         ++vertices;
801                                         ++vertex_index;
802
803                                         // edges
804                                         edges->v1 = vertex_index - 1;
805                                         edges->v2 = vertex_index - 3;
806                                         ++edges;
807                                         ++edge_index;
808
809                                         edges->v1 = vertex_index - 1;
810                                         edges->v2 = vertex_index - 2;
811                                         ++edges;
812                                         ++edge_index;
813
814                                         // poly
815                                         polys->loopstart = loop_index;
816                                         polys->totloop = 3;
817                                         polys->mat_nr = material_index;
818                                         ++polys;
819
820                                         // Even and odd loops connect triangles vertices differently
821                                         bool is_odd = n % 2;
822                                         // loops
823                                         if (is_odd) {
824                                                 loops[0].v = vertex_index - 1;
825                                                 loops[0].e = edge_index - 2;
826
827                                                 loops[1].v = vertex_index - 3;
828                                                 loops[1].e = edge_index - 3;
829
830                                                 loops[2].v = vertex_index - 2;
831                                                 loops[2].e = edge_index - 1;
832                                         }
833                                         else {
834                                                 loops[0].v = vertex_index - 1;
835                                                 loops[0].e = edge_index - 1;
836
837                                                 loops[1].v = vertex_index - 2;
838                                                 loops[1].e = edge_index - 3;
839
840                                                 loops[2].v = vertex_index - 3;
841                                                 loops[2].e = edge_index - 2;
842                                         }
843                                         loops += 3;
844                                         loop_index += 3;
845
846                                         // UV
847                                         if (hasTex) {
848                                                 // First UV layer (loopsuv[0]) has no tips (texCoord(0)).
849                                                 // Second UV layer (loopsuv[1]) has tips:  (texCoord(1)).
850                                                 for (int L = 0; L < 2; L++) {
851                                                         if (is_odd) {
852                                                                 loopsuv[L][0].uv[0] = svRep[2]->texCoord(L).x();
853                                                                 loopsuv[L][0].uv[1] = svRep[2]->texCoord(L).y();
854
855                                                                 loopsuv[L][1].uv[0] = svRep[0]->texCoord(L).x();
856                                                                 loopsuv[L][1].uv[1] = svRep[0]->texCoord(L).y();
857
858                                                                 loopsuv[L][2].uv[0] = svRep[1]->texCoord(L).x();
859                                                                 loopsuv[L][2].uv[1] = svRep[1]->texCoord(L).y();
860                                                         }
861                                                         else {
862                                                                 loopsuv[L][0].uv[0] = svRep[2]->texCoord(L).x();
863                                                                 loopsuv[L][0].uv[1] = svRep[2]->texCoord(L).y();
864
865                                                                 loopsuv[L][1].uv[0] = svRep[1]->texCoord(L).x();
866                                                                 loopsuv[L][1].uv[1] = svRep[1]->texCoord(L).y();
867
868                                                                 loopsuv[L][2].uv[0] = svRep[0]->texCoord(L).x();
869                                                                 loopsuv[L][2].uv[1] = svRep[0]->texCoord(L).y();
870                                                         }
871                                                         loopsuv[L] += 3;
872                                                 }
873                                         }
874
875                                         // colors and alpha transparency. vertex colors are in sRGB
876                                         // space by convention, so convert from linear
877                                         float rgba[3][4];
878
879                                         for (int i = 0; i < 3; i++) {
880                                                 copy_v3fl_v3db(rgba[i], &svRep[i]->color()[0]);
881                                                 rgba[i][3] = svRep[i]->alpha();
882                                         }
883
884                                         if (is_odd) {
885                                                 linearrgb_to_srgb_uchar4(&colors[0].r, rgba[2]);
886                                                 linearrgb_to_srgb_uchar4(&colors[1].r, rgba[0]);
887                                                 linearrgb_to_srgb_uchar4(&colors[2].r, rgba[1]);
888                                         }
889                                         else {
890                                                 linearrgb_to_srgb_uchar4(&colors[0].r, rgba[2]);
891                                                 linearrgb_to_srgb_uchar4(&colors[1].r, rgba[1]);
892                                                 linearrgb_to_srgb_uchar4(&colors[2].r, rgba[0]);
893                                         }
894                                         transp[0].r = transp[0].g = transp[0].b = colors[0].a;
895                                         transp[1].r = transp[1].g = transp[1].b = colors[1].a;
896                                         transp[2].r = transp[2].g = transp[2].b = colors[2].a;
897                                         colors += 3;
898                                         transp += 3;
899                                 }
900                         } // loop over strip vertices
901                 } // loop over strips
902                 material_index++;
903         } // loop over strokes
904
905         test_object_materials(freestyle_bmain, (ID *)mesh);
906
907 #if 0 // XXX
908         BLI_assert(mesh->totvert == vertex_index);
909         BLI_assert(mesh->totedge == edge_index);
910         BLI_assert(mesh->totloop == loop_index);
911         BLI_assert(mesh->totcol == material_index);
912         BKE_mesh_validate(mesh, true, true);
913 #endif
914 }
915
916 // A replacement of BKE_object_add() for better performance.
917 Object *BlenderStrokeRenderer::NewMesh() const
918 {
919         Object *ob;
920         Base *base;
921         char name[MAX_ID_NAME];
922         unsigned int mesh_id = get_stroke_mesh_id();
923
924         BLI_snprintf(name, MAX_ID_NAME, "0%08xOB", mesh_id);
925         ob = BKE_object_add_only_object(freestyle_bmain, OB_MESH, name);
926         BLI_snprintf(name, MAX_ID_NAME, "0%08xME", mesh_id);
927         ob->data = BKE_mesh_add(freestyle_bmain, name);
928         ob->lay = 1;
929
930         base = BKE_scene_base_add(freestyle_scene, ob);
931         DAG_relations_tag_update(freestyle_bmain);
932 #if 0
933         BKE_scene_base_deselect_all(scene);
934         BKE_scene_base_select(scene, base);
935 #else
936         (void)base;
937 #endif
938
939         DAG_id_tag_update_ex(freestyle_bmain, &ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
940
941         return ob;
942 }
943
944 Render *BlenderStrokeRenderer::RenderScene(Render * /*re*/, bool render)
945 {
946         Camera *camera = (Camera *)freestyle_scene->camera->data;
947         if (camera->clipend < _z)
948                 camera->clipend = _z + _z_delta * 100.0f;
949 #if 0
950         if (G.debug & G_DEBUG_FREESTYLE) {
951                 cout << "clipsta " << camera->clipsta << ", clipend " << camera->clipend << endl;
952         }
953 #endif
954
955         Render *freestyle_render = RE_NewRender(freestyle_scene->id.name);
956
957         RE_RenderFreestyleStrokes(freestyle_render, freestyle_bmain, freestyle_scene,
958                                   render && get_stroke_count() > 0);
959
960         return freestyle_render;
961 }
962
963 } /* namespace Freestyle */