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