Merge branch 'blender2.7'
[blender.git] / source / blender / editors / sculpt_paint / paint_image_proj.c
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  * along with this program; if not, write to the Free Software Foundation,
15  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16  *
17  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
18  * All rights reserved.
19  *
20  * The Original Code is: some of this file.
21  *
22  * Contributor(s): Jens Ole Wund (bjornmose), Campbell Barton (ideasman42)
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/editors/sculpt_paint/paint_image_proj.c
28  *  \ingroup edsculpt
29  *  \brief Functions to paint images in 2D and 3D.
30  */
31
32 #include <float.h>
33 #include <string.h>
34 #include <stdio.h>
35 #include <math.h>
36
37 #include "MEM_guardedalloc.h"
38
39 #ifdef WIN32
40 #  include "BLI_winstuff.h"
41 #endif
42
43 #include "BLI_blenlib.h"
44 #include "BLI_linklist.h"
45 #include "BLI_math.h"
46 #include "BLI_math_bits.h"
47 #include "BLI_math_color_blend.h"
48 #include "BLI_memarena.h"
49 #include "BLI_threads.h"
50 #include "BLI_utildefines.h"
51
52 #include "BLT_translation.h"
53
54
55 #include "IMB_imbuf.h"
56 #include "IMB_imbuf_types.h"
57
58 #include "DNA_brush_types.h"
59 #include "DNA_material_types.h"
60 #include "DNA_mesh_types.h"
61 #include "DNA_meshdata_types.h"
62 #include "DNA_node_types.h"
63 #include "DNA_object_types.h"
64
65 #include "BKE_brush.h"
66 #include "BKE_camera.h"
67 #include "BKE_colorband.h"
68 #include "BKE_context.h"
69 #include "BKE_colortools.h"
70 #include "BKE_idprop.h"
71 #include "BKE_image.h"
72 #include "BKE_library.h"
73 #include "BKE_main.h"
74 #include "BKE_material.h"
75 #include "BKE_mesh.h"
76 #include "BKE_mesh_mapping.h"
77 #include "BKE_mesh_runtime.h"
78 #include "BKE_node.h"
79 #include "BKE_paint.h"
80 #include "BKE_report.h"
81 #include "BKE_scene.h"
82 #include "BKE_screen.h"
83 #include "BKE_texture.h"
84
85 #include "DEG_depsgraph.h"
86 #include "DEG_depsgraph_query.h"
87
88 #include "UI_interface.h"
89
90 #include "ED_object.h"
91 #include "ED_mesh.h"
92 #include "ED_node.h"
93 #include "ED_paint.h"
94 #include "ED_screen.h"
95 #include "ED_uvedit.h"
96 #include "ED_view3d.h"
97
98 #include "GPU_extensions.h"
99
100 #include "WM_api.h"
101 #include "WM_types.h"
102
103 #include "RNA_access.h"
104 #include "RNA_define.h"
105 #include "RNA_enum_types.h"
106
107 #include "GPU_draw.h"
108
109 #include "IMB_colormanagement.h"
110
111 #include "bmesh.h"
112 //#include "bmesh_tools.h"
113
114 #include "paint_intern.h"
115
116 static void partial_redraw_array_init(ImagePaintPartialRedraw *pr);
117
118 /* Defines and Structs */
119 /* unit_float_to_uchar_clamp as inline function */
120 BLI_INLINE unsigned char f_to_char(const float val)
121 {
122         return unit_float_to_uchar_clamp(val);
123 }
124
125 /* ProjectionPaint defines */
126
127 /* approx the number of buckets to have under the brush,
128  * used with the brush size to set the ps->buckets_x and ps->buckets_y value.
129  *
130  * When 3 - a brush should have ~9 buckets under it at once
131  * ...this helps for threading while painting as well as
132  * avoiding initializing pixels that wont touch the brush */
133 #define PROJ_BUCKET_BRUSH_DIV 4
134
135 #define PROJ_BUCKET_RECT_MIN 4
136 #define PROJ_BUCKET_RECT_MAX 256
137
138 #define PROJ_BOUNDBOX_DIV 8
139 #define PROJ_BOUNDBOX_SQUARED  (PROJ_BOUNDBOX_DIV * PROJ_BOUNDBOX_DIV)
140
141 //#define PROJ_DEBUG_PAINT 1
142 //#define PROJ_DEBUG_NOSEAMBLEED 1
143 //#define PROJ_DEBUG_PRINT_CLIP 1
144 #define PROJ_DEBUG_WINCLIP 1
145
146
147 #ifndef PROJ_DEBUG_NOSEAMBLEED
148 /* projectFaceSeamFlags options */
149 //#define PROJ_FACE_IGNORE      (1<<0)  /* When the face is hidden, backfacing or occluded */
150 //#define PROJ_FACE_INIT        (1<<1)  /* When we have initialized the faces data */
151 #define PROJ_FACE_SEAM1 (1 << 0)  /* If this face has a seam on any of its edges */
152 #define PROJ_FACE_SEAM2 (1 << 1)
153 #define PROJ_FACE_SEAM3 (1 << 2)
154
155 #define PROJ_FACE_NOSEAM1   (1 << 4)
156 #define PROJ_FACE_NOSEAM2   (1 << 5)
157 #define PROJ_FACE_NOSEAM3   (1 << 6)
158
159 /* face winding */
160 #define PROJ_FACE_WINDING_INIT 1
161 #define PROJ_FACE_WINDING_CW 2
162
163 /* a slightly scaled down face is used to get fake 3D location for edge pixels in the seams
164  * as this number approaches  1.0f the likelihood increases of float precision errors where
165  * it is occluded by an adjacent face */
166 #define PROJ_FACE_SCALE_SEAM    0.99f
167 #endif  /* PROJ_DEBUG_NOSEAMBLEED */
168
169
170 #define PROJ_SRC_VIEW       1
171 #define PROJ_SRC_IMAGE_CAM  2
172 #define PROJ_SRC_IMAGE_VIEW 3
173 #define PROJ_SRC_VIEW_FILL  4
174
175 #define PROJ_VIEW_DATA_ID "view_data"
176 /* viewmat + winmat + clipsta + clipend + is_ortho */
177 #define PROJ_VIEW_DATA_SIZE (4 * 4 + 4 * 4 + 3)
178
179 #define PROJ_BUCKET_NULL        0
180 #define PROJ_BUCKET_INIT        (1 << 0)
181 // #define PROJ_BUCKET_CLONE_INIT       (1<<1)
182
183 /* used for testing doubles, if a point is on a line etc */
184 #define PROJ_GEOM_TOLERANCE 0.00075f
185 #define PROJ_PIXEL_TOLERANCE 0.01f
186
187 /* vert flags */
188 #define PROJ_VERT_CULL 1
189
190 /* to avoid locking in tile initialization */
191 #define TILE_PENDING POINTER_FROM_INT(-1)
192
193 /** This is mainly a convenience struct used so we can keep an array of images we use -
194  * their imbufs, etc, in 1 array, When using threads this array is copied for each thread
195  * because 'partRedrawRect' and 'touch' values would not be thread safe */
196 typedef struct ProjPaintImage {
197         Image *ima;
198         ImBuf *ibuf;
199         ImagePaintPartialRedraw *partRedrawRect;
200         /** Only used to build undo tiles during painting. */
201         volatile void **undoRect;
202         /** The mask accumulation must happen on canvas, not on space screen bucket.
203          * Here we store the mask rectangle. */
204         unsigned short **maskRect;
205         /** Store flag to enforce validation of undo rectangle. */
206         bool **valid;
207         bool touch;
208 } ProjPaintImage;
209
210 /**
211  * Handle for stroke (operator customdata)
212  */
213 typedef struct ProjStrokeHandle {
214         /* Support for painting from multiple views at once,
215          * currently used to implement symmetry painting,
216          * we can assume at least the first is set while painting. */
217         struct ProjPaintState *ps_views[8];
218         int ps_views_tot;
219         int symmetry_flags;
220
221         int orig_brush_size;
222
223         bool need_redraw;
224
225         /* trick to bypass regular paint and allow clone picking */
226         bool is_clone_cursor_pick;
227
228         /* In ProjPaintState, only here for convenience */
229         Scene *scene;
230         Brush *brush;
231 } ProjStrokeHandle;
232
233 /* Main projection painting struct passed to all projection painting functions */
234 typedef struct ProjPaintState {
235         View3D *v3d;
236         RegionView3D *rv3d;
237         ARegion *ar;
238         Depsgraph *depsgraph;
239         Scene *scene;
240         /* PROJ_SRC_**** */
241         int source;
242
243         /* the paint color. It can change depending of inverted mode or not */
244         float paint_color[3];
245         float paint_color_linear[3];
246         float dither;
247
248         Brush *brush;
249         short tool, blend, mode;
250
251         float brush_size;
252         Object *ob;
253         /* for symmetry, we need to store modified object matrix */
254         float obmat[4][4];
255         float obmat_imat[4][4];
256         /* end similarities with ImagePaintState */
257
258         Image *stencil_ima;
259         Image *canvas_ima;
260         Image *clone_ima;
261         float stencil_value;
262
263         /* projection painting only */
264         /** for multithreading, the first item is sometimes used for non threaded cases too. */
265         MemArena *arena_mt[BLENDER_MAX_THREADS];
266         /** screen sized 2D array, each pixel has a linked list of ProjPixel's */
267         LinkNode **bucketRect;
268         /** bucketRect aligned array linkList of faces overlapping each bucket. */
269         LinkNode **bucketFaces;
270         /** store if the bucks have been initialized. */
271         unsigned char *bucketFlags;
272
273         /** store options per vert, now only store if the vert is pointing away from the view. */
274         char *vertFlags;
275         /** The size of the bucket grid, the grid span's screenMin/screenMax
276          * so you can paint outsize the screen or with 2 brushes at once. */
277         int buckets_x;
278         int buckets_y;
279
280         /** result of project_paint_pixel_sizeof(), constant per stroke. */
281         int pixel_sizeof;
282
283         /** size of projectImages array. */
284         int image_tot;
285
286         /** verts projected into floating point screen space. */
287         float (*screenCoords)[4];
288         /** 2D bounds for mesh verts on the screen's plane (screenspace). */
289         float screenMin[2];
290         float screenMax[2];
291         /** Calculated from screenMin & screenMax. */
292         float screen_width;
293         float screen_height;
294         /** from the carea or from the projection render. */
295         int winx, winy;
296
297         /* options for projection painting */
298         bool  do_layer_clone;
299         bool  do_layer_stencil;
300         bool  do_layer_stencil_inv;
301         bool  do_stencil_brush;
302         bool  do_material_slots;
303
304         /** Use raytraced occlusion? - ortherwise will paint right through to the back. */
305         bool  do_occlude;
306         /** ignore faces with normals pointing away,
307          * skips a lot of raycasts if your normals are correctly flipped. */
308         bool  do_backfacecull;
309         /** mask out pixels based on their normals. */
310         bool  do_mask_normal;
311         /** mask out pixels based on cavity. */
312         bool  do_mask_cavity;
313         /** what angle to mask at. */
314         float normal_angle;
315         /** cos(normal_angle), faster to compare. */
316         float normal_angle__cos;
317         float normal_angle_inner;
318         float normal_angle_inner__cos;
319         /** difference between normal_angle and normal_angle_inner, for easy access. */
320         float normal_angle_range;
321
322         /** quick access to (me->editflag & ME_EDIT_PAINT_FACE_SEL) */
323         bool do_face_sel;
324         bool is_ortho;
325         /** the object is negative scaled. */
326         bool is_flip_object;
327         /** use masking during painting. Some operations such as airbrush may disable. */
328         bool do_masking;
329         /** only to avoid running. */
330         bool is_texbrush;
331         /** mask brush is applied before masking. */
332         bool is_maskbrush;
333 #ifndef PROJ_DEBUG_NOSEAMBLEED
334         float seam_bleed_px;
335 #endif
336         /* clone vars */
337         float cloneOffset[2];
338
339         /** Projection matrix, use for getting screen coords. */
340         float projectMat[4][4];
341         /** inverse of projectMat. */
342         float projectMatInv[4][4];
343         /** View vector, use for do_backfacecull and for ray casting with an ortho viewport. */
344         float viewDir[3];
345         /** View location in object relative 3D space, so can compare to verts. */
346         float viewPos[3];
347         float clipsta, clipend;
348
349         /* reproject vars */
350         Image *reproject_image;
351         ImBuf *reproject_ibuf;
352         bool   reproject_ibuf_free_float;
353         bool   reproject_ibuf_free_uchar;
354
355         /* threads */
356         int thread_tot;
357         int bucketMin[2];
358         int bucketMax[2];
359         /** must lock threads while accessing these. */
360         int context_bucket_x, context_bucket_y;
361
362         struct CurveMapping *cavity_curve;
363         BlurKernel *blurkernel;
364
365
366
367         /* -------------------------------------------------------------------- */
368         /* Vars shared between multiple views (keep last) */
369         /**
370          * This data is owned by ``ProjStrokeHandle.ps_views[0]``,
371          * all other views re-use the data.
372          */
373
374 #define PROJ_PAINT_STATE_SHARED_MEMCPY(ps_dst, ps_src) \
375         MEMCPY_STRUCT_OFS(ps_dst, ps_src, is_shared_user)
376
377 #define PROJ_PAINT_STATE_SHARED_CLEAR(ps) \
378         MEMSET_STRUCT_OFS(ps, 0, is_shared_user)
379
380         bool is_shared_user;
381
382         ProjPaintImage *projImages;
383         /** cavity amount for vertices. */
384         float *cavities;
385
386 #ifndef PROJ_DEBUG_NOSEAMBLEED
387         /** store info about faces, if they are initialized etc*/
388         char *faceSeamFlags;
389         /** save the winding of the face in uv space,
390          * helps as an extra validation step for seam detection. */
391         char *faceWindingFlags;
392         /** expanded UVs for faces to use as seams. */
393         float (*faceSeamUVs)[3][2];
394         /** Only needed for when seam_bleed_px is enabled, use to find UV seams. */
395         LinkNode **vertFaces;
396 #endif
397
398         SpinLock *tile_lock;
399
400         Mesh *me_eval;
401         bool  me_eval_free;
402         int  totlooptri_eval;
403         int  totpoly_eval;
404         int  totedge_eval;
405         int  totvert_eval;
406
407         const MVert    *mvert_eval;
408         const MEdge    *medge_eval;
409         const MPoly    *mpoly_eval;
410         const MLoop    *mloop_eval;
411         const MLoopTri *mlooptri_eval;
412
413         const MLoopUV  *mloopuv_stencil_eval;
414
415         /**
416          * \note These UV layers are aligned to \a mpoly_eval
417          * but each pointer references the start of the layer,
418          * so a loop indirection is needed as well.
419          */
420         const MLoopUV **poly_to_loop_uv;
421         /** other UV map, use for cloning between layers. */
422         const MLoopUV **poly_to_loop_uv_clone;
423
424         /* Actual material for each index, either from object or Mesh datablock... */
425         Material **mat_array;
426
427         bool use_colormanagement;
428 } ProjPaintState;
429
430 typedef union pixelPointer {
431         /** float buffer. */
432         float *f_pt;
433         /** 2 ways to access a char buffer. */
434         unsigned int *uint_pt;
435         unsigned char *ch_pt;
436 } PixelPointer;
437
438 typedef union pixelStore {
439         unsigned char ch[4];
440         unsigned int uint;
441         float f[4];
442 } PixelStore;
443
444 typedef struct ProjPixel {
445         /** the floating point screen projection of this pixel. */
446         float projCoSS[2];
447         float worldCoSS[3];
448
449         short x_px, y_px;
450
451         /** if anyone wants to paint onto more than 65535 images they can bite me. */
452         unsigned short image_index;
453         unsigned char bb_cell_index;
454
455         /* for various reasons we may want to mask out painting onto this pixel */
456         unsigned short mask;
457
458         /* Only used when the airbrush is disabled.
459          * Store the max mask value to avoid painting over an area with a lower opacity
460          * with an advantage that we can avoid touching the pixel at all, if the
461          * new mask value is lower then mask_accum */
462         unsigned short *mask_accum;
463
464         /* horrible hack, store tile valid flag pointer here to re-validate tiles
465          * used for anchored and drag-dot strokes */
466         bool *valid;
467
468         PixelPointer origColor;
469         PixelStore newColor;
470         PixelPointer pixel;
471 } ProjPixel;
472
473 typedef struct ProjPixelClone {
474         struct ProjPixel __pp;
475         PixelStore clonepx;
476 } ProjPixelClone;
477
478 /* undo tile pushing */
479 typedef struct {
480         SpinLock *lock;
481         bool masked;
482         unsigned short tile_width;
483         ImBuf **tmpibuf;
484         ProjPaintImage *pjima;
485 } TileInfo;
486
487
488
489 /* -------------------------------------------------------------------- */
490
491 /** \name MLoopTri accessor functions.
492  * \{ */
493
494 BLI_INLINE const MPoly *ps_tri_index_to_mpoly(const ProjPaintState *ps, int tri_index)
495 {
496         return &ps->mpoly_eval[ps->mlooptri_eval[tri_index].poly];
497 }
498
499 #define PS_LOOPTRI_AS_VERT_INDEX_3(ps, lt) \
500         ps->mloop_eval[lt->tri[0]].v, \
501         ps->mloop_eval[lt->tri[1]].v, \
502         ps->mloop_eval[lt->tri[2]].v,
503
504 #define PS_LOOPTRI_AS_UV_3(uvlayer, lt) \
505         uvlayer[lt->poly][lt->tri[0]].uv, \
506         uvlayer[lt->poly][lt->tri[1]].uv, \
507         uvlayer[lt->poly][lt->tri[2]].uv,
508
509 #define PS_LOOPTRI_ASSIGN_UV_3(uv_tri, uvlayer, lt)  { \
510         (uv_tri)[0] = uvlayer[lt->poly][lt->tri[0]].uv; \
511         (uv_tri)[1] = uvlayer[lt->poly][lt->tri[1]].uv; \
512         (uv_tri)[2] = uvlayer[lt->poly][lt->tri[2]].uv; \
513 } ((void)0)
514
515 /** \} */
516
517
518
519 /* Finish projection painting structs */
520
521 static TexPaintSlot *project_paint_face_paint_slot(const ProjPaintState *ps, int tri_index)
522 {
523         const MPoly *mp = ps_tri_index_to_mpoly(ps, tri_index);
524         Material *ma = ps->mat_array[mp->mat_nr];
525         return ma ? ma->texpaintslot + ma->paint_active_slot : NULL;
526 }
527
528 static Image *project_paint_face_paint_image(const ProjPaintState *ps, int tri_index)
529 {
530         if (ps->do_stencil_brush) {
531                 return ps->stencil_ima;
532         }
533         else {
534                 const MPoly *mp = ps_tri_index_to_mpoly(ps, tri_index);
535                 Material *ma = ps->mat_array[mp->mat_nr];
536                 TexPaintSlot *slot = ma ? ma->texpaintslot + ma->paint_active_slot : NULL;
537                 return slot ? slot->ima : ps->canvas_ima;
538         }
539 }
540
541 static TexPaintSlot *project_paint_face_clone_slot(const ProjPaintState *ps, int tri_index)
542 {
543         const MPoly *mp = ps_tri_index_to_mpoly(ps, tri_index);
544         Material *ma = ps->mat_array[mp->mat_nr];
545         return ma ? ma->texpaintslot + ma->paint_clone_slot : NULL;
546 }
547
548 static Image *project_paint_face_clone_image(const ProjPaintState *ps, int tri_index)
549 {
550         const MPoly *mp = ps_tri_index_to_mpoly(ps, tri_index);
551         Material *ma = ps->mat_array[mp->mat_nr];
552         TexPaintSlot *slot = ma ? ma->texpaintslot + ma->paint_clone_slot : NULL;
553         return slot ? slot->ima : ps->clone_ima;
554 }
555
556 /* fast projection bucket array lookup, use the safe version for bound checking  */
557 static int project_bucket_offset(const ProjPaintState *ps, const float projCoSS[2])
558 {
559         /* If we were not dealing with screenspace 2D coords we could simple do...
560          * ps->bucketRect[x + (y*ps->buckets_y)] */
561
562         /* please explain?
563          * projCoSS[0] - ps->screenMin[0]   : zero origin
564          * ... / ps->screen_width           : range from 0.0 to 1.0
565          * ... * ps->buckets_x              : use as a bucket index
566          *
567          * Second multiplication does similar but for vertical offset
568          */
569         return ( (int)(((projCoSS[0] - ps->screenMin[0]) / ps->screen_width)  * ps->buckets_x)) +
570                (((int)(((projCoSS[1] - ps->screenMin[1]) / ps->screen_height) * ps->buckets_y)) * ps->buckets_x);
571 }
572
573 static int project_bucket_offset_safe(const ProjPaintState *ps, const float projCoSS[2])
574 {
575         int bucket_index = project_bucket_offset(ps, projCoSS);
576
577         if (bucket_index < 0 || bucket_index >= ps->buckets_x * ps->buckets_y) {
578                 return -1;
579         }
580         else {
581                 return bucket_index;
582         }
583 }
584
585 static float VecZDepthOrtho(
586         const float pt[2],
587         const float v1[3], const float v2[3], const float v3[3],
588         float w[3])
589 {
590         barycentric_weights_v2(v1, v2, v3, pt, w);
591         return (v1[2] * w[0]) + (v2[2] * w[1]) + (v3[2] * w[2]);
592 }
593
594 static float VecZDepthPersp(
595         const float pt[2],
596         const float v1[4], const float v2[4], const float v3[4],
597         float w[3])
598 {
599         float wtot_inv, wtot;
600         float w_tmp[3];
601
602         barycentric_weights_v2_persp(v1, v2, v3, pt, w);
603         /* for the depth we need the weights to match what
604          * barycentric_weights_v2 would return, in this case its easiest just to
605          * undo the 4th axis division and make it unit-sum
606          *
607          * don't call barycentric_weights_v2() because our callers expect 'w'
608          * to be weighted from the perspective */
609         w_tmp[0] = w[0] * v1[3];
610         w_tmp[1] = w[1] * v2[3];
611         w_tmp[2] = w[2] * v3[3];
612
613         wtot = w_tmp[0] + w_tmp[1] + w_tmp[2];
614
615         if (wtot != 0.0f) {
616                 wtot_inv = 1.0f / wtot;
617
618                 w_tmp[0] = w_tmp[0] * wtot_inv;
619                 w_tmp[1] = w_tmp[1] * wtot_inv;
620                 w_tmp[2] = w_tmp[2] * wtot_inv;
621         }
622         else /* dummy values for zero area face */
623                 w_tmp[0] = w_tmp[1] = w_tmp[2] = 1.0f / 3.0f;
624         /* done mimicking barycentric_weights_v2() */
625
626         return (v1[2] * w_tmp[0]) + (v2[2] * w_tmp[1]) + (v3[2] * w_tmp[2]);
627 }
628
629
630 /* Return the top-most face index that the screen space coord 'pt' touches (or -1) */
631 static int project_paint_PickFace(
632         const ProjPaintState *ps, const float pt[2],
633         float w[3])
634 {
635         LinkNode *node;
636         float w_tmp[3];
637         int bucket_index;
638         int best_tri_index = -1;
639         float z_depth_best = FLT_MAX, z_depth;
640
641         bucket_index = project_bucket_offset_safe(ps, pt);
642         if (bucket_index == -1)
643                 return -1;
644
645
646
647         /* we could return 0 for 1 face buckets, as long as this function assumes
648          * that the point its testing is only every originated from an existing face */
649
650         for (node = ps->bucketFaces[bucket_index]; node; node = node->next) {
651                 const int tri_index = POINTER_AS_INT(node->link);
652                 const MLoopTri *lt = &ps->mlooptri_eval[tri_index];
653                 const float *vtri_ss[3] = {
654                     ps->screenCoords[ps->mloop_eval[lt->tri[0]].v],
655                     ps->screenCoords[ps->mloop_eval[lt->tri[1]].v],
656                     ps->screenCoords[ps->mloop_eval[lt->tri[2]].v],
657                 };
658
659
660                 if (isect_point_tri_v2(pt, UNPACK3(vtri_ss))) {
661                         if (ps->is_ortho) {
662                                 z_depth = VecZDepthOrtho(pt, UNPACK3(vtri_ss), w_tmp);
663                         }
664                         else {
665                                 z_depth = VecZDepthPersp(pt, UNPACK3(vtri_ss), w_tmp);
666                         }
667
668                         if (z_depth < z_depth_best) {
669                                 best_tri_index = tri_index;
670                                 z_depth_best = z_depth;
671                                 copy_v3_v3(w, w_tmp);
672                         }
673                 }
674         }
675
676         /** will be -1 or a valid face. */
677         return best_tri_index;
678 }
679
680 /* Converts a uv coord into a pixel location wrapping if the uv is outside 0-1 range */
681 static void uvco_to_wrapped_pxco(const float uv[2], int ibuf_x, int ibuf_y, float *x, float *y)
682 {
683         /* use */
684         *x = fmodf(uv[0], 1.0f);
685         *y = fmodf(uv[1], 1.0f);
686
687         if (*x < 0.0f) *x += 1.0f;
688         if (*y < 0.0f) *y += 1.0f;
689
690         *x = *x * ibuf_x - 0.5f;
691         *y = *y * ibuf_y - 0.5f;
692 }
693
694 /* Set the top-most face color that the screen space coord 'pt' touches
695  * (or return 0 if none touch) */
696 static bool project_paint_PickColor(
697         const ProjPaintState *ps, const float pt[2],
698         float *rgba_fp, unsigned char *rgba, const bool interp)
699 {
700         const MLoopTri *lt;
701         const float *lt_tri_uv[3];
702         float w[3], uv[2];
703         int tri_index;
704         Image *ima;
705         ImBuf *ibuf;
706         int xi, yi;
707
708         tri_index = project_paint_PickFace(ps, pt, w);
709
710         if (tri_index == -1)
711                 return 0;
712
713         lt = &ps->mlooptri_eval[tri_index];
714         PS_LOOPTRI_ASSIGN_UV_3(lt_tri_uv, ps->poly_to_loop_uv, lt);
715
716         interp_v2_v2v2v2(uv, UNPACK3(lt_tri_uv), w);
717
718         ima = project_paint_face_paint_image(ps, tri_index);
719         /** we must have got the imbuf before getting here. */
720         ibuf = BKE_image_get_first_ibuf(ima);
721         if (!ibuf) return 0;
722
723         if (interp) {
724                 float x, y;
725                 uvco_to_wrapped_pxco(uv, ibuf->x, ibuf->y, &x, &y);
726
727                 if (ibuf->rect_float) {
728                         if (rgba_fp) {
729                                 bilinear_interpolation_color_wrap(ibuf, NULL, rgba_fp, x, y);
730                         }
731                         else {
732                                 float rgba_tmp_f[4];
733                                 bilinear_interpolation_color_wrap(ibuf, NULL, rgba_tmp_f, x, y);
734                                 premul_float_to_straight_uchar(rgba, rgba_tmp_f);
735                         }
736                 }
737                 else {
738                         if (rgba) {
739                                 bilinear_interpolation_color_wrap(ibuf, rgba, NULL, x, y);
740                         }
741                         else {
742                                 unsigned char rgba_tmp[4];
743                                 bilinear_interpolation_color_wrap(ibuf, rgba_tmp, NULL, x, y);
744                                 straight_uchar_to_premul_float(rgba_fp, rgba_tmp);
745                         }
746                 }
747         }
748         else {
749                 //xi = (int)((uv[0]*ibuf->x) + 0.5f);
750                 //yi = (int)((uv[1]*ibuf->y) + 0.5f);
751                 //if (xi < 0 || xi >= ibuf->x  ||  yi < 0 || yi >= ibuf->y) return 0;
752
753                 /* wrap */
754                 xi = mod_i((int)(uv[0] * ibuf->x), ibuf->x);
755                 yi = mod_i((int)(uv[1] * ibuf->y), ibuf->y);
756
757                 if (rgba) {
758                         if (ibuf->rect_float) {
759                                 const float *rgba_tmp_fp = ibuf->rect_float + (xi + yi * ibuf->x * 4);
760                                 premul_float_to_straight_uchar(rgba, rgba_tmp_fp);
761                         }
762                         else {
763                                 *((unsigned int *)rgba) = *(unsigned int *)(((char *)ibuf->rect) + ((xi + yi * ibuf->x) * 4));
764                         }
765                 }
766
767                 if (rgba_fp) {
768                         if (ibuf->rect_float) {
769                                 copy_v4_v4(rgba_fp, (ibuf->rect_float + ((xi + yi * ibuf->x) * 4)));
770                         }
771                         else {
772                                 unsigned char *tmp_ch = ((unsigned char *)ibuf->rect) + ((xi + yi * ibuf->x) * 4);
773                                 straight_uchar_to_premul_float(rgba_fp, tmp_ch);
774                         }
775                 }
776         }
777         BKE_image_release_ibuf(ima, ibuf, NULL);
778         return 1;
779 }
780
781 /**
782  * Check if 'pt' is infront of the 3 verts on the Z axis (used for screenspace occlusion test)
783  * \return
784  * -  `0`:   no occlusion
785  * - `-1`: no occlusion but 2D intersection is true
786  * -  `1`: occluded
787  * -  `2`: occluded with `w[3]` weights set (need to know in some cases)
788  */
789 static int project_paint_occlude_ptv(
790         const float pt[3],
791         const float v1[4], const float v2[4], const float v3[4],
792         float w[3], const bool is_ortho)
793 {
794         /* if all are behind us, return false */
795         if (v1[2] > pt[2] && v2[2] > pt[2] && v3[2] > pt[2])
796                 return 0;
797
798         /* do a 2D point in try intersection */
799         if (!isect_point_tri_v2(pt, v1, v2, v3))
800                 return 0;
801
802
803         /* From here on we know there IS an intersection */
804         /* if ALL of the verts are infront of us then we know it intersects ? */
805         if (v1[2] < pt[2] && v2[2] < pt[2] && v3[2] < pt[2]) {
806                 return 1;
807         }
808         else {
809                 /* we intersect? - find the exact depth at the point of intersection */
810                 /* Is this point is occluded by another face? */
811                 if (is_ortho) {
812                         if (VecZDepthOrtho(pt, v1, v2, v3, w) < pt[2]) return 2;
813                 }
814                 else {
815                         if (VecZDepthPersp(pt, v1, v2, v3, w) < pt[2]) return 2;
816                 }
817         }
818         return -1;
819 }
820
821
822 static int project_paint_occlude_ptv_clip(
823         const float pt[3],
824         const float v1[4], const float v2[4], const float v3[4],
825         const float v1_3d[3], const float v2_3d[3], const float v3_3d[3],
826         float w[3], const bool is_ortho, RegionView3D *rv3d)
827 {
828         float wco[3];
829         int ret = project_paint_occlude_ptv(pt, v1, v2, v3, w, is_ortho);
830
831         if (ret <= 0)
832                 return ret;
833
834         if (ret == 1) { /* weights not calculated */
835                 if (is_ortho) {
836                         barycentric_weights_v2(v1, v2, v3, pt, w);
837                 }
838                 else {
839                         barycentric_weights_v2_persp(v1, v2, v3, pt, w);
840                 }
841         }
842
843         /* Test if we're in the clipped area, */
844         interp_v3_v3v3v3(wco, v1_3d, v2_3d, v3_3d, w);
845
846         if (!ED_view3d_clipping_test(rv3d, wco, true)) {
847                 return 1;
848         }
849
850         return -1;
851 }
852
853
854 /* Check if a screenspace location is occluded by any other faces
855  * check, pixelScreenCo must be in screenspace, its Z-Depth only needs to be used for comparison
856  * and doesn't need to be correct in relation to X and Y coords
857  * (this is the case in perspective view) */
858 static bool project_bucket_point_occluded(
859         const ProjPaintState *ps, LinkNode *bucketFace,
860         const int orig_face, const float pixelScreenCo[4])
861 {
862         int isect_ret;
863         const bool do_clip = ps->rv3d ? (ps->rv3d->rflag & RV3D_CLIPPING) != 0 : 0;
864
865         /* we could return 0 for 1 face buckets, as long as this function assumes
866          * that the point its testing is only every originated from an existing face */
867
868         for (; bucketFace; bucketFace = bucketFace->next) {
869                 const int tri_index = POINTER_AS_INT(bucketFace->link);
870
871                 if (orig_face != tri_index) {
872                         const MLoopTri *lt = &ps->mlooptri_eval[tri_index];
873                         const float *vtri_ss[3] = {
874                             ps->screenCoords[ps->mloop_eval[lt->tri[0]].v],
875                             ps->screenCoords[ps->mloop_eval[lt->tri[1]].v],
876                             ps->screenCoords[ps->mloop_eval[lt->tri[2]].v],
877                         };
878                         float w[3];
879
880                         if (do_clip) {
881                                 const float *vtri_co[3] = {
882                                     ps->mvert_eval[ps->mloop_eval[lt->tri[0]].v].co,
883                                     ps->mvert_eval[ps->mloop_eval[lt->tri[1]].v].co,
884                                     ps->mvert_eval[ps->mloop_eval[lt->tri[2]].v].co,
885                                 };
886                                 isect_ret = project_paint_occlude_ptv_clip(
887                                         pixelScreenCo, UNPACK3(vtri_ss), UNPACK3(vtri_co),
888                                         w, ps->is_ortho, ps->rv3d);
889                         }
890                         else {
891                                 isect_ret = project_paint_occlude_ptv(
892                                         pixelScreenCo, UNPACK3(vtri_ss),
893                                         w, ps->is_ortho);
894                         }
895
896                         if (isect_ret >= 1) {
897                                 /* TODO - we may want to cache the first hit,
898                                  * it is not possible to swap the face order in the list anymore */
899                                 return true;
900                         }
901                 }
902         }
903         return false;
904 }
905
906 /* basic line intersection, could move to math_geom.c, 2 points with a horiz line
907  * 1 for an intersection, 2 if the first point is aligned, 3 if the second point is aligned */
908 #define ISECT_TRUE 1
909 #define ISECT_TRUE_P1 2
910 #define ISECT_TRUE_P2 3
911 static int line_isect_y(const float p1[2], const float p2[2], const float y_level, float *x_isect)
912 {
913         float y_diff;
914
915         /* are we touching the first point? - no interpolation needed */
916         if (y_level == p1[1]) {
917                 *x_isect = p1[0];
918                 return ISECT_TRUE_P1;
919         }
920         /* are we touching the second point? - no interpolation needed */
921         if (y_level == p2[1]) {
922                 *x_isect = p2[0];
923                 return ISECT_TRUE_P2;
924         }
925
926         /** yuck, horizontal line, we cant do much here. */
927         y_diff = fabsf(p1[1] - p2[1]);
928
929         if (y_diff < 0.000001f) {
930                 *x_isect = (p1[0] + p2[0]) * 0.5f;
931                 return ISECT_TRUE;
932         }
933
934         if (p1[1] > y_level && p2[1] < y_level) {
935                 /* (p1[1] - p2[1]); */
936                 *x_isect = (p2[0] * (p1[1] - y_level) + p1[0] * (y_level - p2[1])) / y_diff;
937                 return ISECT_TRUE;
938         }
939         else if (p1[1] < y_level && p2[1] > y_level) {
940                 /* (p2[1] - p1[1]); */
941                 *x_isect = (p2[0] * (y_level - p1[1]) + p1[0] * (p2[1] - y_level)) / y_diff;
942                 return ISECT_TRUE;
943         }
944         else {
945                 return 0;
946         }
947 }
948
949 static int line_isect_x(const float p1[2], const float p2[2], const float x_level, float *y_isect)
950 {
951         float x_diff;
952
953         if (x_level == p1[0]) { /* are we touching the first point? - no interpolation needed */
954                 *y_isect = p1[1];
955                 return ISECT_TRUE_P1;
956         }
957         if (x_level == p2[0]) { /* are we touching the second point? - no interpolation needed */
958                 *y_isect = p2[1];
959                 return ISECT_TRUE_P2;
960         }
961
962         /* yuck, horizontal line, we cant do much here */
963         x_diff = fabsf(p1[0] - p2[0]);
964
965         /* yuck, vertical line, we cant do much here */
966         if (x_diff < 0.000001f) {
967                 *y_isect = (p1[0] + p2[0]) * 0.5f;
968                 return ISECT_TRUE;
969         }
970
971         if (p1[0] > x_level && p2[0] < x_level) {
972                 /* (p1[0] - p2[0]); */
973                 *y_isect = (p2[1] * (p1[0] - x_level) + p1[1] * (x_level - p2[0])) / x_diff;
974                 return ISECT_TRUE;
975         }
976         else if (p1[0] < x_level && p2[0] > x_level) {
977                 /* (p2[0] - p1[0]); */
978                 *y_isect = (p2[1] * (x_level - p1[0]) + p1[1] * (p2[0] - x_level)) / x_diff;
979                 return ISECT_TRUE;
980         }
981         else {
982                 return 0;
983         }
984 }
985
986 /* simple func use for comparing UV locations to check if there are seams.
987  * Its possible this gives incorrect results, when the UVs for 1 face go into the next
988  * tile, but do not do this for the adjacent face, it could return a false positive.
989  * This is so unlikely that Id not worry about it. */
990 #ifndef PROJ_DEBUG_NOSEAMBLEED
991 static bool cmp_uv(const float vec2a[2], const float vec2b[2])
992 {
993         /* if the UV's are not between 0.0 and 1.0 */
994         float xa = fmodf(vec2a[0], 1.0f);
995         float ya = fmodf(vec2a[1], 1.0f);
996
997         float xb = fmodf(vec2b[0], 1.0f);
998         float yb = fmodf(vec2b[1], 1.0f);
999
1000         if (xa < 0.0f) xa += 1.0f;
1001         if (ya < 0.0f) ya += 1.0f;
1002
1003         if (xb < 0.0f) xb += 1.0f;
1004         if (yb < 0.0f) yb += 1.0f;
1005
1006         return ((fabsf(xa - xb) < PROJ_GEOM_TOLERANCE) && (fabsf(ya - yb) < PROJ_GEOM_TOLERANCE)) ? 1 : 0;
1007 }
1008 #endif
1009
1010 /* set min_px and max_px to the image space bounds of the UV coords
1011  * return zero if there is no area in the returned rectangle */
1012 #ifndef PROJ_DEBUG_NOSEAMBLEED
1013 static bool pixel_bounds_uv(
1014         const float uv_quad[4][2],
1015         rcti *bounds_px,
1016         const int ibuf_x, const int ibuf_y
1017         )
1018 {
1019         /* UV bounds */
1020         float min_uv[2], max_uv[2];
1021
1022         INIT_MINMAX2(min_uv, max_uv);
1023
1024         minmax_v2v2_v2(min_uv, max_uv, uv_quad[0]);
1025         minmax_v2v2_v2(min_uv, max_uv, uv_quad[1]);
1026         minmax_v2v2_v2(min_uv, max_uv, uv_quad[2]);
1027         minmax_v2v2_v2(min_uv, max_uv, uv_quad[3]);
1028
1029         bounds_px->xmin = (int)(ibuf_x * min_uv[0]);
1030         bounds_px->ymin = (int)(ibuf_y * min_uv[1]);
1031
1032         bounds_px->xmax = (int)(ibuf_x * max_uv[0]) + 1;
1033         bounds_px->ymax = (int)(ibuf_y * max_uv[1]) + 1;
1034
1035         /*printf("%d %d %d %d\n", min_px[0], min_px[1], max_px[0], max_px[1]);*/
1036
1037         /* face uses no UV area when quantized to pixels? */
1038         return (bounds_px->xmin == bounds_px->xmax || bounds_px->ymin == bounds_px->ymax) ? 0 : 1;
1039 }
1040 #endif
1041
1042 static bool pixel_bounds_array(float (*uv)[2], rcti *bounds_px, const int ibuf_x, const int ibuf_y, int tot)
1043 {
1044         /* UV bounds */
1045         float min_uv[2], max_uv[2];
1046
1047         if (tot == 0) {
1048                 return 0;
1049         }
1050
1051         INIT_MINMAX2(min_uv, max_uv);
1052
1053         while (tot--) {
1054                 minmax_v2v2_v2(min_uv, max_uv, (*uv));
1055                 uv++;
1056         }
1057
1058         bounds_px->xmin = (int)(ibuf_x * min_uv[0]);
1059         bounds_px->ymin = (int)(ibuf_y * min_uv[1]);
1060
1061         bounds_px->xmax = (int)(ibuf_x * max_uv[0]) + 1;
1062         bounds_px->ymax = (int)(ibuf_y * max_uv[1]) + 1;
1063
1064         /*printf("%d %d %d %d\n", min_px[0], min_px[1], max_px[0], max_px[1]);*/
1065
1066         /* face uses no UV area when quantized to pixels? */
1067         return (bounds_px->xmin == bounds_px->xmax || bounds_px->ymin == bounds_px->ymax) ? 0 : 1;
1068 }
1069
1070 #ifndef PROJ_DEBUG_NOSEAMBLEED
1071
1072 static void project_face_winding_init(const ProjPaintState *ps, const int tri_index)
1073 {
1074         /* detect the winding of faces in uv space */
1075         const MLoopTri *lt = &ps->mlooptri_eval[tri_index];
1076         const float *lt_tri_uv[3] = { PS_LOOPTRI_AS_UV_3(ps->poly_to_loop_uv, lt) };
1077         float winding = cross_tri_v2(lt_tri_uv[0], lt_tri_uv[1], lt_tri_uv[2]);
1078
1079         if (winding > 0)
1080                 ps->faceWindingFlags[tri_index] |= PROJ_FACE_WINDING_CW;
1081
1082         ps->faceWindingFlags[tri_index] |= PROJ_FACE_WINDING_INIT;
1083 }
1084
1085 /* This function returns 1 if this face has a seam along the 2 face-vert indices
1086  * 'orig_i1_fidx' and 'orig_i2_fidx' */
1087 static bool check_seam(
1088         const ProjPaintState *ps,
1089         const int orig_face, const int orig_i1_fidx, const int orig_i2_fidx,
1090         int *other_face, int *orig_fidx)
1091 {
1092         const MLoopTri *orig_lt = &ps->mlooptri_eval[orig_face];
1093         const float *orig_lt_tri_uv[3] = { PS_LOOPTRI_AS_UV_3(ps->poly_to_loop_uv, orig_lt) };
1094         /* vert indices from face vert order indices */
1095         const unsigned int i1 = ps->mloop_eval[orig_lt->tri[orig_i1_fidx]].v;
1096         const unsigned int i2 = ps->mloop_eval[orig_lt->tri[orig_i2_fidx]].v;
1097         LinkNode *node;
1098         /* index in face */
1099         int i1_fidx = -1, i2_fidx = -1;
1100
1101         for (node = ps->vertFaces[i1]; node; node = node->next) {
1102                 const int tri_index = POINTER_AS_INT(node->link);
1103
1104                 if (tri_index != orig_face) {
1105                         const MLoopTri *lt = &ps->mlooptri_eval[tri_index];
1106                         const int lt_vtri[3] = { PS_LOOPTRI_AS_VERT_INDEX_3(ps, lt) };
1107                         /* could check if the 2 faces images match here,
1108                          * but then there wouldn't be a way to return the opposite face's info */
1109
1110
1111                         /* We need to know the order of the verts in the adjacent face
1112                          * set the i1_fidx and i2_fidx to (0,1,2,3) */
1113                         i1_fidx = BKE_MESH_TESSTRI_VINDEX_ORDER(lt_vtri, i1);
1114                         i2_fidx = BKE_MESH_TESSTRI_VINDEX_ORDER(lt_vtri, i2);
1115
1116                         /* Only need to check if 'i2_fidx' is valid because we know i1_fidx is the same vert on both faces */
1117                         if (i2_fidx != -1) {
1118                                 const float *lt_tri_uv[3] = { PS_LOOPTRI_AS_UV_3(ps->poly_to_loop_uv, lt) };
1119                                 Image *tpage = project_paint_face_paint_image(ps, tri_index);
1120                                 Image *orig_tpage = project_paint_face_paint_image(ps, orig_face);
1121
1122                                 BLI_assert(i1_fidx != -1);
1123
1124                                 /* This IS an adjacent face!, now lets check if the UVs are ok */
1125
1126                                 /* set up the other face */
1127                                 *other_face = tri_index;
1128
1129                                 /* we check if difference is 1 here, else we might have a case of edge 2-0 for a tri */
1130                                 *orig_fidx = (i1_fidx < i2_fidx && (i2_fidx - i1_fidx == 1)) ? i1_fidx : i2_fidx;
1131
1132                                 /* initialize face winding if needed */
1133                                 if ((ps->faceWindingFlags[tri_index] & PROJ_FACE_WINDING_INIT) == 0)
1134                                         project_face_winding_init(ps, tri_index);
1135
1136                                 /* first test if they have the same image */
1137                                 if ((orig_tpage == tpage) &&
1138                                     cmp_uv(orig_lt_tri_uv[orig_i1_fidx], lt_tri_uv[i1_fidx]) &&
1139                                     cmp_uv(orig_lt_tri_uv[orig_i2_fidx], lt_tri_uv[i2_fidx]))
1140                                 {
1141                                         /* if faces don't have the same winding in uv space,
1142                                          * they are on the same side so edge is boundary */
1143                                         if ((ps->faceWindingFlags[tri_index] & PROJ_FACE_WINDING_CW) !=
1144                                             (ps->faceWindingFlags[orig_face] & PROJ_FACE_WINDING_CW))
1145                                         {
1146                                                 return 1;
1147                                         }
1148
1149                                         // printf("SEAM (NONE)\n");
1150                                         return 0;
1151
1152                                 }
1153                                 else {
1154                                         // printf("SEAM (UV GAP)\n");
1155                                         return 1;
1156                                 }
1157                         }
1158                 }
1159         }
1160         // printf("SEAM (NO FACE)\n");
1161         *other_face = -1;
1162         return 1;
1163 }
1164
1165 #define SMALL_NUMBER  1.e-6f
1166 BLI_INLINE float shell_v2v2_normal_dir_to_dist(float n[2], float d[2])
1167 {
1168         const float angle_cos = (normalize_v2(n) < SMALL_NUMBER) ? fabsf(dot_v2v2(d, n)) : 0.0f;
1169         return (UNLIKELY(angle_cos < SMALL_NUMBER)) ? 1.0f : (1.0f / angle_cos);
1170 }
1171 #undef SMALL_NUMBER
1172
1173 /* Calculate outset UV's, this is not the same as simply scaling the UVs,
1174  * since the outset coords are a margin that keep an even distance from the original UV's,
1175  * note that the image aspect is taken into account */
1176 static void uv_image_outset(
1177         float (*orig_uv)[2], float (*outset_uv)[2], const float scaler,
1178         const int ibuf_x, const int ibuf_y, const bool cw)
1179 {
1180         /* disallow shell-thickness to outset extreme values,
1181          * otherwise near zero area UV's may extend thousands of pixels. */
1182         const float scale_clamp = 5.0f;
1183
1184         float a1, a2, a3;
1185         /* pixelspace uv's */
1186         float puv[3][2];
1187         /* normals */
1188         float no1[2], no2[2], no3[2];
1189         float dir1[2], dir2[2], dir3[2];
1190         float ibuf_inv[2];
1191
1192         ibuf_inv[0] = 1.0f / (float)ibuf_x;
1193         ibuf_inv[1] = 1.0f / (float)ibuf_y;
1194
1195         /* make UV's in pixel space so we can */
1196         puv[0][0] = orig_uv[0][0] * ibuf_x;
1197         puv[0][1] = orig_uv[0][1] * ibuf_y;
1198
1199         puv[1][0] = orig_uv[1][0] * ibuf_x;
1200         puv[1][1] = orig_uv[1][1] * ibuf_y;
1201
1202         puv[2][0] = orig_uv[2][0] * ibuf_x;
1203         puv[2][1] = orig_uv[2][1] * ibuf_y;
1204
1205         /* face edge directions */
1206         sub_v2_v2v2(dir1, puv[1], puv[0]);
1207         sub_v2_v2v2(dir2, puv[2], puv[1]);
1208         sub_v2_v2v2(dir3, puv[0], puv[2]);
1209         normalize_v2(dir1);
1210         normalize_v2(dir2);
1211         normalize_v2(dir3);
1212
1213         /* here we just use the orthonormality property (a1, a2) dot (a2, -a1) = 0
1214          * to get normals from the edge directions based on the winding */
1215         if (cw) {
1216                 no1[0] = -dir3[1] - dir1[1];
1217                 no1[1] =  dir3[0] + dir1[0];
1218                 no2[0] = -dir1[1] - dir2[1];
1219                 no2[1] =  dir1[0] + dir2[0];
1220                 no3[0] = -dir2[1] - dir3[1];
1221                 no3[1] =  dir2[0] + dir3[0];
1222         }
1223         else {
1224                 no1[0] =  dir3[1] + dir1[1];
1225                 no1[1] = -dir3[0] - dir1[0];
1226                 no2[0] =  dir1[1] + dir2[1];
1227                 no2[1] = -dir1[0] - dir2[0];
1228                 no3[0] =  dir2[1] + dir3[1];
1229                 no3[1] = -dir2[0] - dir3[0];
1230         }
1231
1232         a1 = shell_v2v2_normal_dir_to_dist(no1, dir3);
1233         a2 = shell_v2v2_normal_dir_to_dist(no2, dir1);
1234         a3 = shell_v2v2_normal_dir_to_dist(no3, dir2);
1235
1236         CLAMP_MAX(a1, scale_clamp);
1237         CLAMP_MAX(a2, scale_clamp);
1238         CLAMP_MAX(a3, scale_clamp);
1239
1240         mul_v2_fl(no1, a1 * scaler);
1241         mul_v2_fl(no2, a2 * scaler);
1242         mul_v2_fl(no3, a3 * scaler);
1243         add_v2_v2v2(outset_uv[0], puv[0], no1);
1244         add_v2_v2v2(outset_uv[1], puv[1], no2);
1245         add_v2_v2v2(outset_uv[2], puv[2], no3);
1246
1247         mul_v2_v2(outset_uv[0], ibuf_inv);
1248         mul_v2_v2(outset_uv[1], ibuf_inv);
1249         mul_v2_v2(outset_uv[2], ibuf_inv);
1250 }
1251
1252 /*
1253  * Be tricky with flags, first 4 bits are PROJ_FACE_SEAM1 to 4, last 4 bits are PROJ_FACE_NOSEAM1 to 4
1254  * 1<<i - where i is (0-3)
1255  *
1256  * If we're multithreadng, make sure threads are locked when this is called
1257  */
1258 static void project_face_seams_init(const ProjPaintState *ps, const int tri_index)
1259 {
1260         /* vars for the other face, we also set its flag */
1261         int other_face, other_fidx;
1262         int fidx1 = 2;
1263         /* next fidx in the face (0,1,2,3) -> (1,2,3,0) or (0,1,2) -> (1,2,0) for a tri */
1264         int fidx2 = 0;
1265
1266         /* initialize face winding if needed */
1267         if ((ps->faceWindingFlags[tri_index] & PROJ_FACE_WINDING_INIT) == 0)
1268                 project_face_winding_init(ps, tri_index);
1269
1270         do {
1271                 if ((ps->faceSeamFlags[tri_index] & (1 << fidx1 | 16 << fidx1)) == 0) {
1272                         if (check_seam(ps, tri_index, fidx1, fidx2, &other_face, &other_fidx)) {
1273                                 ps->faceSeamFlags[tri_index] |= 1 << fidx1;
1274                                 if (other_face != -1)
1275                                         ps->faceSeamFlags[other_face] |= 1 << other_fidx;
1276                         }
1277                         else {
1278                                 ps->faceSeamFlags[tri_index] |= 16 << fidx1;
1279                                 if (other_face != -1) {
1280                                         /* second 4 bits for disabled */
1281                                         ps->faceSeamFlags[other_face] |= 16 << other_fidx;
1282                                 }
1283                         }
1284                 }
1285
1286                 fidx2 = fidx1;
1287         } while (fidx1--);
1288 }
1289 #endif // PROJ_DEBUG_NOSEAMBLEED
1290
1291
1292 /* Converts a UV location to a 3D screenspace location
1293  * Takes a 'uv' and 3 UV coords, and sets the values of pixelScreenCo
1294  *
1295  * This is used for finding a pixels location in screenspace for painting */
1296 static void screen_px_from_ortho(
1297         const float uv[2],
1298         const float v1co[3], const float v2co[3], const float v3co[3],  /* Screenspace coords */
1299         const float uv1co[2], const float uv2co[2], const float uv3co[2],
1300         float pixelScreenCo[4],
1301         float w[3])
1302 {
1303         barycentric_weights_v2(uv1co, uv2co, uv3co, uv, w);
1304         interp_v3_v3v3v3(pixelScreenCo, v1co, v2co, v3co, w);
1305 }
1306
1307 /* same as screen_px_from_ortho except we
1308  * do perspective correction on the pixel coordinate */
1309 static void screen_px_from_persp(
1310         const float uv[2],
1311         const float v1co[4], const float v2co[4], const float v3co[4],  /* screenspace coords */
1312         const float uv1co[2], const float uv2co[2], const float uv3co[2],
1313         float pixelScreenCo[4],
1314         float w[3])
1315 {
1316         float w_int[3];
1317         float wtot_inv, wtot;
1318         barycentric_weights_v2(uv1co, uv2co, uv3co, uv, w);
1319
1320         /* re-weight from the 4th coord of each screen vert */
1321         w_int[0] = w[0] * v1co[3];
1322         w_int[1] = w[1] * v2co[3];
1323         w_int[2] = w[2] * v3co[3];
1324
1325         wtot = w_int[0] + w_int[1] + w_int[2];
1326
1327         if (wtot > 0.0f) {
1328                 wtot_inv = 1.0f / wtot;
1329                 w_int[0] *= wtot_inv;
1330                 w_int[1] *= wtot_inv;
1331                 w_int[2] *= wtot_inv;
1332         }
1333         else {
1334                 w[0] = w[1] = w[2] =
1335                 /* dummy values for zero area face */
1336                 w_int[0] = w_int[1] = w_int[2] = 1.0f / 3.0f;
1337         }
1338         /* done re-weighting */
1339
1340         /* do interpolation based on projected weight */
1341         interp_v3_v3v3v3(pixelScreenCo, v1co, v2co, v3co, w_int);
1342 }
1343
1344
1345 /**
1346  * Set a direction vector based on a screen location.
1347  * (use for perspective view, else we can simply use `ps->viewDir`)
1348  *
1349  * Similar functionality to #ED_view3d_win_to_vector
1350  *
1351  * \param r_dir: Resulting direction (length is undefined).
1352  */
1353 static void screen_px_to_vector_persp(
1354         int winx, int winy, const float projmat_inv[4][4], const float view_pos[3],
1355         const float co_px[2],
1356         float r_dir[3])
1357 {
1358         r_dir[0] = 2.0f * (co_px[0] / winx) - 1.0f;
1359         r_dir[1] = 2.0f * (co_px[1] / winy) - 1.0f;
1360         r_dir[2] = -0.5f;
1361         mul_project_m4_v3((float(*)[4])projmat_inv, r_dir);
1362         sub_v3_v3(r_dir, view_pos);
1363 }
1364
1365 /**
1366  * Special function to return the factor to a point along a line in pixel space.
1367  *
1368  * This is needed since we can't use #line_point_factor_v2 for perspective screen-space coords.
1369  *
1370  * \param p: 2D screen-space location.
1371  * \param v1, v2: 3D object-space locations.
1372  */
1373 static float screen_px_line_point_factor_v2_persp(
1374         const ProjPaintState *ps,
1375         const float p[2],
1376         const float v1[3], const float v2[3])
1377 {
1378         const float zero[3] = {0};
1379         float v1_proj[3], v2_proj[3];
1380         float dir[3];
1381
1382         screen_px_to_vector_persp(ps->winx, ps->winy, ps->projectMatInv, ps->viewPos, p, dir);
1383
1384         sub_v3_v3v3(v1_proj, v1, ps->viewPos);
1385         sub_v3_v3v3(v2_proj, v2, ps->viewPos);
1386
1387         project_plane_v3_v3v3(v1_proj, v1_proj, dir);
1388         project_plane_v3_v3v3(v2_proj, v2_proj, dir);
1389
1390         return line_point_factor_v2(zero, v1_proj, v2_proj);
1391 }
1392
1393
1394 static void project_face_pixel(
1395         const float *lt_tri_uv[3], ImBuf *ibuf_other, const float w[3],
1396         unsigned char rgba_ub[4], float rgba_f[4])
1397 {
1398         float uv_other[2], x, y;
1399
1400         interp_v2_v2v2v2(uv_other, UNPACK3(lt_tri_uv), w);
1401
1402         /* use */
1403         uvco_to_wrapped_pxco(uv_other, ibuf_other->x, ibuf_other->y, &x, &y);
1404
1405         if (ibuf_other->rect_float) { /* from float to float */
1406                 bilinear_interpolation_color_wrap(ibuf_other, NULL, rgba_f, x, y);
1407         }
1408         else { /* from char to float */
1409                 bilinear_interpolation_color_wrap(ibuf_other, rgba_ub, NULL, x, y);
1410         }
1411
1412 }
1413
1414 /* run this outside project_paint_uvpixel_init since pixels with mask 0 don't need init */
1415 static float project_paint_uvpixel_mask(
1416         const ProjPaintState *ps,
1417         const int tri_index,
1418         const float w[3])
1419 {
1420         float mask;
1421
1422         /* Image Mask */
1423         if (ps->do_layer_stencil) {
1424                 /* another UV maps image is masking this one's */
1425                 ImBuf *ibuf_other;
1426                 Image *other_tpage = ps->stencil_ima;
1427
1428                 if (other_tpage && (ibuf_other = BKE_image_acquire_ibuf(other_tpage, NULL, NULL))) {
1429                         const MLoopTri *lt_other = &ps->mlooptri_eval[tri_index];
1430                         const float *lt_other_tri_uv[3] = { PS_LOOPTRI_AS_UV_3(ps->poly_to_loop_uv, lt_other) };
1431
1432                         /* BKE_image_acquire_ibuf - TODO - this may be slow */
1433                         unsigned char rgba_ub[4];
1434                         float rgba_f[4];
1435
1436                         project_face_pixel(lt_other_tri_uv, ibuf_other, w, rgba_ub, rgba_f);
1437
1438                         if (ibuf_other->rect_float) { /* from float to float */
1439                                 mask = ((rgba_f[0] + rgba_f[1] + rgba_f[2]) * (1.0f / 3.0f)) * rgba_f[3];
1440                         }
1441                         else { /* from char to float */
1442                                 mask = ((rgba_ub[0] + rgba_ub[1] + rgba_ub[2]) * (1.0f / (255.0f * 3.0f))) * (rgba_ub[3] * (1.0f / 255.0f));
1443                         }
1444
1445                         BKE_image_release_ibuf(other_tpage, ibuf_other, NULL);
1446
1447                         if (!ps->do_layer_stencil_inv) {
1448                                 /* matching the gimps layer mask black/white rules, white==full opacity */
1449                                 mask = (1.0f - mask);
1450                         }
1451
1452                         if (mask == 0.0f) {
1453                                 return 0.0f;
1454                         }
1455                 }
1456                 else {
1457                         return 0.0f;
1458                 }
1459         }
1460         else {
1461                 mask = 1.0f;
1462         }
1463
1464         if (ps->do_mask_cavity) {
1465                 const MLoopTri *lt = &ps->mlooptri_eval[tri_index];
1466                 const int lt_vtri[3] = { PS_LOOPTRI_AS_VERT_INDEX_3(ps, lt) };
1467                 float ca1, ca2, ca3, ca_mask;
1468                 ca1 = ps->cavities[lt_vtri[0]];
1469                 ca2 = ps->cavities[lt_vtri[1]];
1470                 ca3 = ps->cavities[lt_vtri[2]];
1471
1472                 ca_mask = w[0] * ca1 + w[1] * ca2 + w[2] * ca3;
1473                 ca_mask = curvemapping_evaluateF(ps->cavity_curve, 0, ca_mask);
1474                 CLAMP(ca_mask, 0.0f, 1.0f);
1475                 mask *= ca_mask;
1476         }
1477
1478         /* calculate mask */
1479         if (ps->do_mask_normal) {
1480                 const MLoopTri *lt = &ps->mlooptri_eval[tri_index];
1481                 const int lt_vtri[3] = { PS_LOOPTRI_AS_VERT_INDEX_3(ps, lt) };
1482                 const MPoly *mp = &ps->mpoly_eval[lt->poly];
1483                 float no[3], angle_cos;
1484
1485                 if (mp->flag & ME_SMOOTH) {
1486                         const short *no1, *no2, *no3;
1487                         no1 = ps->mvert_eval[lt_vtri[0]].no;
1488                         no2 = ps->mvert_eval[lt_vtri[1]].no;
1489                         no3 = ps->mvert_eval[lt_vtri[2]].no;
1490
1491                         no[0] = w[0] * no1[0] + w[1] * no2[0] + w[2] * no3[0];
1492                         no[1] = w[0] * no1[1] + w[1] * no2[1] + w[2] * no3[1];
1493                         no[2] = w[0] * no1[2] + w[1] * no2[2] + w[2] * no3[2];
1494                         normalize_v3(no);
1495                 }
1496                 else {
1497                         /* incase the */
1498 #if 1
1499                         /* normalizing per pixel isn't optimal, we could cache or check ps->*/
1500                         normal_tri_v3(no,
1501                                       ps->mvert_eval[lt_vtri[0]].co,
1502                                       ps->mvert_eval[lt_vtri[1]].co,
1503                                       ps->mvert_eval[lt_vtri[2]].co);
1504 #else
1505                         /* don't use because some modifiers dont have normal data (subsurf for eg) */
1506                         copy_v3_v3(no, (float *)ps->dm->getTessFaceData(ps->dm, tri_index, CD_NORMAL));
1507 #endif
1508                 }
1509
1510                 if (UNLIKELY(ps->is_flip_object)) {
1511                         negate_v3(no);
1512                 }
1513
1514                 /* now we can use the normal as a mask */
1515                 if (ps->is_ortho) {
1516                         angle_cos = dot_v3v3(ps->viewDir, no);
1517                 }
1518                 else {
1519                         /* Annoying but for the perspective view we need to get the pixels location in 3D space :/ */
1520                         float viewDirPersp[3];
1521                         const float *co1, *co2, *co3;
1522                         co1 = ps->mvert_eval[lt_vtri[0]].co;
1523                         co2 = ps->mvert_eval[lt_vtri[1]].co;
1524                         co3 = ps->mvert_eval[lt_vtri[2]].co;
1525
1526                         /* Get the direction from the viewPoint to the pixel and normalize */
1527                         viewDirPersp[0] = (ps->viewPos[0] - (w[0] * co1[0] + w[1] * co2[0] + w[2] * co3[0]));
1528                         viewDirPersp[1] = (ps->viewPos[1] - (w[0] * co1[1] + w[1] * co2[1] + w[2] * co3[1]));
1529                         viewDirPersp[2] = (ps->viewPos[2] - (w[0] * co1[2] + w[1] * co2[2] + w[2] * co3[2]));
1530                         normalize_v3(viewDirPersp);
1531                         if (UNLIKELY(ps->is_flip_object)) {
1532                                 negate_v3(viewDirPersp);
1533                         }
1534
1535                         angle_cos = dot_v3v3(viewDirPersp, no);
1536                 }
1537
1538                 /* If backface culling is disabled, allow painting on back faces. */
1539                 if (!ps->do_backfacecull) {
1540                         angle_cos = fabsf(angle_cos);
1541                 }
1542
1543                 if (angle_cos <= ps->normal_angle__cos) {
1544                         /* outsize the normal limit*/
1545                         return 0.0f;
1546                 }
1547                 else if (angle_cos < ps->normal_angle_inner__cos) {
1548                         mask *= (ps->normal_angle - acosf(angle_cos)) / ps->normal_angle_range;
1549                 } /* otherwise no mask normal is needed, were within the limit */
1550         }
1551
1552         /* This only works when the opacity dosnt change while painting, stylus pressure messes with this
1553          * so don't use it. */
1554         // if (ps->is_airbrush == 0) mask *= BKE_brush_alpha_get(ps->brush);
1555
1556         return mask;
1557 }
1558
1559 static int project_paint_pixel_sizeof(const short tool)
1560 {
1561         if ((tool == PAINT_TOOL_CLONE) || (tool == PAINT_TOOL_SMEAR)) {
1562                 return sizeof(ProjPixelClone);
1563         }
1564         else {
1565                 return sizeof(ProjPixel);
1566         }
1567 }
1568
1569 static int project_paint_undo_subtiles(const TileInfo *tinf, int tx, int ty)
1570 {
1571         ProjPaintImage *pjIma = tinf->pjima;
1572         int tile_index = tx + ty * tinf->tile_width;
1573         bool generate_tile = false;
1574
1575         /* double check lock to avoid locking */
1576         if (UNLIKELY(!pjIma->undoRect[tile_index])) {
1577                 if (tinf->lock)
1578                         BLI_spin_lock(tinf->lock);
1579                 if (LIKELY(!pjIma->undoRect[tile_index])) {
1580                         pjIma->undoRect[tile_index] = TILE_PENDING;
1581                         generate_tile = true;
1582                 }
1583                 if (tinf->lock)
1584                         BLI_spin_unlock(tinf->lock);
1585         }
1586
1587
1588         if (generate_tile) {
1589                 ListBase *undo_tiles = ED_image_undo_get_tiles();
1590                 volatile void *undorect;
1591                 if (tinf->masked) {
1592                         undorect = image_undo_push_tile(
1593                                 undo_tiles, pjIma->ima, pjIma->ibuf, tinf->tmpibuf,
1594                                 tx, ty, &pjIma->maskRect[tile_index], &pjIma->valid[tile_index], true, false);
1595                 }
1596                 else {
1597                         undorect = image_undo_push_tile(
1598                                 undo_tiles, pjIma->ima, pjIma->ibuf, tinf->tmpibuf,
1599                                 tx, ty, NULL, &pjIma->valid[tile_index], true, false);
1600                 }
1601
1602                 pjIma->ibuf->userflags |= IB_BITMAPDIRTY;
1603                 /* tile ready, publish */
1604                 if (tinf->lock)
1605                         BLI_spin_lock(tinf->lock);
1606                 pjIma->undoRect[tile_index] = undorect;
1607                 if (tinf->lock)
1608                         BLI_spin_unlock(tinf->lock);
1609
1610         }
1611
1612         return tile_index;
1613 }
1614
1615 /* run this function when we know a bucket's, face's pixel can be initialized,
1616  * return the ProjPixel which is added to 'ps->bucketRect[bucket_index]' */
1617 static ProjPixel *project_paint_uvpixel_init(
1618         const ProjPaintState *ps,
1619         MemArena *arena,
1620         const TileInfo *tinf,
1621         int x_px, int y_px,
1622         const float mask,
1623         const int tri_index,
1624         const float pixelScreenCo[4],
1625         const float world_spaceCo[3],
1626         const float w[3])
1627 {
1628         ProjPixel *projPixel;
1629         int x_tile, y_tile;
1630         int x_round, y_round;
1631         int tile_offset;
1632         /* volatile is important here to ensure pending check is not optimized away by compiler*/
1633         volatile int tile_index;
1634
1635         ProjPaintImage *projima = tinf->pjima;
1636         ImBuf *ibuf = projima->ibuf;
1637         /* wrap pixel location */
1638
1639         x_px = mod_i(x_px, ibuf->x);
1640         y_px = mod_i(y_px, ibuf->y);
1641
1642         BLI_assert(ps->pixel_sizeof == project_paint_pixel_sizeof(ps->tool));
1643         projPixel = BLI_memarena_alloc(arena, ps->pixel_sizeof);
1644
1645         /* calculate the undo tile offset of the pixel, used to store the original
1646          * pixel color and accumulated mask if any */
1647         x_tile =  x_px >> IMAPAINT_TILE_BITS;
1648         y_tile =  y_px >> IMAPAINT_TILE_BITS;
1649
1650         x_round = x_tile * IMAPAINT_TILE_SIZE;
1651         y_round = y_tile * IMAPAINT_TILE_SIZE;
1652         //memset(projPixel, 0, size);
1653
1654         tile_offset = (x_px - x_round) + (y_px - y_round) * IMAPAINT_TILE_SIZE;
1655         tile_index = project_paint_undo_subtiles(tinf, x_tile, y_tile);
1656
1657         /* other thread may be initializing the tile so wait here */
1658         while (projima->undoRect[tile_index] == TILE_PENDING)
1659                 ;
1660
1661         BLI_assert(tile_index < (IMAPAINT_TILE_NUMBER(ibuf->x) * IMAPAINT_TILE_NUMBER(ibuf->y)));
1662         BLI_assert(tile_offset < (IMAPAINT_TILE_SIZE * IMAPAINT_TILE_SIZE));
1663
1664         projPixel->valid = projima->valid[tile_index];
1665
1666         if (ibuf->rect_float) {
1667                 projPixel->pixel.f_pt = ibuf->rect_float + ((x_px + y_px * ibuf->x) * 4);
1668                 projPixel->origColor.f_pt = (float *)projima->undoRect[tile_index] + 4 * tile_offset;
1669                 zero_v4(projPixel->newColor.f);
1670         }
1671         else {
1672                 projPixel->pixel.ch_pt = (unsigned char *)(ibuf->rect + (x_px + y_px * ibuf->x));
1673                 projPixel->origColor.uint_pt = (unsigned int *)projima->undoRect[tile_index] + tile_offset;
1674                 projPixel->newColor.uint = 0;
1675         }
1676
1677         /* screenspace unclamped, we could keep its z and w values but don't need them at the moment */
1678         if (ps->brush->mtex.brush_map_mode == MTEX_MAP_MODE_3D) {
1679                 copy_v3_v3(projPixel->worldCoSS, world_spaceCo);
1680         }
1681
1682         copy_v2_v2(projPixel->projCoSS, pixelScreenCo);
1683
1684         projPixel->x_px = x_px;
1685         projPixel->y_px = y_px;
1686
1687         projPixel->mask = (unsigned short)(mask * 65535);
1688         if (ps->do_masking)
1689                 projPixel->mask_accum = projima->maskRect[tile_index] + tile_offset;
1690         else
1691                 projPixel->mask_accum = NULL;
1692
1693         /* which bounding box cell are we in?, needed for undo */
1694         projPixel->bb_cell_index = ((int)(((float)x_px / (float)ibuf->x) * PROJ_BOUNDBOX_DIV)) +
1695                                    ((int)(((float)y_px / (float)ibuf->y) * PROJ_BOUNDBOX_DIV)) * PROJ_BOUNDBOX_DIV;
1696
1697         /* done with view3d_project_float inline */
1698         if (ps->tool == PAINT_TOOL_CLONE) {
1699                 if (ps->poly_to_loop_uv_clone) {
1700                         ImBuf *ibuf_other;
1701                         Image *other_tpage = project_paint_face_clone_image(ps, tri_index);
1702
1703                         if (other_tpage && (ibuf_other = BKE_image_acquire_ibuf(other_tpage, NULL, NULL))) {
1704                                 const MLoopTri *lt_other = &ps->mlooptri_eval[tri_index];
1705                                 const float *lt_other_tri_uv[3] = { PS_LOOPTRI_AS_UV_3(ps->poly_to_loop_uv_clone, lt_other) };
1706
1707                                 /* BKE_image_acquire_ibuf - TODO - this may be slow */
1708
1709                                 if (ibuf->rect_float) {
1710                                         if (ibuf_other->rect_float) { /* from float to float */
1711                                                 project_face_pixel(lt_other_tri_uv, ibuf_other, w, NULL, ((ProjPixelClone *)projPixel)->clonepx.f);
1712                                         }
1713                                         else { /* from char to float */
1714                                                 unsigned char rgba_ub[4];
1715                                                 float rgba[4];
1716                                                 project_face_pixel(lt_other_tri_uv, ibuf_other, w, rgba_ub, NULL);
1717                                                 if (ps->use_colormanagement) {
1718                                                         srgb_to_linearrgb_uchar4(rgba, rgba_ub);
1719                                                 }
1720                                                 else {
1721                                                         rgba_uchar_to_float(rgba, rgba_ub);
1722                                                 }
1723                                                 straight_to_premul_v4_v4(((ProjPixelClone *)projPixel)->clonepx.f, rgba);
1724                                         }
1725                                 }
1726                                 else {
1727                                         if (ibuf_other->rect_float) { /* float to char */
1728                                                 float rgba[4];
1729                                                 project_face_pixel(lt_other_tri_uv, ibuf_other, w, NULL, rgba);
1730                                                 premul_to_straight_v4(rgba);
1731                                                 if (ps->use_colormanagement) {
1732                                                         linearrgb_to_srgb_uchar3(((ProjPixelClone *)projPixel)->clonepx.ch, rgba);
1733                                                 }
1734                                                 else {
1735                                                         rgb_float_to_uchar(((ProjPixelClone *)projPixel)->clonepx.ch, rgba);
1736                                                 }
1737                                                 ((ProjPixelClone *)projPixel)->clonepx.ch[3] =  rgba[3] * 255;
1738                                         }
1739                                         else { /* char to char */
1740                                                 project_face_pixel(lt_other_tri_uv, ibuf_other, w, ((ProjPixelClone *)projPixel)->clonepx.ch, NULL);
1741                                         }
1742                                 }
1743
1744                                 BKE_image_release_ibuf(other_tpage, ibuf_other, NULL);
1745                         }
1746                         else {
1747                                 if (ibuf->rect_float) {
1748                                         ((ProjPixelClone *)projPixel)->clonepx.f[3] = 0;
1749                                 }
1750                                 else {
1751                                         ((ProjPixelClone *)projPixel)->clonepx.ch[3] = 0;
1752                                 }
1753                         }
1754
1755                 }
1756                 else {
1757                         float co[2];
1758                         sub_v2_v2v2(co, projPixel->projCoSS, ps->cloneOffset);
1759
1760                         /* no need to initialize the bucket, we're only checking buckets faces and for this
1761                          * the faces are already initialized in project_paint_delayed_face_init(...) */
1762                         if (ibuf->rect_float) {
1763                                 if (!project_paint_PickColor(ps, co, ((ProjPixelClone *)projPixel)->clonepx.f, NULL, 1)) {
1764                                         /* zero alpha - ignore */
1765                                         ((ProjPixelClone *)projPixel)->clonepx.f[3] = 0;
1766                                 }
1767                         }
1768                         else {
1769                                 if (!project_paint_PickColor(ps, co, NULL, ((ProjPixelClone *)projPixel)->clonepx.ch, 1)) {
1770                                         /* zero alpha - ignore */
1771                                         ((ProjPixelClone *)projPixel)->clonepx.ch[3] = 0;
1772                                 }
1773                         }
1774                 }
1775         }
1776
1777 #ifdef PROJ_DEBUG_PAINT
1778         if (ibuf->rect_float) projPixel->pixel.f_pt[0] = 0;
1779         else                  projPixel->pixel.ch_pt[0] = 0;
1780 #endif
1781         /* pointer arithmetic */
1782         projPixel->image_index = projima - ps->projImages;
1783
1784         return projPixel;
1785 }
1786
1787 static bool line_clip_rect2f(
1788         const rctf *cliprect,
1789         const rctf *rect,
1790         const float l1[2], const float l2[2],
1791         float l1_clip[2], float l2_clip[2])
1792 {
1793         /* first account for horizontal, then vertical lines */
1794         /* horiz */
1795         if (fabsf(l1[1] - l2[1]) < PROJ_PIXEL_TOLERANCE) {
1796                 /* is the line out of range on its Y axis? */
1797                 if (l1[1] < rect->ymin || l1[1] > rect->ymax) {
1798                         return 0;
1799                 }
1800                 /* line is out of range on its X axis */
1801                 if ((l1[0] < rect->xmin && l2[0] < rect->xmin) || (l1[0] > rect->xmax && l2[0] > rect->xmax)) {
1802                         return 0;
1803                 }
1804
1805
1806                 /* this is a single point  (or close to)*/
1807                 if (fabsf(l1[0] - l2[0]) < PROJ_PIXEL_TOLERANCE) {
1808                         if (BLI_rctf_isect_pt_v(rect, l1)) {
1809                                 copy_v2_v2(l1_clip, l1);
1810                                 copy_v2_v2(l2_clip, l2);
1811                                 return 1;
1812                         }
1813                         else {
1814                                 return 0;
1815                         }
1816                 }
1817
1818                 copy_v2_v2(l1_clip, l1);
1819                 copy_v2_v2(l2_clip, l2);
1820                 CLAMP(l1_clip[0], rect->xmin, rect->xmax);
1821                 CLAMP(l2_clip[0], rect->xmin, rect->xmax);
1822                 return 1;
1823         }
1824         else if (fabsf(l1[0] - l2[0]) < PROJ_PIXEL_TOLERANCE) {
1825                 /* is the line out of range on its X axis? */
1826                 if (l1[0] < rect->xmin || l1[0] > rect->xmax) {
1827                         return 0;
1828                 }
1829
1830                 /* line is out of range on its Y axis */
1831                 if ((l1[1] < rect->ymin && l2[1] < rect->ymin) || (l1[1] > rect->ymax && l2[1] > rect->ymax)) {
1832                         return 0;
1833                 }
1834
1835                 /* this is a single point  (or close to)*/
1836                 if (fabsf(l1[1] - l2[1]) < PROJ_PIXEL_TOLERANCE) {
1837                         if (BLI_rctf_isect_pt_v(rect, l1)) {
1838                                 copy_v2_v2(l1_clip, l1);
1839                                 copy_v2_v2(l2_clip, l2);
1840                                 return 1;
1841                         }
1842                         else {
1843                                 return 0;
1844                         }
1845                 }
1846
1847                 copy_v2_v2(l1_clip, l1);
1848                 copy_v2_v2(l2_clip, l2);
1849                 CLAMP(l1_clip[1], rect->ymin, rect->ymax);
1850                 CLAMP(l2_clip[1], rect->ymin, rect->ymax);
1851                 return 1;
1852         }
1853         else {
1854                 float isect;
1855                 short ok1 = 0;
1856                 short ok2 = 0;
1857
1858                 /* Done with vertical lines */
1859
1860                 /* are either of the points inside the rectangle ? */
1861                 if (BLI_rctf_isect_pt_v(rect, l1)) {
1862                         copy_v2_v2(l1_clip, l1);
1863                         ok1 = 1;
1864                 }
1865
1866                 if (BLI_rctf_isect_pt_v(rect, l2)) {
1867                         copy_v2_v2(l2_clip, l2);
1868                         ok2 = 1;
1869                 }
1870
1871                 /* line inside rect */
1872                 if (ok1 && ok2) return 1;
1873
1874                 /* top/bottom */
1875                 if (line_isect_y(l1, l2, rect->ymin, &isect) && (isect >= cliprect->xmin) && (isect <= cliprect->xmax)) {
1876                         if (l1[1] < l2[1]) { /* line 1 is outside */
1877                                 l1_clip[0] = isect;
1878                                 l1_clip[1] = rect->ymin;
1879                                 ok1 = 1;
1880                         }
1881                         else {
1882                                 l2_clip[0] = isect;
1883                                 l2_clip[1] = rect->ymin;
1884                                 ok2 = 2;
1885                         }
1886                 }
1887
1888                 if (ok1 && ok2) return 1;
1889
1890                 if (line_isect_y(l1, l2, rect->ymax, &isect) && (isect >= cliprect->xmin) && (isect <= cliprect->xmax)) {
1891                         if (l1[1] > l2[1]) { /* line 1 is outside */
1892                                 l1_clip[0] = isect;
1893                                 l1_clip[1] = rect->ymax;
1894                                 ok1 = 1;
1895                         }
1896                         else {
1897                                 l2_clip[0] = isect;
1898                                 l2_clip[1] = rect->ymax;
1899                                 ok2 = 2;
1900                         }
1901                 }
1902
1903                 if (ok1 && ok2) return 1;
1904
1905                 /* left/right */
1906                 if (line_isect_x(l1, l2, rect->xmin, &isect) && (isect >= cliprect->ymin) && (isect <= cliprect->ymax)) {
1907                         if (l1[0] < l2[0]) { /* line 1 is outside */
1908                                 l1_clip[0] = rect->xmin;
1909                                 l1_clip[1] = isect;
1910                                 ok1 = 1;
1911                         }
1912                         else {
1913                                 l2_clip[0] = rect->xmin;
1914                                 l2_clip[1] = isect;
1915                                 ok2 = 2;
1916                         }
1917                 }
1918
1919                 if (ok1 && ok2) return 1;
1920
1921                 if (line_isect_x(l1, l2, rect->xmax, &isect) && (isect >= cliprect->ymin) && (isect <= cliprect->ymax)) {
1922                         if (l1[0] > l2[0]) { /* line 1 is outside */
1923                                 l1_clip[0] = rect->xmax;
1924                                 l1_clip[1] = isect;
1925                                 ok1 = 1;
1926                         }
1927                         else {
1928                                 l2_clip[0] = rect->xmax;
1929                                 l2_clip[1] = isect;
1930                                 ok2 = 2;
1931                         }
1932                 }
1933
1934                 if (ok1 && ok2) {
1935                         return 1;
1936                 }
1937                 else {
1938                         return 0;
1939                 }
1940         }
1941 }
1942
1943
1944
1945 /**
1946  * Scale the tri about its center
1947  * scaling by #PROJ_FACE_SCALE_SEAM (0.99x) is used for getting fake UV pixel coords that are on the
1948  * edge of the face but slightly inside it occlusion tests don't return hits on adjacent faces
1949  */
1950 #ifndef PROJ_DEBUG_NOSEAMBLEED
1951
1952 static void scale_tri(float insetCos[3][3], const float *origCos[4], const float inset)
1953 {
1954         float cent[3];
1955         cent[0] = (origCos[0][0] + origCos[1][0] + origCos[2][0]) * (1.0f / 3.0f);
1956         cent[1] = (origCos[0][1] + origCos[1][1] + origCos[2][1]) * (1.0f / 3.0f);
1957         cent[2] = (origCos[0][2] + origCos[1][2] + origCos[2][2]) * (1.0f / 3.0f);
1958
1959         sub_v3_v3v3(insetCos[0], origCos[0], cent);
1960         sub_v3_v3v3(insetCos[1], origCos[1], cent);
1961         sub_v3_v3v3(insetCos[2], origCos[2], cent);
1962
1963         mul_v3_fl(insetCos[0], inset);
1964         mul_v3_fl(insetCos[1], inset);
1965         mul_v3_fl(insetCos[2], inset);
1966
1967         add_v3_v3(insetCos[0], cent);
1968         add_v3_v3(insetCos[1], cent);
1969         add_v3_v3(insetCos[2], cent);
1970 }
1971 #endif //PROJ_DEBUG_NOSEAMBLEED
1972
1973 static float len_squared_v2v2_alt(const float v1[2], const float v2_1, const float v2_2)
1974 {
1975         float x, y;
1976
1977         x = v1[0] - v2_1;
1978         y = v1[1] - v2_2;
1979         return x * x + y * y;
1980 }
1981
1982 /* note, use a squared value so we can use len_squared_v2v2
1983  * be sure that you have done a bounds check first or this may fail */
1984 /* only give bucket_bounds as an arg because we need it elsewhere */
1985 static bool project_bucket_isect_circle(const float cent[2], const float radius_squared, const rctf *bucket_bounds)
1986 {
1987
1988         /* Would normally to a simple intersection test, however we know the bounds of these 2 already intersect
1989          * so we only need to test if the center is inside the vertical or horizontal bounds on either axis,
1990          * this is even less work then an intersection test
1991          */
1992 #if 0
1993         if (BLI_rctf_isect_pt_v(bucket_bounds, cent))
1994                 return 1;
1995 #endif
1996
1997         if ((bucket_bounds->xmin <= cent[0] && bucket_bounds->xmax >= cent[0]) ||
1998             (bucket_bounds->ymin <= cent[1] && bucket_bounds->ymax >= cent[1]))
1999         {
2000                 return 1;
2001         }
2002
2003         /* out of bounds left */
2004         if (cent[0] < bucket_bounds->xmin) {
2005                 /* lower left out of radius test */
2006                 if (cent[1] < bucket_bounds->ymin) {
2007                         return (len_squared_v2v2_alt(cent, bucket_bounds->xmin, bucket_bounds->ymin) < radius_squared) ? 1 : 0;
2008                 }
2009                 /* top left test */
2010                 else if (cent[1] > bucket_bounds->ymax) {
2011                         return (len_squared_v2v2_alt(cent, bucket_bounds->xmin, bucket_bounds->ymax) < radius_squared) ? 1 : 0;
2012                 }
2013         }
2014         else if (cent[0] > bucket_bounds->xmax) {
2015                 /* lower right out of radius test */
2016                 if (cent[1] < bucket_bounds->ymin) {
2017                         return (len_squared_v2v2_alt(cent, bucket_bounds->xmax, bucket_bounds->ymin) < radius_squared) ? 1 : 0;
2018                 }
2019                 /* top right test */
2020                 else if (cent[1] > bucket_bounds->ymax) {
2021                         return (len_squared_v2v2_alt(cent, bucket_bounds->xmax, bucket_bounds->ymax) < radius_squared) ? 1 : 0;
2022                 }
2023         }
2024
2025         return 0;
2026 }
2027
2028
2029
2030 /* Note for rect_to_uvspace_ortho() and rect_to_uvspace_persp()
2031  * in ortho view this function gives good results when bucket_bounds are outside the triangle
2032  * however in some cases, perspective view will mess up with faces that have minimal screenspace area
2033  * (viewed from the side)
2034  *
2035  * for this reason its not reliable in this case so we'll use the Simple Barycentric'
2036  * funcs that only account for points inside the triangle.
2037  * however switching back to this for ortho is always an option */
2038
2039 static void rect_to_uvspace_ortho(
2040         const rctf *bucket_bounds,
2041         const float *v1coSS, const float *v2coSS, const float *v3coSS,
2042         const float *uv1co, const float *uv2co, const float *uv3co,
2043         float bucket_bounds_uv[4][2],
2044         const int flip)
2045 {
2046         float uv[2];
2047         float w[3];
2048
2049         /* get the UV space bounding box */
2050         uv[0] = bucket_bounds->xmax;
2051         uv[1] = bucket_bounds->ymin;
2052         barycentric_weights_v2(v1coSS, v2coSS, v3coSS, uv, w);
2053         interp_v2_v2v2v2(bucket_bounds_uv[flip ? 3 : 0], uv1co, uv2co, uv3co, w);
2054
2055         //uv[0] = bucket_bounds->xmax; // set above
2056         uv[1] = bucket_bounds->ymax;
2057         barycentric_weights_v2(v1coSS, v2coSS, v3coSS, uv, w);
2058         interp_v2_v2v2v2(bucket_bounds_uv[flip ? 2 : 1], uv1co, uv2co, uv3co, w);
2059
2060         uv[0] = bucket_bounds->xmin;
2061         //uv[1] = bucket_bounds->ymax; // set above
2062         barycentric_weights_v2(v1coSS, v2coSS, v3coSS, uv, w);
2063         interp_v2_v2v2v2(bucket_bounds_uv[flip ? 1 : 2], uv1co, uv2co, uv3co, w);
2064
2065         //uv[0] = bucket_bounds->xmin; // set above
2066         uv[1] = bucket_bounds->ymin;
2067         barycentric_weights_v2(v1coSS, v2coSS, v3coSS, uv, w);
2068         interp_v2_v2v2v2(bucket_bounds_uv[flip ? 0 : 3], uv1co, uv2co, uv3co, w);
2069 }
2070
2071 /* same as above but use barycentric_weights_v2_persp */
2072 static void rect_to_uvspace_persp(
2073         const rctf *bucket_bounds,
2074         const float *v1coSS, const float *v2coSS, const float *v3coSS,
2075         const float *uv1co, const float *uv2co, const float *uv3co,
2076         float bucket_bounds_uv[4][2],
2077         const int flip
2078         )
2079 {
2080         float uv[2];
2081         float w[3];
2082
2083         /* get the UV space bounding box */
2084         uv[0] = bucket_bounds->xmax;
2085         uv[1] = bucket_bounds->ymin;
2086         barycentric_weights_v2_persp(v1coSS, v2coSS, v3coSS, uv, w);
2087         interp_v2_v2v2v2(bucket_bounds_uv[flip ? 3 : 0], uv1co, uv2co, uv3co, w);
2088
2089         //uv[0] = bucket_bounds->xmax; // set above
2090         uv[1] = bucket_bounds->ymax;
2091         barycentric_weights_v2_persp(v1coSS, v2coSS, v3coSS, uv, w);
2092         interp_v2_v2v2v2(bucket_bounds_uv[flip ? 2 : 1], uv1co, uv2co, uv3co, w);
2093
2094         uv[0] = bucket_bounds->xmin;
2095         //uv[1] = bucket_bounds->ymax; // set above
2096         barycentric_weights_v2_persp(v1coSS, v2coSS, v3coSS, uv, w);
2097         interp_v2_v2v2v2(bucket_bounds_uv[flip ? 1 : 2], uv1co, uv2co, uv3co, w);
2098
2099         //uv[0] = bucket_bounds->xmin; // set above
2100         uv[1] = bucket_bounds->ymin;
2101         barycentric_weights_v2_persp(v1coSS, v2coSS, v3coSS, uv, w);
2102         interp_v2_v2v2v2(bucket_bounds_uv[flip ? 0 : 3], uv1co, uv2co, uv3co, w);
2103 }
2104
2105 /* This works as we need it to but we can save a few steps and not use it */
2106
2107 #if 0
2108 static float angle_2d_clockwise(const float p1[2], const float p2[2], const float p3[2])
2109 {
2110         float v1[2], v2[2];
2111
2112         v1[0] = p1[0] - p2[0];    v1[1] = p1[1] - p2[1];
2113         v2[0] = p3[0] - p2[0];    v2[1] = p3[1] - p2[1];
2114
2115         return -atan2f(v1[0] * v2[1] - v1[1] * v2[0], v1[0] * v2[0] + v1[1] * v2[1]);
2116 }
2117 #endif
2118
2119 #define ISECT_1 (1)
2120 #define ISECT_2 (1 << 1)
2121 #define ISECT_3 (1 << 2)
2122 #define ISECT_4 (1 << 3)
2123 #define ISECT_ALL3 ((1 << 3) - 1)
2124 #define ISECT_ALL4 ((1 << 4) - 1)
2125
2126 /* limit must be a fraction over 1.0f */
2127 static bool IsectPT2Df_limit(
2128         const float pt[2],
2129         const float v1[2], const float v2[2], const float v3[2],
2130         const float limit)
2131 {
2132         return ((area_tri_v2(pt, v1, v2) +
2133                  area_tri_v2(pt, v2, v3) +
2134                  area_tri_v2(pt, v3, v1)) / (area_tri_v2(v1, v2, v3))) < limit;
2135 }
2136
2137 /* Clip the face by a bucket and set the uv-space bucket_bounds_uv
2138  * so we have the clipped UV's to do pixel intersection tests with
2139  * */
2140 static int float_z_sort_flip(const void *p1, const void *p2)
2141 {
2142         return (((float *)p1)[2] < ((float *)p2)[2] ? 1 : -1);
2143 }
2144
2145 static int float_z_sort(const void *p1, const void *p2)
2146 {
2147         return (((float *)p1)[2] < ((float *)p2)[2] ? -1 : 1);
2148 }
2149
2150 /* assumes one point is within the rectangle */
2151 static bool line_rect_clip(
2152         const rctf *rect,
2153         const float l1[4], const float l2[4],
2154         const float uv1[2], const float uv2[2],
2155         float uv[2], bool is_ortho)
2156 {
2157         float min = FLT_MAX, tmp;
2158         float xlen = l2[0] - l1[0];
2159         float ylen = l2[1] - l1[1];
2160
2161         /* 0.1 might seem too much, but remember, this is pixels! */
2162         if (xlen > 0.1f) {
2163                 if ((l1[0] - rect->xmin) * (l2[0] - rect->xmin) <= 0) {
2164                         tmp = rect->xmin;
2165                         min = min_ff((tmp - l1[0]) / xlen, min);
2166                 }
2167                 else if ((l1[0] - rect->xmax) * (l2[0] - rect->xmax) < 0) {
2168                         tmp = rect->xmax;
2169                         min = min_ff((tmp - l1[0]) / xlen, min);
2170                 }
2171         }
2172
2173         if (ylen > 0.1f) {
2174                 if ((l1[1] - rect->ymin) * (l2[1] - rect->ymin) <= 0) {
2175                         tmp = rect->ymin;
2176                         min = min_ff((tmp - l1[1]) / ylen, min);
2177                 }
2178                 else if ((l1[1] - rect->ymax) * (l2[1] - rect->ymax) < 0) {
2179                         tmp = rect->ymax;
2180                         min = min_ff((tmp - l1[1]) / ylen, min);
2181                 }
2182         }
2183
2184         if (min == FLT_MAX)
2185                 return false;
2186
2187         tmp = (is_ortho) ? 1.0f : (l1[3] + min * (l2[3] - l1[3]));
2188
2189         uv[0] = (uv1[0] + min / tmp * (uv2[0] - uv1[0]));
2190         uv[1] = (uv1[1] + min / tmp * (uv2[1] - uv1[1]));
2191
2192         return true;
2193 }
2194
2195
2196 static void project_bucket_clip_face(
2197         const bool is_ortho, const bool is_flip_object,
2198         const rctf *cliprect,
2199         const rctf *bucket_bounds,
2200         const float *v1coSS, const float *v2coSS, const float *v3coSS,
2201         const float *uv1co, const float *uv2co, const float *uv3co,
2202         float bucket_bounds_uv[8][2],
2203         int *tot, bool cull)
2204 {
2205         int inside_bucket_flag = 0;
2206         int inside_face_flag = 0;
2207         int flip;
2208         bool collinear = false;
2209
2210         float bucket_bounds_ss[4][2];
2211
2212         /* detect pathological case where face the three vertices are almost collinear in screen space.
2213          * mostly those will be culled but when flood filling or with
2214          * smooth shading it's a possibility */
2215         if (min_fff(dist_squared_to_line_v2(v1coSS, v2coSS, v3coSS),
2216                     dist_squared_to_line_v2(v2coSS, v3coSS, v1coSS),
2217                     dist_squared_to_line_v2(v3coSS, v1coSS, v2coSS)) < PROJ_PIXEL_TOLERANCE)
2218         {
2219                 collinear = true;
2220         }
2221
2222         /* get the UV space bounding box */
2223         inside_bucket_flag |= BLI_rctf_isect_pt_v(bucket_bounds, v1coSS);
2224         inside_bucket_flag |= BLI_rctf_isect_pt_v(bucket_bounds, v2coSS) << 1;
2225         inside_bucket_flag |= BLI_rctf_isect_pt_v(bucket_bounds, v3coSS) << 2;
2226
2227         if (inside_bucket_flag == ISECT_ALL3) {
2228                 /* is_flip_object is used here because we use the face winding */
2229                 flip = (((line_point_side_v2(v1coSS, v2coSS, v3coSS) > 0.0f) != is_flip_object) !=
2230                         (line_point_side_v2(uv1co, uv2co, uv3co) > 0.0f));
2231
2232                 /* all screenspace points are inside the bucket bounding box,
2233                  * this means we don't need to clip and can simply return the UVs */
2234                 if (flip) { /* facing the back? */
2235                         copy_v2_v2(bucket_bounds_uv[0], uv3co);
2236                         copy_v2_v2(bucket_bounds_uv[1], uv2co);
2237                         copy_v2_v2(bucket_bounds_uv[2], uv1co);
2238                 }
2239                 else {
2240                         copy_v2_v2(bucket_bounds_uv[0], uv1co);
2241                         copy_v2_v2(bucket_bounds_uv[1], uv2co);
2242                         copy_v2_v2(bucket_bounds_uv[2], uv3co);
2243                 }
2244
2245                 *tot = 3;
2246                 return;
2247         }
2248         /* handle pathological case here,
2249          * no need for further intersections below since tringle area is almost zero */
2250         if (collinear) {
2251                 int flag;
2252
2253                 (*tot) = 0;
2254
2255                 if (cull)
2256                         return;
2257
2258                 if (inside_bucket_flag & ISECT_1) { copy_v2_v2(bucket_bounds_uv[*tot], uv1co); (*tot)++; }
2259
2260                 flag = inside_bucket_flag & (ISECT_1 | ISECT_2);
2261                 if (flag && flag != (ISECT_1 | ISECT_2)) {
2262                         if (line_rect_clip(bucket_bounds, v1coSS, v2coSS, uv1co, uv2co, bucket_bounds_uv[*tot], is_ortho))
2263                                 (*tot)++;
2264                 }
2265
2266                 if (inside_bucket_flag & ISECT_2) { copy_v2_v2(bucket_bounds_uv[*tot], uv2co); (*tot)++; }
2267
2268                 flag = inside_bucket_flag & (ISECT_2 | ISECT_3);
2269                 if (flag && flag != (ISECT_2 | ISECT_3)) {
2270                         if (line_rect_clip(bucket_bounds, v2coSS, v3coSS, uv2co, uv3co, bucket_bounds_uv[*tot], is_ortho))
2271                                 (*tot)++;
2272                 }
2273
2274                 if (inside_bucket_flag & ISECT_3) { copy_v2_v2(bucket_bounds_uv[*tot], uv3co); (*tot)++; }
2275
2276                 flag = inside_bucket_flag & (ISECT_3 | ISECT_1);
2277                 if (flag && flag != (ISECT_3 | ISECT_1)) {
2278                         if (line_rect_clip(bucket_bounds, v3coSS, v1coSS, uv3co, uv1co, bucket_bounds_uv[*tot], is_ortho))
2279                                 (*tot)++;
2280                 }
2281
2282                 if ((*tot) < 3) {
2283                         /* no intersections to speak of, but more probable is that all face is just outside the
2284                          * rectangle and culled due to float precision issues. Since above tests have failed,
2285                          * just dump triangle as is for painting */
2286                         *tot = 0;
2287                         copy_v2_v2(bucket_bounds_uv[*tot], uv1co); (*tot)++;
2288                         copy_v2_v2(bucket_bounds_uv[*tot], uv2co); (*tot)++;
2289                         copy_v2_v2(bucket_bounds_uv[*tot], uv3co); (*tot)++;
2290                         return;
2291                 }
2292
2293                 return;
2294         }
2295
2296         /* get the UV space bounding box */
2297         /* use IsectPT2Df_limit here so we catch points are are touching the tri edge
2298          * (or a small fraction over) */
2299         bucket_bounds_ss[0][0] = bucket_bounds->xmax;
2300         bucket_bounds_ss[0][1] = bucket_bounds->ymin;
2301         inside_face_flag |= (IsectPT2Df_limit(bucket_bounds_ss[0], v1coSS, v2coSS, v3coSS, 1 + PROJ_GEOM_TOLERANCE) ? ISECT_1 : 0);
2302
2303         bucket_bounds_ss[1][0] = bucket_bounds->xmax;
2304         bucket_bounds_ss[1][1] = bucket_bounds->ymax;
2305         inside_face_flag |= (IsectPT2Df_limit(bucket_bounds_ss[1], v1coSS, v2coSS, v3coSS, 1 + PROJ_GEOM_TOLERANCE) ? ISECT_2 : 0);
2306
2307         bucket_bounds_ss[2][0] = bucket_bounds->xmin;
2308         bucket_bounds_ss[2][1] = bucket_bounds->ymax;
2309         inside_face_flag |= (IsectPT2Df_limit(bucket_bounds_ss[2], v1coSS, v2coSS, v3coSS, 1 + PROJ_GEOM_TOLERANCE) ? ISECT_3 : 0);
2310
2311         bucket_bounds_ss[3][0] = bucket_bounds->xmin;
2312         bucket_bounds_ss[3][1] = bucket_bounds->ymin;
2313         inside_face_flag |= (IsectPT2Df_limit(bucket_bounds_ss[3], v1coSS, v2coSS, v3coSS, 1 + PROJ_GEOM_TOLERANCE) ? ISECT_4 : 0);
2314
2315         flip = ((line_point_side_v2(v1coSS, v2coSS, v3coSS) > 0.0f) !=
2316                 (line_point_side_v2(uv1co, uv2co, uv3co) > 0.0f));
2317
2318         if (inside_face_flag == ISECT_ALL4) {
2319                 /* bucket is totally inside the screenspace face, we can safely use weights */
2320
2321                 if (is_ortho) {
2322                         rect_to_uvspace_ortho(bucket_bounds, v1coSS, v2coSS, v3coSS, uv1co, uv2co, uv3co, bucket_bounds_uv, flip);
2323                 }
2324                 else {
2325                         rect_to_uvspace_persp(bucket_bounds, v1coSS, v2coSS, v3coSS, uv1co, uv2co, uv3co, bucket_bounds_uv, flip);
2326                 }
2327
2328                 *tot = 4;
2329                 return;
2330         }
2331         else {
2332                 /* The Complicated Case!
2333                  *
2334                  * The 2 cases above are where the face is inside the bucket
2335                  * or the bucket is inside the face.
2336                  *
2337                  * we need to make a convex polyline from the intersection between the screenspace face
2338                  * and the bucket bounds.
2339                  *
2340                  * There are a number of ways this could be done, currently it just collects all
2341                  * intersecting verts, and line intersections, then sorts them clockwise, this is
2342                  * a lot easier then evaluating the geometry to do a correct clipping on both shapes.
2343                  */
2344
2345
2346                 /* Add a bunch of points, we know must make up the convex hull
2347                  * which is the clipped rect and triangle */
2348
2349                 /* Maximum possible 6 intersections when using a rectangle and triangle */
2350
2351                 /* The 3rd float is used to store angle for qsort(), NOT as a Z location */
2352                 float isectVCosSS[8][3];
2353                 float v1_clipSS[2], v2_clipSS[2];
2354                 float w[3];
2355
2356                 /* calc center */
2357                 float cent[2] = {0.0f, 0.0f};
2358                 /*float up[2] = {0.0f, 1.0f};*/
2359                 int i;
2360                 bool doubles;
2361
2362                 (*tot) = 0;
2363
2364                 if (inside_face_flag & ISECT_1) { copy_v2_v2(isectVCosSS[*tot], bucket_bounds_ss[0]); (*tot)++; }
2365                 if (inside_face_flag & ISECT_2) { copy_v2_v2(isectVCosSS[*tot], bucket_bounds_ss[1]); (*tot)++; }
2366                 if (inside_face_flag & ISECT_3) { copy_v2_v2(isectVCosSS[*tot], bucket_bounds_ss[2]); (*tot)++; }
2367                 if (inside_face_flag & ISECT_4) { copy_v2_v2(isectVCosSS[*tot], bucket_bounds_ss[3]); (*tot)++; }
2368
2369                 if (inside_bucket_flag & ISECT_1) { copy_v2_v2(isectVCosSS[*tot], v1coSS); (*tot)++; }
2370                 if (inside_bucket_flag & ISECT_2) { copy_v2_v2(isectVCosSS[*tot], v2coSS); (*tot)++; }
2371                 if (inside_bucket_flag & ISECT_3) { copy_v2_v2(isectVCosSS[*tot], v3coSS); (*tot)++; }
2372
2373                 if ((inside_bucket_flag & (ISECT_1 | ISECT_2)) != (ISECT_1 | ISECT_2)) {
2374                         if (line_clip_rect2f(cliprect, bucket_bounds, v1coSS, v2coSS, v1_clipSS, v2_clipSS)) {
2375                                 if ((inside_bucket_flag & ISECT_1) == 0) { copy_v2_v2(isectVCosSS[*tot], v1_clipSS); (*tot)++; }
2376                                 if ((inside_bucket_flag & ISECT_2) == 0) { copy_v2_v2(isectVCosSS[*tot], v2_clipSS); (*tot)++; }
2377                         }
2378                 }
2379
2380                 if ((inside_bucket_flag & (ISECT_2 | ISECT_3)) != (ISECT_2 | ISECT_3)) {
2381                         if (line_clip_rect2f(cliprect, bucket_bounds, v2coSS, v3coSS, v1_clipSS, v2_clipSS)) {
2382                                 if ((inside_bucket_flag & ISECT_2) == 0) { copy_v2_v2(isectVCosSS[*tot], v1_clipSS); (*tot)++; }
2383                                 if ((inside_bucket_flag & ISECT_3) == 0) { copy_v2_v2(isectVCosSS[*tot], v2_clipSS); (*tot)++; }
2384                         }
2385                 }
2386
2387                 if ((inside_bucket_flag & (ISECT_3 | ISECT_1)) != (ISECT_3 | ISECT_1)) {
2388                         if (line_clip_rect2f(cliprect, bucket_bounds, v3coSS, v1coSS, v1_clipSS, v2_clipSS)) {
2389                                 if ((inside_bucket_flag & ISECT_3) == 0) { copy_v2_v2(isectVCosSS[*tot], v1_clipSS); (*tot)++; }
2390                                 if ((inside_bucket_flag & ISECT_1) == 0) { copy_v2_v2(isectVCosSS[*tot], v2_clipSS); (*tot)++; }
2391                         }
2392                 }
2393
2394
2395                 if ((*tot) < 3) { /* no intersections to speak of */
2396                         *tot = 0;
2397                         return;
2398                 }
2399
2400                 /* now we have all points we need, collect their angles and sort them clockwise */
2401
2402                 for (i = 0; i < (*tot); i++) {
2403                         cent[0] += isectVCosSS[i][0];
2404                         cent[1] += isectVCosSS[i][1];
2405                 }
2406                 cent[0] = cent[0] / (float)(*tot);
2407                 cent[1] = cent[1] / (float)(*tot);
2408
2409
2410
2411                 /* Collect angles for every point around the center point */
2412
2413
2414 #if 0   /* uses a few more cycles then the above loop */
2415                 for (i = 0; i < (*tot); i++) {
2416                         isectVCosSS[i][2] = angle_2d_clockwise(up, cent, isectVCosSS[i]);
2417                 }
2418 #endif
2419
2420                 /* Abuse this var for the loop below */
2421                 v1_clipSS[0] = cent[0];
2422                 v1_clipSS[1] = cent[1] + 1.0f;
2423
2424                 for (i = 0; i < (*tot); i++) {
2425                         v2_clipSS[0] = isectVCosSS[i][0] - cent[0];
2426                         v2_clipSS[1] = isectVCosSS[i][1] - cent[1];
2427                         isectVCosSS[i][2] = atan2f(v1_clipSS[0] * v2_clipSS[1] - v1_clipSS[1] * v2_clipSS[0],
2428                                                    v1_clipSS[0] * v2_clipSS[0] + v1_clipSS[1] * v2_clipSS[1]);
2429                 }
2430
2431                 if (flip) qsort(isectVCosSS, *tot, sizeof(float) * 3, float_z_sort_flip);
2432                 else      qsort(isectVCosSS, *tot, sizeof(float) * 3, float_z_sort);
2433
2434                 doubles = true;
2435                 while (doubles == true) {
2436                         doubles = false;
2437
2438                         for (i = 0; i < (*tot); i++) {
2439                                 if (fabsf(isectVCosSS[(i + 1) % *tot][0] - isectVCosSS[i][0]) < PROJ_PIXEL_TOLERANCE &&
2440                                     fabsf(isectVCosSS[(i + 1) % *tot][1] - isectVCosSS[i][1]) < PROJ_PIXEL_TOLERANCE)
2441                                 {
2442                                         int j;
2443                                         for (j = i; j < (*tot) - 1; j++) {
2444                                                 isectVCosSS[j][0] = isectVCosSS[j + 1][0];
2445                                                 isectVCosSS[j][1] = isectVCosSS[j + 1][1];
2446                                         }
2447                                         /* keep looking for more doubles */
2448                                         doubles = true;
2449                                         (*tot)--;
2450                                 }
2451                         }
2452
2453                         /* its possible there is only a few left after remove doubles */
2454                         if ((*tot) < 3) {
2455                                 // printf("removed too many doubles B\n");
2456                                 *tot = 0;
2457                                 return;
2458                         }
2459                 }
2460
2461                 if (is_ortho) {
2462                         for (i = 0; i < (*tot); i++) {
2463                                 barycentric_weights_v2(v1coSS, v2coSS, v3coSS, isectVCosSS[i], w);
2464                                 interp_v2_v2v2v2(bucket_bounds_uv[i], uv1co, uv2co, uv3co, w);
2465                         }
2466                 }
2467                 else {
2468                         for (i = 0; i < (*tot); i++) {
2469                                 barycentric_weights_v2_persp(v1coSS, v2coSS, v3coSS, isectVCosSS[i], w);
2470                                 interp_v2_v2v2v2(bucket_bounds_uv[i], uv1co, uv2co, uv3co, w);
2471                         }
2472                 }
2473         }
2474
2475 #ifdef PROJ_DEBUG_PRINT_CLIP
2476         /* include this at the bottom of the above function to debug the output */
2477
2478         {
2479                 /* If there are ever any problems, */
2480                 float test_uv[4][2];
2481                 int i;
2482                 if (is_ortho) rect_to_uvspace_ortho(bucket_bounds, v1coSS, v2coSS, v3coSS, uv1co, uv2co, uv3co, test_uv, flip);
2483                 else          rect_to_uvspace_persp(bucket_bounds, v1coSS, v2coSS, v3coSS, uv1co, uv2co, uv3co, test_uv, flip);
2484                 printf("(  [(%f,%f), (%f,%f), (%f,%f), (%f,%f)], ",
2485                        test_uv[0][0], test_uv[0][1],   test_uv[1][0], test_uv[1][1],
2486                        test_uv[2][0], test_uv[2][1],    test_uv[3][0], test_uv[3][1]);
2487
2488                 printf("  [(%f,%f), (%f,%f), (%f,%f)], ", uv1co[0], uv1co[1],   uv2co[0], uv2co[1],    uv3co[0], uv3co[1]);
2489
2490                 printf("[");
2491                 for (i = 0; i < (*tot); i++) {
2492                         printf("(%f, %f),", bucket_bounds_uv[i][0], bucket_bounds_uv[i][1]);
2493                 }
2494                 printf("]),\\\n");
2495         }
2496 #endif
2497 }
2498
2499 /*
2500  * # This script creates faces in a blender scene from printed data above.
2501  *
2502  * project_ls = [
2503  * ...(output from above block)...
2504  * ]
2505  *
2506  * from Blender import Scene, Mesh, Window, sys, Mathutils
2507  *
2508  * import bpy
2509  *
2510  * V = Mathutils.Vector
2511  *
2512  * def main():
2513  *     sce = bpy.data.scenes.active
2514  *
2515  *     for item in project_ls:
2516  *         bb = item[0]
2517  *         uv = item[1]
2518  *         poly = item[2]
2519  *
2520  *         me = bpy.data.meshes.new()
2521  *         ob = sce.objects.new(me)
2522  *
2523  *         me.verts.extend([V(bb[0]).xyz, V(bb[1]).xyz, V(bb[2]).xyz, V(bb[3]).xyz])
2524  *         me.faces.extend([(0,1,2,3),])
2525  *         me.verts.extend([V(uv[0]).xyz, V(uv[1]).xyz, V(uv[2]).xyz])
2526  *         me.faces.extend([(4,5,6),])
2527  *
2528  *         vs = [V(p).xyz for p in poly]
2529  *         print len(vs)
2530  *         l = len(me.verts)
2531  *         me.verts.extend(vs)
2532  *
2533  *         i = l
2534  *         while i < len(me.verts):
2535  *             ii = i + 1
2536  *             if ii == len(me.verts):
2537  *                 ii = l
2538  *             me.edges.extend([i, ii])
2539  *             i += 1
2540  *
2541  * if __name__ == '__main__':
2542  *     main()
2543  */
2544
2545
2546 #undef ISECT_1
2547 #undef ISECT_2
2548 #undef ISECT_3
2549 #undef ISECT_4
2550 #undef ISECT_ALL3
2551 #undef ISECT_ALL4
2552
2553
2554 /* checks if pt is inside a convex 2D polyline, the polyline must be ordered rotating clockwise
2555  * otherwise it would have to test for mixed (line_point_side_v2 > 0.0f) cases */
2556 static bool IsectPoly2Df(const float pt[2], float uv[][2], const int tot)
2557 {
2558         int i;
2559         if (line_point_side_v2(uv[tot - 1], uv[0], pt) < 0.0f)
2560                 return 0;
2561
2562         for (i = 1; i < tot; i++) {
2563                 if (line_point_side_v2(uv[i - 1], uv[i], pt) < 0.0f)
2564                         return 0;
2565
2566         }
2567
2568         return 1;
2569 }
2570 static bool IsectPoly2Df_twoside(const float pt[2], float uv[][2], const int tot)
2571 {
2572         int i;
2573         bool side = (line_point_side_v2(uv[tot - 1], uv[0], pt) > 0.0f);
2574
2575         for (i = 1; i < tot; i++) {
2576                 if ((line_point_side_v2(uv[i - 1], uv[i], pt) > 0.0f) != side)
2577                         return 0;
2578
2579         }
2580
2581         return 1;
2582 }
2583
2584 /* One of the most important function for projection painting,
2585  * since it selects the pixels to be added into each bucket.
2586  *
2587  * initialize pixels from this face where it intersects with the bucket_index,
2588  * optionally initialize pixels for removing seams */
2589 static void project_paint_face_init(
2590         const ProjPaintState *ps,
2591         const int thread_index, const int bucket_index, const int tri_index, const int image_index,
2592         const rctf *clip_rect, const rctf *bucket_bounds, ImBuf *ibuf, ImBuf **tmpibuf)
2593 {
2594         /* Projection vars, to get the 3D locations into screen space  */
2595         MemArena *arena = ps->arena_mt[thread_index];
2596         LinkNode **bucketPixelNodes = ps->bucketRect + bucket_index;
2597         LinkNode *bucketFaceNodes = ps->bucketFaces[bucket_index];
2598         bool threaded = (ps->thread_tot > 1);
2599
2600         TileInfo tinf = {
2601                 ps->tile_lock,
2602                 ps->do_masking,
2603                 IMAPAINT_TILE_NUMBER(ibuf->x),
2604                 tmpibuf,
2605                 ps->projImages + image_index
2606         };
2607
2608         const MLoopTri *lt = &ps->mlooptri_eval[tri_index];
2609         const int lt_vtri[3] = { PS_LOOPTRI_AS_VERT_INDEX_3(ps, lt) };
2610         const float *lt_tri_uv[3] = { PS_LOOPTRI_AS_UV_3(ps->poly_to_loop_uv, lt) };
2611
2612         /* UV/pixel seeking data */
2613         /* Image X/Y-Pixel */
2614         int x, y;
2615         float mask;
2616         /* Image floating point UV - same as x, y but from 0.0-1.0 */
2617         float uv[2];
2618
2619         /* vert co screen-space, these will be assigned to lt_vtri[0-2] */
2620         const float *v1coSS, *v2coSS, *v3coSS;
2621
2622         /* vertex screenspace coords */
2623         const float *vCo[3];
2624
2625         float w[3], wco[3];
2626
2627         /* for convenience only, these will be assigned to lt_tri_uv[0],1,2 or lt_tri_uv[0],2,3 */
2628         float *uv1co, *uv2co, *uv3co;
2629         float pixelScreenCo[4];
2630         bool do_3d_mapping = ps->brush->mtex.brush_map_mode == MTEX_MAP_MODE_3D;
2631
2632         /* ispace bounds */
2633         rcti bounds_px;
2634         /* vars for getting uvspace bounds */
2635
2636         /* bucket bounds in UV space so we can init pixels only for this face,  */
2637         float lt_uv_pxoffset[3][2];
2638         float xhalfpx, yhalfpx;
2639         const float ibuf_xf = (float)ibuf->x, ibuf_yf = (float)ibuf->y;
2640
2641         /* for early loop exit */
2642         int has_x_isect = 0, has_isect = 0;
2643
2644         float uv_clip[8][2];
2645         int uv_clip_tot;
2646         const bool is_ortho = ps->is_ortho;
2647         const bool is_flip_object = ps->is_flip_object;
2648         const bool do_backfacecull = ps->do_backfacecull;
2649         const bool do_clip = ps->rv3d ? ps->rv3d->rflag & RV3D_CLIPPING : 0;
2650
2651         vCo[0] = ps->mvert_eval[lt_vtri[0]].co;
2652         vCo[1] = ps->mvert_eval[lt_vtri[1]].co;
2653         vCo[2] = ps->mvert_eval[lt_vtri[2]].co;
2654
2655
2656         /* Use lt_uv_pxoffset instead of lt_tri_uv so we can offset the UV half a pixel
2657          * this is done so we can avoid offsetting all the pixels by 0.5 which causes
2658          * problems when wrapping negative coords */
2659         xhalfpx = (0.5f + (PROJ_PIXEL_TOLERANCE * (1.0f / 3.0f))) / ibuf_xf;
2660         yhalfpx = (0.5f + (PROJ_PIXEL_TOLERANCE * (1.0f / 4.0f))) / ibuf_yf;
2661
2662         /* Note about (PROJ_GEOM_TOLERANCE/x) above...
2663          * Needed to add this offset since UV coords are often quads aligned to pixels.
2664          * In this case pixels can be exactly between 2 triangles causing nasty
2665          * artifacts.
2666          *
2667          * This workaround can be removed and painting will still work on most cases
2668          * but since the first thing most people try is painting onto a quad- better make it work.
2669          */
2670
2671         lt_uv_pxoffset[0][0] = lt_tri_uv[0][0] - xhalfpx;
2672         lt_uv_pxoffset[0][1] = lt_tri_uv[0][1] - yhalfpx;
2673
2674         lt_uv_pxoffset[1][0] = lt_tri_uv[1][0] - xhalfpx;
2675         lt_uv_pxoffset[1][1] = lt_tri_uv[1][1] - yhalfpx;
2676
2677         lt_uv_pxoffset[2][0] = lt_tri_uv[2][0] - xhalfpx;
2678         lt_uv_pxoffset[2][1] = lt_tri_uv[2][1] - yhalfpx;
2679
2680         {
2681                 uv1co = lt_uv_pxoffset[0]; // was lt_tri_uv[i1];
2682                 uv2co = lt_uv_pxoffset[1]; // was lt_tri_uv[i2];
2683                 uv3co = lt_uv_pxoffset[2]; // was lt_tri_uv[i3];
2684
2685                 v1coSS = ps->screenCoords[lt_vtri[0]];
2686                 v2coSS = ps->screenCoords[lt_vtri[1]];
2687                 v3coSS = ps->screenCoords[lt_vtri[2]];
2688
2689                 /* This function gives is a concave polyline in UV space from the clipped tri*/
2690                 project_bucket_clip_face(
2691                         is_ortho, is_flip_object,
2692                         clip_rect, bucket_bounds,
2693                         v1coSS, v2coSS, v3coSS,
2694                         uv1co, uv2co, uv3co,
2695                         uv_clip, &uv_clip_tot,
2696                         do_backfacecull || ps->do_occlude);
2697
2698                 /* sometimes this happens, better just allow for 8 intersectiosn even though there should be max 6 */
2699 #if 0
2700                 if (uv_clip_tot > 6) {
2701                         printf("this should never happen! %d\n", uv_clip_tot);
2702                 }
2703 #endif
2704
2705                 if (pixel_bounds_array(uv_clip, &bounds_px, ibuf->x, ibuf->y, uv_clip_tot)) {
2706 #if 0
2707                         project_paint_undo_tiles_init(
2708                                 &bounds_px, ps->projImages + image_index, tmpibuf,
2709                                 tile_width, threaded, ps->do_masking);
2710 #endif
2711                         /* clip face and */
2712
2713                         has_isect = 0;
2714                         for (y = bounds_px.ymin; y < bounds_px.ymax; y++) {
2715                                 //uv[1] = (((float)y) + 0.5f) / (float)ibuf->y;
2716                                 /* use pixel offset UV coords instead */
2717                                 uv[1] = (float)y / ibuf_yf;
2718
2719                                 has_x_isect = 0;
2720                                 for (x = bounds_px.xmin; x < bounds_px.xmax; x++) {
2721                                         //uv[0] = (((float)x) + 0.5f) / ibuf->x;
2722                                         /* use pixel offset UV coords instead */
2723                                         uv[0] = (float)x / ibuf_xf;
2724
2725                                         /* Note about IsectPoly2Df_twoside, checking the face or uv flipping doesn't work,
2726                                          * could check the poly direction but better to do this */
2727                                         if ((do_backfacecull == true  && IsectPoly2Df(uv, uv_clip, uv_clip_tot)) ||
2728                                             (do_backfacecull == false && IsectPoly2Df_twoside(uv, uv_clip, uv_clip_tot)))
2729                                         {
2730
2731                                                 has_x_isect = has_isect = 1;
2732
2733                                                 if (is_ortho) screen_px_from_ortho(uv, v1coSS, v2coSS, v3coSS, uv1co, uv2co, uv3co, pixelScreenCo, w);
2734                                                 else screen_px_from_persp(uv, v1coSS, v2coSS, v3coSS, uv1co, uv2co, uv3co, pixelScreenCo, w);
2735
2736                                                 /* a pity we need to get the worldspace pixel location here */
2737                                                 if (do_clip || do_3d_mapping) {
2738                                                         interp_v3_v3v3v3(
2739                                                                 wco,
2740                                                                 ps->mvert_eval[lt_vtri[0]].co,
2741                                                                 ps->mvert_eval[lt_vtri[1]].co,
2742                                                                 ps->mvert_eval[lt_vtri[2]].co,
2743                                                                 w);
2744                                                         if (do_clip && ED_view3d_clipping_test(ps->rv3d, wco, true)) {
2745                                                                 /* Watch out that no code below this needs to run */
2746                                                                 continue;
2747                                                         }
2748                                                 }
2749
2750                                                 /* Is this UV visible from the view? - raytrace */
2751                                                 /* project_paint_PickFace is less complex, use for testing */
2752                                                 //if (project_paint_PickFace(ps, pixelScreenCo, w, &side) == tri_index) {
2753                                                 if ((ps->do_occlude == false) ||
2754                                                     !project_bucket_point_occluded(ps, bucketFaceNodes, tri_index, pixelScreenCo))
2755                                                 {
2756                                                         mask = project_paint_uvpixel_mask(ps, tri_index, w);
2757
2758                                                         if (mask > 0.0f) {
2759                                                                 BLI_linklist_prepend_arena(
2760                                                                         bucketPixelNodes,
2761                                                                         project_paint_uvpixel_init(
2762                                                                                 ps, arena, &tinf, x, y, mask, tri_index,
2763                                                                                 pixelScreenCo, wco, w),
2764                                                                         arena);
2765                                                         }
2766                                                 }
2767
2768                                         }
2769 //#if 0
2770                                         else if (has_x_isect) {
2771                                                 /* assuming the face is not a bow-tie - we know we cant intersect again on the X */
2772                                                 break;
2773                                         }
2774 //#endif
2775                                 }
2776
2777
2778 #if 0           /* TODO - investigate why this dosnt work sometimes! it should! */
2779                                 /* no intersection for this entire row,
2780                                  * after some intersection above means we can quit now */
2781                                 if (has_x_isect == 0 && has_isect) {
2782                                         break;
2783                                 }
2784 #endif
2785                         }
2786                 }
2787         }
2788
2789
2790 #ifndef PROJ_DEBUG_NOSEAMBLEED
2791         if (ps->seam_bleed_px > 0.0f) {
2792                 int face_seam_flag;
2793
2794                 if (threaded) {
2795                         /* Other threads could be modifying these vars. */
2796                         BLI_thread_lock(LOCK_CUSTOM1);
2797                 }
2798
2799                 face_seam_flag = ps->faceSeamFlags[tri_index];
2800
2801                 /* are any of our edges un-initialized? */
2802                 if ((face_seam_flag & (PROJ_FACE_SEAM1 | PROJ_FACE_NOSEAM1)) == 0 ||
2803                     (face_seam_flag & (PROJ_FACE_SEAM2 | PROJ_FACE_NOSEAM2)) == 0 ||
2804                     (face_seam_flag & (PROJ_FACE_SEAM3 | PROJ_FACE_NOSEAM3)) == 0)
2805                 {
2806                         project_face_seams_init(ps, tri_index);
2807                         face_seam_flag = ps->faceSeamFlags[tri_index];
2808                         //printf("seams - %d %d %d %d\n", flag&PROJ_FACE_SEAM1, flag&PROJ_FACE_SEAM2, flag&PROJ_FACE_SEAM3);
2809                 }
2810
2811                 if ((face_seam_flag & (PROJ_FACE_SEAM1 | PROJ_FACE_SEAM2 | PROJ_FACE_SEAM3)) == 0) {
2812
2813                         if (threaded) {
2814                                 /* Other threads could be modifying these vars. */
2815                                 BLI_thread_unlock(LOCK_CUSTOM1);
2816                         }
2817
2818                 }
2819                 else {
2820                         /* we have a seam - deal with it! */
2821
2822                         /* Now create new UV's for the seam face */
2823                         float (*outset_uv)[2] = ps->faceSeamUVs[tri_index];
2824                         /* inset face coords.  NOTE!!! ScreenSace for ortho, Worldspace in perspective view */
2825                         float insetCos[3][3];
2826
2827                         /* vertex screenspace coords */
2828                         const float *vCoSS[3];
2829
2830                         /* Store the screenspace coords of the face,
2831                          * clipped by the bucket's screen aligned rectangle. */
2832                         float bucket_clip_edges[2][2];
2833                         float edge_verts_inset_clip[2][3];
2834                         /* face edge pairs - loop throuh these:
2835                          * ((0,1), (1,2), (2,3), (3,0)) or ((0,1), (1,2), (2,0)) for a tri */
2836                         int fidx1, fidx2;
2837
2838                         float seam_subsection[4][2];
2839                         float fac1, fac2;
2840
2841                         if (outset_uv[0][0] == FLT_MAX) /* first time initialize */
2842                                 uv_image_outset(
2843                                         lt_uv_pxoffset, outset_uv, ps->seam_bleed_px,
2844                                         ibuf->x, ibuf->y, (ps->faceWindingFlags[tri_index] & PROJ_FACE_WINDING_CW) == 0);
2845
2846                         /* ps->faceSeamUVs cant be modified when threading, now this is done we can unlock. */
2847                         if (threaded) {
2848                                 /* Other threads could be modifying these vars */
2849                                 BLI_thread_unlock(LOCK_CUSTOM1);
2850                         }
2851
2852                         vCoSS[0] = ps->screenCoords[lt_vtri[0]];
2853                         vCoSS[1] = ps->screenCoords[lt_vtri[1]];
2854                         vCoSS[2] = ps->screenCoords[lt_vtri[2]];
2855
2856                         /* PROJ_FACE_SCALE_SEAM must be slightly less then 1.0f */
2857                         if (is_ortho) {
2858                                 scale_tri(insetCos, vCoSS, PROJ_FACE_SCALE_SEAM);
2859                         }
2860                         else {
2861                                 scale_tri(insetCos, vCo, PROJ_FACE_SCALE_SEAM);
2862                         }
2863
2864                         for (fidx1 = 0; fidx1 < 3; fidx1++) {
2865                                 /* next fidx in the face (0,1,2) -> (1,2,0) */
2866                                 fidx2 = (fidx1 == 2) ? 0 : fidx1 + 1;
2867
2868                                 if ((face_seam_flag & (1 << fidx1)) && /* 1<<fidx1 -> PROJ_FACE_SEAM# */
2869                                     line_clip_rect2f(clip_rect, bucket_bounds, vCoSS[fidx1], vCoSS[fidx2], bucket_clip_edges[0], bucket_clip_edges[1]))
2870                                 {
2871                                         /* Avoid div by zero. */
2872                                         if (len_squared_v2v2(vCoSS[fidx1], vCoSS[fidx2]) > FLT_EPSILON) {
2873
2874                                                 if (is_ortho) {
2875                                                         fac1 = line_point_factor_v2(bucket_clip_edges[0], vCoSS[fidx1], vCoSS[fidx2]);
2876                                                         fac2 = line_point_factor_v2(bucket_clip_edges[1], vCoSS[fidx1], vCoSS[fidx2]);
2877                                                 }
2878                                                 else {
2879                                                         fac1 = screen_px_line_point_factor_v2_persp(ps, bucket_clip_edges[0], vCo[fidx1], vCo[fidx2]);
2880                                                         fac2 = screen_px_line_point_factor_v2_persp(ps, bucket_clip_edges[1], vCo[fidx1], vCo[fidx2]);
2881                                                 }
2882
2883                                                 interp_v2_v2v2(seam_subsection[0], lt_uv_pxoffset[fidx1], lt_uv_pxoffset[fidx2], fac1);
2884                                                 interp_v2_v2v2(seam_subsection[1], lt_uv_pxoffset[fidx1], lt_uv_pxoffset[fidx2], fac2);
2885
2886                                                 interp_v2_v2v2(seam_subsection[2], outset_uv[fidx1], outset_uv[fidx2], fac2);
2887                                                 interp_v2_v2v2(seam_subsection[3], outset_uv[fidx1], outset_uv[fidx2], fac1);
2888
2889                                                 /* if the bucket_clip_edges values Z values was kept we could avoid this
2890                                                  * Inset needs to be added so occlusion tests wont hit adjacent faces */
2891                                                 interp_v3_v3v3(edge_verts_inset_clip[0], insetCos[fidx1], insetCos[fidx2], fac1);
2892                                                 interp_v3_v3v3(edge_verts_inset_clip[1], insetCos[fidx1], insetCos[fidx2], fac2);
2893
2894
2895                                                 if (pixel_bounds_uv(seam_subsection, &bounds_px, ibuf->x, ibuf->y)) {
2896                                                         /* bounds between the seam rect and the uvspace bucket pixels */
2897
2898                                                         has_isect = 0;
2899                                                         for (y = bounds_px.ymin; y < bounds_px.ymax; y++) {
2900                                                                 // uv[1] = (((float)y) + 0.5f) / (float)ibuf->y;
2901                                                                 /* use offset uvs instead */
2902                                                                 uv[1] = (float)y / ibuf_yf;
2903
2904                                                                 has_x_isect = 0;
2905                                                                 for (x = bounds_px.xmin; x < bounds_px.xmax; x++) {
2906                                                                         //uv[0] = (((float)x) + 0.5f) / (float)ibuf->x;
2907                                                                         /* use offset uvs instead */
2908                                                                         uv[0] = (float)x / ibuf_xf;
2909
2910                                                                         /* test we're inside uvspace bucket and triangle bounds */
2911                                                                         if (isect_point_quad_v2(uv, UNPACK4(seam_subsection))) {
2912                                                                                 float fac;
2913
2914                                                                                 /* We need to find the closest point along the face edge,
2915                                                                                  * getting the screen_px_from_*** wont work because our
2916                                                                                  * actual location is not relevant, since we are outside
2917                                                                                  * the face, Use VecLerpf to find our location on the side
2918                                                                                  * of the face's UV */
2919 #if 0
2920                                                                                 if (is_ortho) screen_px_from_ortho(ps, uv, v1co, v2co, v3co, uv1co, uv2co, uv3co, pixelScreenCo);
2921                                                                                 else          screen_px_from_persp(ps, uv, v1co, v2co, v3co, uv1co, uv2co, uv3co, pixelScreenCo);
2922 #endif
2923
2924                                                                                 /* Since this is a seam we need to work out where on
2925                                                                                  * the line this pixel is */
2926                                                                                 //fac = line_point_factor_v2(uv, uv_seam_quad[0], uv_seam_quad[1]);
2927                                                                                 fac = resolve_quad_u_v2(uv, UNPACK4(seam_subsection));
2928                                                                                 interp_v3_v3v3(pixelScreenCo, edge_verts_inset_clip[0], edge_verts_inset_clip[1], fac);
2929
2930                                                                                 if (!is_ortho) {
2931                                                                                         pixelScreenCo[3] = 1.0f;
2932                                                                                         /* cast because of const */
2933                                                                                         mul_m4_v4((float(*)[4])ps->projectMat, pixelScreenCo);
2934                                                                                         pixelScreenCo[0] = (float)(ps->winx * 0.5f) + (ps->winx * 0.5f) * pixelScreenCo[0] / pixelScreenCo[3];
2935                                                                                         pixelScreenCo[1] = (float)(ps->winy * 0.5f) + (ps->winy * 0.5f) * pixelScreenCo[1] / pixelScreenCo[3];
2936                                                                                         /* Use the depth for bucket point occlusion */
2937                                                                                         pixelScreenCo[2] = pixelScreenCo[2] / pixelScreenCo[3];
2938                                                                                 }
2939
2940                                                                                 if ((ps->do_occlude == false) ||
2941                                                                                     !project_bucket_point_occluded(ps, bucketFaceNodes, tri_index, pixelScreenCo))
2942                                                                                 {
2943                                                                                         /* Only bother calculating the weights if we intersect */
2944                                                                                         if (ps->do_mask_normal || ps->poly_to_loop_uv_clone) {
2945                                                                                                 const float uv_fac = fac1 + (fac * (fac2 - fac1));
2946 #if 0
2947                                                                                                 /* get the UV on the line since we want to copy the
2948                                                                                                  * pixels from there for bleeding */
2949                                                                                                 float uv_close[2];
2950                                                                                                 interp_v2_v2v2(uv_close, lt_uv_pxoffset[fidx1], lt_uv_pxoffset[fidx2], uv_fac);
2951                                                                                                 barycentric_weights_v2(lt_uv_pxoffset[0], lt_uv_pxoffset[1], lt_uv_pxoffset[2], uv_close, w);
2952 #else
2953
2954                                                                                                 /* Cheat, we know where we are along the edge
2955                                                                                                  * so work out the weights from that */
2956                                                                                                 w[0] = w[1] = w[2] = 0.0;
2957                                                                                                 w[fidx1] = 1.0f - uv_fac;
2958                                                                                                 w[fidx2] = uv_fac;
2959 #endif
2960                                                                                         }
2961
2962                                                                                         /* a pity we need to get the worldspace
2963                                                                                          * pixel location here */
2964                                                                                         if (do_clip || do_3d_mapping) {
2965                                                                                                 interp_v3_v3v3v3(wco, vCo[0], vCo[1], vCo[2], w);
2966
2967                                                                                                 if (do_clip && ED_view3d_clipping_test(ps->rv3d, wco, true)) {
2968                                                                                                         /* Watch out that no code below
2969                                                                                                          * this needs to run */
2970                                                                                                         continue;
2971                    &nb