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