Fix build error on Windows 32 bit.
[blender-staging.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         id_us_min(&ma->id);
247
248         if (iNodeTree) {
249                 // make a copy of linestyle->nodetree
250                 ntree = ntreeCopyTree_ex(iNodeTree, bmain, do_id_user);
251
252                 // find the active Output Line Style node
253                 for (bNode *node = (bNode *)ntree->nodes.first; node; node = node->next) {
254                         if (node->type == SH_NODE_OUTPUT_LINESTYLE && (node->flag & NODE_DO_OUTPUT)) {
255                                 output_linestyle = node;
256                                 break;
257                         }
258                 }
259         }
260         else {
261                 ntree = ntreeAddTree(NULL, "stroke_shader", "ShaderNodeTree");
262         }
263         ma->nodetree = ntree;
264         ma->use_nodes = 1;
265
266         bNode *input_attr_color = nodeAddStaticNode(NULL, ntree, SH_NODE_ATTRIBUTE);
267         input_attr_color->locx = 0.0f;
268         input_attr_color->locy = -200.0f;
269         storage = (NodeShaderAttribute *)input_attr_color->storage;
270         BLI_strncpy(storage->name, "Color", sizeof(storage->name));
271
272         bNode *mix_rgb_color = nodeAddStaticNode(NULL, ntree, SH_NODE_MIX_RGB);
273         mix_rgb_color->custom1 = MA_RAMP_BLEND; // Mix
274         mix_rgb_color->locx = 200.0f;
275         mix_rgb_color->locy = -200.0f;
276         tosock = (bNodeSocket *)BLI_findlink(&mix_rgb_color->inputs, 0); // Fac
277         RNA_pointer_create((ID *)ntree, &RNA_NodeSocket, tosock, &toptr);
278         RNA_float_set(&toptr, "default_value", 0.0f);
279
280         bNode *input_attr_alpha = nodeAddStaticNode(NULL, ntree, SH_NODE_ATTRIBUTE);
281         input_attr_alpha->locx = 400.0f;
282         input_attr_alpha->locy = 300.0f;
283         storage = (NodeShaderAttribute *)input_attr_alpha->storage;
284         BLI_strncpy(storage->name, "Alpha", sizeof(storage->name));
285
286         bNode *mix_rgb_alpha = nodeAddStaticNode(NULL, ntree, SH_NODE_MIX_RGB);
287         mix_rgb_alpha->custom1 = MA_RAMP_BLEND; // Mix
288         mix_rgb_alpha->locx = 600.0f;
289         mix_rgb_alpha->locy = 300.0f;
290         tosock = (bNodeSocket *)BLI_findlink(&mix_rgb_alpha->inputs, 0); // Fac
291         RNA_pointer_create((ID *)ntree, &RNA_NodeSocket, tosock, &toptr);
292         RNA_float_set(&toptr, "default_value", 0.0f);
293
294         bNode *shader_emission = nodeAddStaticNode(NULL, ntree, SH_NODE_EMISSION);
295         shader_emission->locx = 400.0f;
296         shader_emission->locy = -200.0f;
297
298         bNode *input_light_path = nodeAddStaticNode(NULL, ntree, SH_NODE_LIGHT_PATH);
299         input_light_path->locx = 400.0f;
300         input_light_path->locy = 100.0f;
301
302         bNode *mix_shader_color = nodeAddStaticNode(NULL, ntree, SH_NODE_MIX_SHADER);
303         mix_shader_color->locx = 600.0f;
304         mix_shader_color->locy = -100.0f;
305
306         bNode *shader_transparent = nodeAddStaticNode(NULL, ntree, SH_NODE_BSDF_TRANSPARENT);
307         shader_transparent->locx = 600.0f;
308         shader_transparent->locy = 100.0f;
309
310         bNode *mix_shader_alpha = nodeAddStaticNode(NULL, ntree, SH_NODE_MIX_SHADER);
311         mix_shader_alpha->locx = 800.0f;
312         mix_shader_alpha->locy = 100.0f;
313
314         bNode *output_material = nodeAddStaticNode(NULL, ntree, SH_NODE_OUTPUT_MATERIAL);
315         output_material->locx = 1000.0f;
316         output_material->locy = 100.0f;
317
318         fromsock = (bNodeSocket *)BLI_findlink(&input_attr_color->outputs, 0); // Color
319         tosock = (bNodeSocket *)BLI_findlink(&mix_rgb_color->inputs, 1); // Color1
320         nodeAddLink(ntree, input_attr_color, fromsock, mix_rgb_color, tosock);
321
322         fromsock = (bNodeSocket *)BLI_findlink(&mix_rgb_color->outputs, 0); // Color
323         tosock = (bNodeSocket *)BLI_findlink(&shader_emission->inputs, 0); // Color
324         nodeAddLink(ntree, mix_rgb_color, fromsock, shader_emission, tosock);
325
326         fromsock = (bNodeSocket *)BLI_findlink(&shader_emission->outputs, 0); // Emission
327         tosock = (bNodeSocket *)BLI_findlink(&mix_shader_color->inputs, 2); // Shader (second)
328         nodeAddLink(ntree, shader_emission, fromsock, mix_shader_color, tosock);
329
330         fromsock = (bNodeSocket *)BLI_findlink(&input_light_path->outputs, 0); // In Camera Ray
331         tosock = (bNodeSocket *)BLI_findlink(&mix_shader_color->inputs, 0); // Fac
332         nodeAddLink(ntree, input_light_path, fromsock, mix_shader_color, tosock);
333
334         fromsock = (bNodeSocket *)BLI_findlink(&mix_rgb_alpha->outputs, 0); // Color
335         tosock = (bNodeSocket *)BLI_findlink(&mix_shader_alpha->inputs, 0); // Fac
336         nodeAddLink(ntree, mix_rgb_alpha, fromsock, mix_shader_alpha, tosock);
337
338         fromsock = (bNodeSocket *)BLI_findlink(&input_attr_alpha->outputs, 0); // Color
339         tosock = (bNodeSocket *)BLI_findlink(&mix_rgb_alpha->inputs, 1); // Color1
340         nodeAddLink(ntree, input_attr_alpha, fromsock, mix_rgb_alpha, tosock);
341
342         fromsock = (bNodeSocket *)BLI_findlink(&shader_transparent->outputs, 0); // BSDF
343         tosock = (bNodeSocket *)BLI_findlink(&mix_shader_alpha->inputs, 1); // Shader (first)
344         nodeAddLink(ntree, shader_transparent, fromsock, mix_shader_alpha, tosock);
345
346         fromsock = (bNodeSocket *)BLI_findlink(&mix_shader_color->outputs, 0); // Shader
347         tosock = (bNodeSocket *)BLI_findlink(&mix_shader_alpha->inputs, 2); // Shader (second)
348         nodeAddLink(ntree, mix_shader_color, fromsock, mix_shader_alpha, tosock);
349
350         fromsock = (bNodeSocket *)BLI_findlink(&mix_shader_alpha->outputs, 0); // Shader
351         tosock = (bNodeSocket *)BLI_findlink(&output_material->inputs, 0); // Surface
352         nodeAddLink(ntree, mix_shader_alpha, fromsock, output_material, tosock);
353
354         if (output_linestyle) {
355                 bNodeSocket *outsock;
356                 bNodeLink *link;
357
358                 mix_rgb_color->custom1 = output_linestyle->custom1; // blend_type
359                 mix_rgb_color->custom2 = output_linestyle->custom2; // use_clamp
360
361                 outsock = (bNodeSocket *)BLI_findlink(&output_linestyle->inputs, 0); // Color
362                 tosock = (bNodeSocket *)BLI_findlink(&mix_rgb_color->inputs, 2); // Color2
363                 link = (bNodeLink *)BLI_findptr(&ntree->links, outsock, offsetof(bNodeLink, tosock));
364                 if (link) {
365                         nodeAddLink(ntree, link->fromnode, link->fromsock, mix_rgb_color, tosock);
366                 }
367                 else {
368                         float color[4];
369                         RNA_pointer_create((ID *)ntree, &RNA_NodeSocket, outsock, &fromptr);
370                         RNA_pointer_create((ID *)ntree, &RNA_NodeSocket, tosock, &toptr);
371                         RNA_float_get_array(&fromptr, "default_value", color);
372                         RNA_float_set_array(&toptr, "default_value", color);
373                 }
374
375                 outsock = (bNodeSocket *)BLI_findlink(&output_linestyle->inputs, 1); // Color Fac
376                 tosock = (bNodeSocket *)BLI_findlink(&mix_rgb_color->inputs, 0); // Fac
377                 link = (bNodeLink *)BLI_findptr(&ntree->links, outsock, offsetof(bNodeLink, tosock));
378                 if (link) {
379                         nodeAddLink(ntree, link->fromnode, link->fromsock, mix_rgb_color, tosock);
380                 }
381                 else {
382                         RNA_pointer_create((ID *)ntree, &RNA_NodeSocket, outsock, &fromptr);
383                         RNA_pointer_create((ID *)ntree, &RNA_NodeSocket, tosock, &toptr);
384                         RNA_float_set(&toptr, "default_value", RNA_float_get(&fromptr, "default_value"));
385                 }
386
387                 outsock = (bNodeSocket *)BLI_findlink(&output_linestyle->inputs, 2); // Alpha
388                 tosock = (bNodeSocket *)BLI_findlink(&mix_rgb_alpha->inputs, 2); // Color2
389                 link = (bNodeLink *)BLI_findptr(&ntree->links, outsock, offsetof(bNodeLink, tosock));
390                 if (link) {
391                         nodeAddLink(ntree, link->fromnode, link->fromsock, mix_rgb_alpha, tosock);
392                 }
393                 else {
394                         float color[4];
395                         RNA_pointer_create((ID *)ntree, &RNA_NodeSocket, outsock, &fromptr);
396                         RNA_pointer_create((ID *)ntree, &RNA_NodeSocket, tosock, &toptr);
397                         color[0] = color[1] = color[2] = RNA_float_get(&fromptr, "default_value");
398                         color[3] = 1.0f;
399                         RNA_float_set_array(&toptr, "default_value", color);
400                 }
401
402                 outsock = (bNodeSocket *)BLI_findlink(&output_linestyle->inputs, 3); // Alpha Fac
403                 tosock = (bNodeSocket *)BLI_findlink(&mix_rgb_alpha->inputs, 0); // Fac
404                 link = (bNodeLink *)BLI_findptr(&ntree->links, outsock, offsetof(bNodeLink, tosock));
405                 if (link) {
406                         nodeAddLink(ntree, link->fromnode, link->fromsock, mix_rgb_alpha, tosock);
407                 }
408                 else {
409                         RNA_pointer_create((ID *)ntree, &RNA_NodeSocket, outsock, &fromptr);
410                         RNA_pointer_create((ID *)ntree, &RNA_NodeSocket, tosock, &toptr);
411                         RNA_float_set(&toptr, "default_value", RNA_float_get(&fromptr, "default_value"));
412                 }
413
414                 for (bNode *node = (bNode *)ntree->nodes.first; node; node = node->next) {
415                         if (node->type == SH_NODE_UVALONGSTROKE) {
416                                 // UV output of the UV Along Stroke node
417                                 bNodeSocket *sock = (bNodeSocket *)BLI_findlink(&node->outputs, 0);
418
419                                 // add new UV Map node
420                                 bNode *input_uvmap = nodeAddStaticNode(NULL, ntree, SH_NODE_UVMAP);
421                                 input_uvmap->locx = node->locx - 200.0f;
422                                 input_uvmap->locy = node->locy;
423                                 NodeShaderUVMap *storage = (NodeShaderUVMap *)input_uvmap->storage;
424                                 if (node->custom1 & 1) { // use_tips
425                                         BLI_strncpy(storage->uv_map, uvNames[1], sizeof(storage->uv_map));
426                                 }
427                                 else {
428                                         BLI_strncpy(storage->uv_map, uvNames[0], sizeof(storage->uv_map));
429                                 }
430                                 fromsock = (bNodeSocket *)BLI_findlink(&input_uvmap->outputs, 0); // UV
431
432                                 // replace links from the UV Along Stroke node by links from the UV Map node
433                                 for (bNodeLink *link = (bNodeLink *)ntree->links.first; link; link = link->next) {
434                                         if (link->fromnode == node && link->fromsock == sock) {
435                                                 nodeAddLink(ntree, input_uvmap, fromsock, link->tonode, link->tosock);
436                                         }
437                                 }
438                                 nodeRemSocketLinks(ntree, sock);
439                         }
440                 }
441         }
442
443         nodeSetActive(ntree, output_material);
444         ntreeUpdateTree(bmain, ntree);
445
446         return ma;
447 }
448
449 void BlenderStrokeRenderer::RenderStrokeRep(StrokeRep *iStrokeRep) const
450 {
451         RenderStrokeRepBasic(iStrokeRep);
452 }
453
454 void BlenderStrokeRenderer::RenderStrokeRepBasic(StrokeRep *iStrokeRep) const
455 {
456         if (_use_shading_nodes) {
457                 bNodeTree *nt = iStrokeRep->getNodeTree();
458                 Material *ma = (Material *)BLI_ghash_lookup(_nodetree_hash, nt);
459                 if (!ma) {
460                         ma = BlenderStrokeRenderer::GetStrokeShader(freestyle_bmain, nt, false);
461                         BLI_ghash_insert(_nodetree_hash, nt, ma);
462                 }
463
464                 if (STREQ(freestyle_scene->r.engine, RE_engine_id_CYCLES)) {
465                         PointerRNA scene_ptr, freestyle_scene_ptr;
466                         RNA_pointer_create(NULL, &RNA_Scene, old_scene, &scene_ptr);
467                         RNA_pointer_create(NULL, &RNA_Scene, freestyle_scene, &freestyle_scene_ptr);
468
469                         PointerRNA cycles_ptr = RNA_pointer_get(&scene_ptr, "cycles");
470                         PointerRNA freestyle_cycles_ptr = RNA_pointer_get(&freestyle_scene_ptr, "cycles");
471
472                         int flag;
473                         RNA_STRUCT_BEGIN(&freestyle_cycles_ptr, prop)
474                         {
475                                 flag = RNA_property_flag(prop);
476                                 if (flag & PROP_HIDDEN)
477                                         continue;
478                                 RNA_property_copy(&freestyle_cycles_ptr, &cycles_ptr, prop, -1);
479                         }
480                         RNA_STRUCT_END;
481
482                         RNA_boolean_set(&freestyle_cycles_ptr, "film_transparent", 1);
483                 }
484
485                 iStrokeRep->setMaterial(ma);
486         }
487         else {
488                 bool has_mat = false;
489                 int a = 0;
490
491                 // Look for a good existing material
492                 for (Link *lnk = (Link *)freestyle_bmain->mat.first; lnk; lnk = lnk->next) {
493                         Material *ma = (Material*)lnk;
494                         bool texs_are_good = true;
495                         // as soon as textures differ it's not the right one
496                         for (int a = 0; a < MAX_MTEX; a++) {
497                                 if (ma->mtex[a] != iStrokeRep->getMTex(a)) {
498                                         texs_are_good = false;
499                                         break;
500                                 }
501                         }
502
503                         if (texs_are_good) {
504                                 iStrokeRep->setMaterial(ma);
505                                 has_mat = true;
506                                 break; // if textures are good, no need to search anymore
507                         }
508                 }
509
510                 // If still no material, create one
511                 if (!has_mat) {
512                         Material *ma = BKE_material_add(freestyle_bmain, "stroke_material");
513                         DAG_relations_tag_update(freestyle_bmain);
514                         ma->mode |= MA_VERTEXCOLP;
515                         ma->mode |= MA_TRANSP;
516                         ma->mode |= MA_SHLESS;
517                         ma->vcol_alpha = 1;
518
519                         id_us_min(&ma->id);
520
521                         // Textures
522                         while (iStrokeRep->getMTex(a)) {
523                                 ma->mtex[a] = (MTex *)iStrokeRep->getMTex(a);
524
525                                 // We'll generate both with tips and without tips
526                                 // coordinates, on two different UV layers.
527                                 if (ma->mtex[a]->texflag & MTEX_TIPS) {
528                                         BLI_strncpy(ma->mtex[a]->uvname, uvNames[1], sizeof(ma->mtex[a]->uvname));
529                                 }
530                                 else {
531                                         BLI_strncpy(ma->mtex[a]->uvname, uvNames[0], sizeof(ma->mtex[a]->uvname));
532                                 }
533                                 a++;
534                         }
535
536                         iStrokeRep->setMaterial(ma);
537                 }
538         }
539
540         const vector<Strip*>& strips = iStrokeRep->getStrips();
541         const bool hasTex = iStrokeRep->hasTex();
542         int totvert = 0, totedge = 0, totpoly = 0, totloop = 0;
543         int visible_faces, visible_segments;
544         for (vector<Strip*>::const_iterator s = strips.begin(), send = strips.end(); s != send; ++s) {
545                 Strip::vertex_container& strip_vertices = (*s)->vertices();
546
547                 // count visible faces and strip segments
548                 test_strip_visibility(strip_vertices, &visible_faces, &visible_segments);
549                 if (visible_faces == 0)
550                         continue;
551
552                 totvert += visible_faces + visible_segments * 2;
553                 totedge += visible_faces * 2 + visible_segments;
554                 totpoly += visible_faces;
555                 totloop += visible_faces * 3;
556         }
557
558         BlenderStrokeRenderer *self = const_cast<BlenderStrokeRenderer *>(this); // FIXME
559         vector<StrokeGroup*> *groups = hasTex ? &self->texturedStrokeGroups : &self->strokeGroups;
560         StrokeGroup *group;
561         if (groups->empty() || !(groups->back()->totvert + totvert < MESH_MAX_VERTS &&
562             groups->back()->totcol + 1 < MAXMAT))
563         {
564                 group = new StrokeGroup;
565                 groups->push_back(group);
566         }
567         else {
568                 group = groups->back();
569         }
570         group->strokes.push_back(iStrokeRep);
571         group->totvert += totvert;
572         group->totedge += totedge;
573         group->totpoly += totpoly;
574         group->totloop += totloop;
575         group->totcol++;
576 }
577
578 // Check if the triangle is visible (i.e., within the render image boundary)
579 bool BlenderStrokeRenderer::test_triangle_visibility(StrokeVertexRep *svRep[3]) const
580 {
581         int xl, xu, yl, yu;
582         Vec2r p;
583
584         xl = xu = yl = yu = 0;
585         for (int i = 0; i < 3; i++) {
586                 p = svRep[i]->point2d();
587                 if (p[0] < 0.0)
588                         xl++;
589                 else if (p[0] > _width)
590                         xu++;
591                 if (p[1] < 0.0)
592                         yl++;
593                 else if (p[1] > _height)
594                         yu++;
595         }
596         return !(xl == 3 || xu == 3 || yl == 3 || yu == 3);
597 }
598
599 // Check the visibility of faces and strip segments.
600 void BlenderStrokeRenderer::test_strip_visibility(Strip::vertex_container& strip_vertices,
601         int *visible_faces, int *visible_segments) const
602 {
603         const int strip_vertex_count = strip_vertices.size();
604         Strip::vertex_container::iterator v[3];
605         StrokeVertexRep *svRep[3];
606         bool visible;
607
608         // iterate over all vertices and count visible faces and strip segments
609         // (note: a strip segment is a series of visible faces, while two strip
610         // segments are separated by one or more invisible faces)
611         v[0] = strip_vertices.begin();
612         v[1] = v[0] + 1;
613         v[2] = v[0] + 2;
614         *visible_faces = *visible_segments = 0;
615         visible = false;
616         for (int n = 2; n < strip_vertex_count; n++, v[0]++, v[1]++, v[2]++) {
617                 svRep[0] = *(v[0]);
618                 svRep[1] = *(v[1]);
619                 svRep[2] = *(v[2]);
620                 if (test_triangle_visibility(svRep)) {
621                         (*visible_faces)++;
622                         if (!visible)
623                                 (*visible_segments)++;
624                         visible = true;
625                 }
626                 else {
627                         visible = false;
628                 }
629         }
630 }
631
632 // Release allocated memory for stroke groups
633 void BlenderStrokeRenderer::FreeStrokeGroups()
634 {
635         vector<StrokeGroup*>::const_iterator it, itend;
636
637         for (it = strokeGroups.begin(), itend = strokeGroups.end();
638              it != itend; ++it)
639         {
640                 delete (*it);
641         }
642         for (it = texturedStrokeGroups.begin(), itend = texturedStrokeGroups.end();
643              it != itend; ++it)
644         {
645                 delete (*it);
646         }
647 }
648
649 // Build a scene populated by mesh objects representing stylized strokes
650 int BlenderStrokeRenderer::GenerateScene()
651 {
652         vector<StrokeGroup*>::const_iterator it, itend;
653
654         for (it = strokeGroups.begin(), itend = strokeGroups.end();
655              it != itend; ++it)
656         {
657                 GenerateStrokeMesh(*it, false);
658         }
659         for (it = texturedStrokeGroups.begin(), itend = texturedStrokeGroups.end();
660              it != itend; ++it)
661         {
662                 GenerateStrokeMesh(*it, true);
663         }
664         return get_stroke_count();
665 }
666
667 // Return the number of strokes
668 int BlenderStrokeRenderer::get_stroke_count() const
669 {
670         return strokeGroups.size() + texturedStrokeGroups.size();
671 }
672
673 // Build a mesh object representing a group of stylized strokes
674 void BlenderStrokeRenderer::GenerateStrokeMesh(StrokeGroup *group, bool hasTex)
675 {
676 #if 0
677         Object *object_mesh = BKE_object_add(freestyle_bmain, freestyle_scene, OB_MESH);
678         DAG_relations_tag_update(freestyle_bmain);
679 #else
680         Object *object_mesh = NewMesh();
681 #endif
682         Mesh *mesh = (Mesh *)object_mesh->data;
683
684         mesh->totvert = group->totvert;
685         mesh->totedge = group->totedge;
686         mesh->totpoly = group->totpoly;
687         mesh->totloop = group->totloop;
688         mesh->totcol = group->totcol;
689
690         mesh->mvert = (MVert *)CustomData_add_layer(&mesh->vdata, CD_MVERT, CD_CALLOC, NULL, mesh->totvert);
691         mesh->medge = (MEdge *)CustomData_add_layer(&mesh->edata, CD_MEDGE, CD_CALLOC, NULL, mesh->totedge);
692         mesh->mpoly = (MPoly *)CustomData_add_layer(&mesh->pdata, CD_MPOLY, CD_CALLOC, NULL, mesh->totpoly);
693         mesh->mloop = (MLoop *)CustomData_add_layer(&mesh->ldata, CD_MLOOP, CD_CALLOC, NULL, mesh->totloop);
694
695         MVert *vertices = mesh->mvert;
696         MEdge *edges = mesh->medge;
697         MPoly *polys = mesh->mpoly;
698         MLoop *loops = mesh->mloop;
699         MLoopUV *loopsuv[2] = { NULL };
700
701         if (hasTex) {
702                 // First UV layer
703                 CustomData_add_layer_named(&mesh->pdata, CD_MTEXPOLY, CD_CALLOC, NULL, mesh->totpoly, uvNames[0]);
704                 CustomData_add_layer_named(&mesh->ldata, CD_MLOOPUV, CD_CALLOC, NULL, mesh->totloop, uvNames[0]);
705                 CustomData_set_layer_active(&mesh->pdata, CD_MTEXPOLY, 0);
706                 CustomData_set_layer_active(&mesh->ldata, CD_MLOOPUV, 0);
707                 BKE_mesh_update_customdata_pointers(mesh, true);
708                 loopsuv[0] = mesh->mloopuv;
709
710                 // Second UV layer
711                 CustomData_add_layer_named(&mesh->pdata, CD_MTEXPOLY, CD_CALLOC, NULL, mesh->totpoly, uvNames[1]);
712                 CustomData_add_layer_named(&mesh->ldata, CD_MLOOPUV, CD_CALLOC, NULL, mesh->totloop, uvNames[1]);
713                 CustomData_set_layer_active(&mesh->pdata, CD_MTEXPOLY, 1);
714                 CustomData_set_layer_active(&mesh->ldata, CD_MLOOPUV, 1);
715                 BKE_mesh_update_customdata_pointers(mesh, true);
716                 loopsuv[1] = mesh->mloopuv;
717         }
718
719         // colors and transparency (the latter represented by grayscale colors)
720         MLoopCol *colors = (MLoopCol *)CustomData_add_layer_named(&mesh->ldata, CD_MLOOPCOL, CD_CALLOC, NULL, mesh->totloop, "Color");
721         MLoopCol *transp = (MLoopCol *)CustomData_add_layer_named(&mesh->ldata, CD_MLOOPCOL, CD_CALLOC, NULL, mesh->totloop, "Alpha");
722         mesh->mloopcol = colors;
723
724         mesh->mat = (Material **)MEM_mallocN(sizeof(Material *) * mesh->totcol, "MaterialList");
725
726         ////////////////////
727         //  Data copy
728         ////////////////////
729
730         int vertex_index = 0, edge_index = 0, loop_index = 0, material_index = 0;
731         int visible_faces, visible_segments;
732         bool visible;
733         Strip::vertex_container::iterator v[3];
734         StrokeVertexRep *svRep[3];
735         Vec2r p;
736
737         for (vector<StrokeRep*>::const_iterator it = group->strokes.begin(), itend = group->strokes.end();
738              it != itend; ++it)
739         {
740                 mesh->mat[material_index] = (*it)->getMaterial();
741                 id_us_plus(&mesh->mat[material_index]->id);
742
743                 vector<Strip*>& strips = (*it)->getStrips();
744                 for (vector<Strip*>::const_iterator s = strips.begin(), send = strips.end(); s != send; ++s) {
745                         Strip::vertex_container& strip_vertices = (*s)->vertices();
746                         int strip_vertex_count = strip_vertices.size();
747
748                         // count visible faces and strip segments
749                         test_strip_visibility(strip_vertices, &visible_faces, &visible_segments);
750                         if (visible_faces == 0)
751                                 continue;
752
753                         v[0] = strip_vertices.begin();
754                         v[1] = v[0] + 1;
755                         v[2] = v[0] + 2;
756
757                         visible = false;
758
759                         // Note: Mesh generation in the following loop assumes stroke strips
760                         // to be triangle strips.
761                         for (int n = 2; n < strip_vertex_count; n++, v[0]++, v[1]++, v[2]++) {
762                                 svRep[0] = *(v[0]);
763                                 svRep[1] = *(v[1]);
764                                 svRep[2] = *(v[2]);
765                                 if (!test_triangle_visibility(svRep)) {
766                                         visible = false;
767                                 }
768                                 else {
769                                         if (!visible) {
770                                                 // first vertex
771                                                 vertices->co[0] = svRep[0]->point2d()[0];
772                                                 vertices->co[1] = svRep[0]->point2d()[1];
773                                                 vertices->co[2] = get_stroke_vertex_z();
774                                                 vertices->no[0] = 0;
775                                                 vertices->no[1] = 0;
776                                                 vertices->no[2] = SHRT_MAX;
777                                                 ++vertices;
778                                                 ++vertex_index;
779
780                                                 // second vertex
781                                                 vertices->co[0] = svRep[1]->point2d()[0];
782                                                 vertices->co[1] = svRep[1]->point2d()[1];
783                                                 vertices->co[2] = get_stroke_vertex_z();
784                                                 vertices->no[0] = 0;
785                                                 vertices->no[1] = 0;
786                                                 vertices->no[2] = SHRT_MAX;
787                                                 ++vertices;
788                                                 ++vertex_index;
789
790                                                 // first edge
791                                                 edges->v1 = vertex_index - 2;
792                                                 edges->v2 = vertex_index - 1;
793                                                 ++edges;
794                                                 ++edge_index;
795                                         }
796                                         visible = true;
797
798                                         // vertex
799                                         vertices->co[0] = svRep[2]->point2d()[0];
800                                         vertices->co[1] = svRep[2]->point2d()[1];
801                                         vertices->co[2] = get_stroke_vertex_z();
802                                         vertices->no[0] = 0;
803                                         vertices->no[1] = 0;
804                                         vertices->no[2] = SHRT_MAX;
805                                         ++vertices;
806                                         ++vertex_index;
807
808                                         // edges
809                                         edges->v1 = vertex_index - 1;
810                                         edges->v2 = vertex_index - 3;
811                                         ++edges;
812                                         ++edge_index;
813
814                                         edges->v1 = vertex_index - 1;
815                                         edges->v2 = vertex_index - 2;
816                                         ++edges;
817                                         ++edge_index;
818
819                                         // poly
820                                         polys->loopstart = loop_index;
821                                         polys->totloop = 3;
822                                         polys->mat_nr = material_index;
823                                         ++polys;
824
825                                         // Even and odd loops connect triangles vertices differently
826                                         bool is_odd = n % 2;
827                                         // loops
828                                         if (is_odd) {
829                                                 loops[0].v = vertex_index - 1;
830                                                 loops[0].e = edge_index - 2;
831
832                                                 loops[1].v = vertex_index - 3;
833                                                 loops[1].e = edge_index - 3;
834
835                                                 loops[2].v = vertex_index - 2;
836                                                 loops[2].e = edge_index - 1;
837                                         }
838                                         else {
839                                                 loops[0].v = vertex_index - 1;
840                                                 loops[0].e = edge_index - 1;
841
842                                                 loops[1].v = vertex_index - 2;
843                                                 loops[1].e = edge_index - 3;
844
845                                                 loops[2].v = vertex_index - 3;
846                                                 loops[2].e = edge_index - 2;
847                                         }
848                                         loops += 3;
849                                         loop_index += 3;
850
851                                         // UV
852                                         if (hasTex) {
853                                                 // First UV layer (loopsuv[0]) has no tips (texCoord(0)).
854                                                 // Second UV layer (loopsuv[1]) has tips:  (texCoord(1)).
855                                                 for (int L = 0; L < 2; L++) {
856                                                         if (is_odd) {
857                                                                 loopsuv[L][0].uv[0] = svRep[2]->texCoord(L).x();
858                                                                 loopsuv[L][0].uv[1] = svRep[2]->texCoord(L).y();
859
860                                                                 loopsuv[L][1].uv[0] = svRep[0]->texCoord(L).x();
861                                                                 loopsuv[L][1].uv[1] = svRep[0]->texCoord(L).y();
862
863                                                                 loopsuv[L][2].uv[0] = svRep[1]->texCoord(L).x();
864                                                                 loopsuv[L][2].uv[1] = svRep[1]->texCoord(L).y();
865                                                         }
866                                                         else {
867                                                                 loopsuv[L][0].uv[0] = svRep[2]->texCoord(L).x();
868                                                                 loopsuv[L][0].uv[1] = svRep[2]->texCoord(L).y();
869
870                                                                 loopsuv[L][1].uv[0] = svRep[1]->texCoord(L).x();
871                                                                 loopsuv[L][1].uv[1] = svRep[1]->texCoord(L).y();
872
873                                                                 loopsuv[L][2].uv[0] = svRep[0]->texCoord(L).x();
874                                                                 loopsuv[L][2].uv[1] = svRep[0]->texCoord(L).y();
875                                                         }
876                                                         loopsuv[L] += 3;
877                                                 }
878                                         }
879
880                                         // colors and alpha transparency. vertex colors are in sRGB
881                                         // space by convention, so convert from linear
882                                         float rgba[3][4];
883
884                                         for (int i = 0; i < 3; i++) {
885                                                 copy_v3fl_v3db(rgba[i], &svRep[i]->color()[0]);
886                                                 rgba[i][3] = svRep[i]->alpha();
887                                         }
888
889                                         if (is_odd) {
890                                                 linearrgb_to_srgb_uchar4(&colors[0].r, rgba[2]);
891                                                 linearrgb_to_srgb_uchar4(&colors[1].r, rgba[0]);
892                                                 linearrgb_to_srgb_uchar4(&colors[2].r, rgba[1]);
893                                         }
894                                         else {
895                                                 linearrgb_to_srgb_uchar4(&colors[0].r, rgba[2]);
896                                                 linearrgb_to_srgb_uchar4(&colors[1].r, rgba[1]);
897                                                 linearrgb_to_srgb_uchar4(&colors[2].r, rgba[0]);
898                                         }
899                                         transp[0].r = transp[0].g = transp[0].b = colors[0].a;
900                                         transp[1].r = transp[1].g = transp[1].b = colors[1].a;
901                                         transp[2].r = transp[2].g = transp[2].b = colors[2].a;
902                                         colors += 3;
903                                         transp += 3;
904                                 }
905                         } // loop over strip vertices
906                 } // loop over strips
907                 material_index++;
908         } // loop over strokes
909
910         test_object_materials(object_mesh, (ID *)mesh);
911
912 #if 0 // XXX
913         BLI_assert(mesh->totvert == vertex_index);
914         BLI_assert(mesh->totedge == edge_index);
915         BLI_assert(mesh->totloop == loop_index);
916         BLI_assert(mesh->totcol == material_index);
917         BKE_mesh_validate(mesh, true, true);
918 #endif
919 }
920
921 // A replacement of BKE_object_add() for better performance.
922 Object *BlenderStrokeRenderer::NewMesh() const
923 {
924         Object *ob;
925         Base *base;
926         char name[MAX_ID_NAME];
927         unsigned int mesh_id = get_stroke_mesh_id();
928
929         BLI_snprintf(name, MAX_ID_NAME, "0%08xOB", mesh_id);
930         ob = BKE_object_add_only_object(freestyle_bmain, OB_MESH, name);
931         BLI_snprintf(name, MAX_ID_NAME, "0%08xME", mesh_id);
932         ob->data = BKE_mesh_add(freestyle_bmain, name);
933         ob->lay = 1;
934
935         base = BKE_scene_base_add(freestyle_scene, ob);
936         DAG_relations_tag_update(freestyle_bmain);
937 #if 0
938         BKE_scene_base_deselect_all(scene);
939         BKE_scene_base_select(scene, base);
940 #else
941         (void)base;
942 #endif
943
944         DAG_id_tag_update_ex(freestyle_bmain, &ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
945
946         return ob;
947 }
948
949 Render *BlenderStrokeRenderer::RenderScene(Render * /*re*/, bool render)
950 {
951         Camera *camera = (Camera *)freestyle_scene->camera->data;
952         if (camera->clipend < _z)
953                 camera->clipend = _z + _z_delta * 100.0f;
954 #if 0
955         if (G.debug & G_DEBUG_FREESTYLE) {
956                 cout << "clipsta " << camera->clipsta << ", clipend " << camera->clipend << endl;
957         }
958 #endif
959
960         Render *freestyle_render = RE_NewSceneRender(freestyle_scene);
961
962         RE_RenderFreestyleStrokes(freestyle_render, freestyle_bmain, freestyle_scene,
963                                   render && get_stroke_count() > 0);
964
965         return freestyle_render;
966 }
967
968 } /* namespace Freestyle */