Welcome to mirror list, hosted at ThFree Co, Russian Federation.

paint_stroke.c « sculpt_paint « editors « blender « source - git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 87f964a8928655adcf1a32e9bde9d03c5ed5bea3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
/*
 * ***** BEGIN GPL LICENSE BLOCK *****
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software  Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * The Original Code is Copyright (C) 2009 by Nicholas Bishop
 * All rights reserved.
 *
 * The Original Code is: all of this file.
 *
 * Contributor(s): Jason Wilkins, Tom Musgrove.
 *
 * ***** END GPL LICENSE BLOCK *****
 *
 */

/** \file blender/editors/sculpt_paint/paint_stroke.c
 *  \ingroup edsculpt
 */

#include "MEM_guardedalloc.h"

#include "BLI_math.h"
#include "BLI_utildefines.h"

#include "DNA_object_types.h"
#include "DNA_scene_types.h"
#include "DNA_brush_types.h"
#include "DNA_meshdata_types.h"

#include "RNA_access.h"

#include "BKE_context.h"
#include "BKE_paint.h"
#include "BKE_brush.h"

#include "WM_api.h"
#include "WM_types.h"

#include "BIF_gl.h"
#include "BIF_glutil.h"

#include "ED_screen.h"
#include "ED_view3d.h"

#include "paint_intern.h"
/* still needed for sculpt_stroke_get_location, should be
   removed eventually (TODO) */
#include "sculpt_intern.h" // XXX, for expedience in getting this working, refactor later (or this just shows that this needs unification)

#include "BKE_DerivedMesh.h"

#include <float.h>
#include <math.h>

typedef struct PaintStroke {
	void *mode_data;
	void *smooth_stroke_cursor;
	wmTimer *timer;

	/* Cached values */
	ViewContext vc;
	bglMats mats;
	Brush *brush;

	float last_mouse_position[2];

	/* Set whether any stroke step has yet occurred
	   e.g. in sculpt mode, stroke doesn't start until cursor
	   passes over the mesh */
	int stroke_started;
	/* event that started stroke, for modal() return */
	int event_type;

	/* event that started stroke, for modal() return */
	int event_type;

	StrokeGetLocation get_location;
	StrokeTestStart test_start;
	StrokeUpdateStep update_step;
	StrokeDone done;
} PaintStroke;

/*** Cursor ***/
static void paint_draw_smooth_stroke(bContext *C, int x, int y, void *customdata) 
{
	Brush *brush = paint_brush(paint_get_active(CTX_data_scene(C)));
	PaintStroke *stroke = customdata;

	glColor4ubv(paint_get_active(CTX_data_scene(C))->paint_cursor_col);
	glEnable(GL_LINE_SMOOTH);
	glEnable(GL_BLEND);

	if(stroke && brush && (brush->flag & BRUSH_SMOOTH_STROKE)) {
		ARegion *ar = CTX_wm_region(C);
		sdrawline(x, y, (int)stroke->last_mouse_position[0] - ar->winrct.xmin,
			  (int)stroke->last_mouse_position[1] - ar->winrct.ymin);
	}

	glDisable(GL_BLEND);
	glDisable(GL_LINE_SMOOTH);
}

#if 0

// grid texture for testing

#define GRID_WIDTH   8
#define GRID_LENGTH  8

#define W (0xFFFFFFFF)
#define G (0x00888888)
#define E (0xE1E1E1E1)
#define C (0xC3C3C3C3)
#define O (0xB4B4B4B4)
#define Q (0xA9A9A9A9)

static unsigned grid_texture0[256] =
{
   W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,
   W,G,G,G,G,G,G,G,G,G,G,G,G,G,G,W,
   W,G,G,G,G,G,G,G,G,G,G,G,G,G,G,W,
   W,G,G,G,G,G,G,G,G,G,G,G,G,G,G,W,
   W,G,G,G,G,G,G,G,G,G,G,G,G,G,G,W,
   W,G,G,G,G,G,G,G,G,G,G,G,G,G,G,W,
   W,G,G,G,G,G,G,G,G,G,G,G,G,G,G,W,
   W,G,G,G,G,G,G,G,G,G,G,G,G,G,G,W,
   W,G,G,G,G,G,G,G,G,G,G,G,G,G,G,W,
   W,G,G,G,G,G,G,G,G,G,G,G,G,G,G,W,
   W,G,G,G,G,G,G,G,G,G,G,G,G,G,G,W,
   W,G,G,G,G,G,G,G,G,G,G,G,G,G,G,W,
   W,G,G,G,G,G,G,G,G,G,G,G,G,G,G,W,
   W,G,G,G,G,G,G,G,G,G,G,G,G,G,G,W,
   W,G,G,G,G,G,G,G,G,G,G,G,G,G,G,W,
   W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,
};

static unsigned grid_texture1[64] =
{
   C,C,C,C,C,C,C,C,
   C,G,G,G,G,G,G,C,
   C,G,G,G,G,G,G,C,
   C,G,G,G,G,G,G,C,
   C,G,G,G,G,G,G,C,
   C,G,G,G,G,G,G,C,
   C,G,G,G,G,G,G,C,
   C,C,C,C,C,C,C,C,
};

static unsigned grid_texture2[16] =
{
   O,O,O,O,
   O,G,G,O,
   O,G,G,O,
   O,O,O,O,
};

static unsigned grid_texture3[4] =
{
   Q,Q,
   Q,Q,
};

static unsigned grid_texture4[1] =
{
   Q,
};

#undef W
#undef G
#undef E
#undef C
#undef O
#undef Q

static void load_grid()
{
	static GLuint overlay_texture;

	if (!overlay_texture) {
		//GLfloat largest_supported_anisotropy;

		glGenTextures(1, &overlay_texture);
		glBindTexture(GL_TEXTURE_2D, overlay_texture);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 16, 16, 0, GL_RGBA, GL_UNSIGNED_BYTE, grid_texture0);
		glTexImage2D(GL_TEXTURE_2D, 1, GL_RGB,  8,  8, 0, GL_RGBA, GL_UNSIGNED_BYTE, grid_texture1);
		glTexImage2D(GL_TEXTURE_2D, 2, GL_RGB,  4,  4, 0, GL_RGBA, GL_UNSIGNED_BYTE, grid_texture2);
		glTexImage2D(GL_TEXTURE_2D, 3, GL_RGB,  2,  2, 0, GL_RGBA, GL_UNSIGNED_BYTE, grid_texture3);
		glTexImage2D(GL_TEXTURE_2D, 4, GL_RGB,  1,  1, 0, GL_RGBA, GL_UNSIGNED_BYTE, grid_texture4);
		glEnable(GL_TEXTURE_2D);
		glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR);

		//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
		//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);

		//glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &largest_supported_anisotropy);
		//glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, largest_supported_anisotropy);
	}
}

#endif

typedef struct Snapshot {
	float size[3];
	float ofs[3];
	float rot;
	int brush_size;
	int winx;
	int winy;
	int brush_map_mode;
	int curve_changed_timestamp;
} Snapshot;

static int same_snap(Snapshot* snap, Brush* brush, ARegion *ar)
{
	MTex* mtex = &brush->mtex;

	return 
		(mtex->tex &&
		    mtex->ofs[0] == snap->ofs[0] &&
		    mtex->ofs[1] == snap->ofs[1] &&
		    mtex->ofs[2] == snap->ofs[2] &&
		    mtex->size[0] == snap->size[0] &&
		    mtex->size[1] == snap->size[1] &&
		    mtex->size[2] == snap->size[2] &&
		    (ELEM(mtex->brush_map_mode, MTEX_MAP_MODE_WRAP, MTEX_MAP_MODE_FIXED) || mtex->rot == snap->rot)) && // rotation does not cause fixed texture to be regenerated
		((ELEM(mtex->brush_map_mode, MTEX_MAP_MODE_WRAP, MTEX_MAP_MODE_FIXED) && brush_size(brush) <= snap->brush_size) || (brush_size(brush) == snap->brush_size)) && // make brush smaller shouldn't cause a resample
		(mtex->brush_map_mode == snap->brush_map_mode ||
		   (ELEM(mtex->brush_map_mode, MTEX_MAP_MODE_WRAP, MTEX_MAP_MODE_FIXED) && ELEM(snap->brush_map_mode, MTEX_MAP_MODE_WRAP, MTEX_MAP_MODE_FIXED))) && // texture doesn't have to be redone if switching from fixed to wrapped or visa versa
		ar->winx == snap->winx &&
		ar->winy == snap->winy;
}

static void make_snap(Snapshot* snap, Brush* brush, ARegion *ar)
{
	if (brush->mtex.tex) {
		snap->brush_map_mode = brush->mtex.brush_map_mode;
		copy_v3_v3(snap->ofs, brush->mtex.ofs);
		copy_v3_v3(snap->size, brush->mtex.size);
		snap->rot = brush->mtex.rot;
	}
	else {
		snap->brush_map_mode = -1;
		snap->ofs[0]= snap->ofs[0]= snap->ofs[0]= -1;
		snap->size[0]= snap->size[0]= snap->size[0]= -1;
		snap->rot = -1;
	}

	snap->brush_size = brush_size(brush);
	snap->winx = ar->winx;
	snap->winy = ar->winy;
}

static int paint_load_overlay_tex(Sculpt *sd, Brush* br, ViewContext* vc)
{
	static GLuint overlay_texture = 0;
	static int init = 0;
	static int tex_changed_timestamp = -1;
	static int curve_changed_timestamp = -1;
	static Snapshot snap;
	static int old_size = -1;

	GLubyte* buffer = NULL;

	int size;
	int j;
	int refresh;

#ifndef _OPENMP
	(void)sd; /* quied unused warning */
#endif
	
	if (br->mtex.brush_map_mode == MTEX_MAP_MODE_TILED && !br->mtex.tex) return 0;

	refresh = 
		!overlay_texture ||
		(br->mtex.tex && 
		    (!br->mtex.tex->preview ||
		      br->mtex.tex->preview->changed_timestamp[0] != tex_changed_timestamp)) ||
		!br->curve ||
		br->curve->changed_timestamp != curve_changed_timestamp ||
		!same_snap(&snap, br, ar);

	if (refresh) {
		if (br->mtex.tex && br->mtex.tex->preview)
			tex_changed_timestamp = br->mtex.tex->preview->changed_timestamp[0];

		if (br->curve)
			curve_changed_timestamp = br->curve->changed_timestamp;

		make_snap(&snap, br, ar);

		if (ELEM(br->mtex.brush_map_mode, MTEX_MAP_MODE_WRAP, MTEX_MAP_MODE_FIXED)) {
			int s = brush_size(br);
			int r = 1;

			for (s >>= 1; s > 0; s >>= 1)
				r++;

			size = (1<<r);

			if (size < 256)
				size = 256;

			if (size < old_size)
				size = old_size;
		}
		else
			size = 512;

		if (old_size != size) {
			if (overlay_texture) {
				glDeleteTextures(1, &overlay_texture);
				overlay_texture = 0;
			}

			init = 0;

			old_size = size;
		}

		buffer = MEM_mallocN(sizeof(GLubyte)*size*size, "paint_load_overlay_tex");

		#pragma omp parallel for schedule(static) if (sd->flags & SCULPT_USE_OPENMP)
		for (j= 0; j < size; j++) {
			int i;
			float y;
			float len;

			for (i= 0; i < size; i++) {

				// largely duplicated from tex_strength

				const float rotation = -br->mtex.rot;
				float diameter = brush_size(br);
				int index = j*size + i;
				float x;
				float avg;

				x = (float)i/size;
				y = (float)j/size;

				x -= 0.5f;
				y -= 0.5f;

				if (br->mtex.brush_map_mode == MTEX_MAP_MODE_TILED) {
					x *= ar->winx / diameter;
					y *= ar->winy / diameter;
				}
				else {
					x *= 2;
					y *= 2;
				}

				len = sqrtf(x*x + y*y);

				if ((br->mtex.brush_map_mode == MTEX_MAP_MODE_TILED) || len <= 1) {
					/* it is probably worth optimizing for those cases where 
					   the texture is not rotated by skipping the calls to
					   atan2, sqrtf, sin, and cos. */
					if ((br->mtex.brush_map_mode == MTEX_MAP_MODE_TILED) &&
						 br->mtex.tex &&
						 (rotation > 0.001f || rotation < -0.001f))
					{
						const float angle= atan2(y, x) + rotation;

						x = len * cosf(angle);
						y = len * sinf(angle);
					}

					x *= br->mtex.size[0];
					y *= br->mtex.size[1];

					x += br->mtex.ofs[0];
					y += br->mtex.ofs[1];

					avg = br->mtex.tex ? paint_get_tex_pixel(br, x, y) : 1;

					avg += br->texture_sample_bias;

					if (ELEM(br->mtex.brush_map_mode, MTEX_MAP_MODE_WRAP, MTEX_MAP_MODE_FIXED))
						avg *= brush_curve_strength(br, len, 1); /* Falloff curve */

					buffer[index] = 255 - (GLubyte)(255*avg);
				}
				else {
					buffer[index] = 0;
				}
			}
		}

		if (!overlay_texture)
			glGenTextures(1, &overlay_texture);
	}
	else {
		size= old_size;
	}

	glBindTexture(GL_TEXTURE_2D, overlay_texture);

	if (refresh) {
		if (!init) {
			glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, size, size, 0, GL_ALPHA, GL_UNSIGNED_BYTE, buffer);
			init = 1;
		}
		else {
			glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, size, size, GL_ALPHA, GL_UNSIGNED_BYTE, buffer);
		}

		if (buffer)
			MEM_freeN(buffer);
	}

	glEnable(GL_TEXTURE_2D);

	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	if (ELEM(br->mtex.brush_map_mode, MTEX_MAP_MODE_WRAP, MTEX_MAP_MODE_FIXED)) {
		float clear[4]= {0,0,0,0};
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
		glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, clear);
	}

	return 1;
}

void ED_draw_paint_overlay(const bContext* C, ARegion *ar)
{
	Paint  *paint = paint_get_active(CTX_data_scene(C));
	Brush  *brush = paint_brush(paint);
	Sculpt *sd    = CTX_data_tool_settings(C)->sculpt;

	if (!sd->sculpting &&
		brush &&
		brush->mtex.brush_map_mode == MTEX_MAP_MODE_TILED &&
		brush->flag & BRUSH_TEXTURE_OVERLAY)
	{
		glPushAttrib(
			GL_COLOR_BUFFER_BIT|
			GL_CURRENT_BIT|
			GL_DEPTH_BUFFER_BIT|
			GL_ENABLE_BIT|
			GL_LINE_BIT|
			GL_POLYGON_BIT|
			GL_STENCIL_BUFFER_BIT|
			GL_TRANSFORM_BIT|
			GL_VIEWPORT_BIT|
			GL_TEXTURE_BIT);

		if (paint_load_overlay_tex(sd, brush, ar)) {
			glEnable(GL_BLEND);

			glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
			glDepthMask(GL_FALSE);
			glDepthFunc(GL_ALWAYS);

			glMatrixMode(GL_TEXTURE);
			glPushMatrix();
			glLoadIdentity();

			glColor4f(
				U.sculpt_paint_overlay_col[0],
				U.sculpt_paint_overlay_col[1],
				U.sculpt_paint_overlay_col[2],
				brush->texture_overlay_alpha / 100.0f);

			glBegin(GL_QUADS);
				glTexCoord2f(0.0f, 0.0f);
				glVertex2f(0.0f, 0.0f);

				glTexCoord2f(1.0f, 0.0f);
				glVertex2f(ar->winx, 0.0f);

				glTexCoord2f(1.0f, 1.0f);
				glVertex2f(ar->winx, ar->winy);

				glTexCoord2f(0.0f, 1.0f);
				glVertex2f(0.0f, ar->winy);
			glEnd();

			glPopMatrix();

			glMatrixMode(GL_MODELVIEW);
		}

		glPopAttrib();
	}
}

static int project_brush_radius(RegionView3D* rv3d, float radius, float location[3], bglMats* mats)
{
	float view[3], nonortho[3], ortho[3], offset[3], p1[2], p2[2];

	ED_view3d_global_to_vector(rv3d, location, view);

	// create a vector that is not orthogonal to view

	if (fabsf(view[0]) < 0.1f) {
		nonortho[0] = view[0] + 1.0f;
		nonortho[1] = view[1];
		nonortho[2] = view[2];
	}
	else if (fabsf(view[1]) < 0.1f) {
		nonortho[0] = view[0];
		nonortho[1] = view[1] + 1.0f;
		nonortho[2] = view[2];
	}
	else {
		nonortho[0] = view[0];
		nonortho[1] = view[1];
		nonortho[2] = view[2] + 1.0f;
	}

	// get a vector in the plane of the view
	cross_v3_v3v3(ortho, nonortho, view);
	normalize_v3(ortho);

	// make a point on the surface of the brush tagent to the view
	mul_v3_fl(ortho, radius);
	add_v3_v3v3(offset, location, ortho);

	// project the center of the brush, and the tagent point to the view onto the screen
	projectf(mats, location, p1);
	projectf(mats, offset, p2);

	// the distance between these points is the size of the projected brush in pixels
	return len_v2v2(p1, p2);
}

static int sculpt_get_brush_geometry(
	bContext* C,
	int x,
	int y,
	int* pixel_radius,
	float location[3],
	float modelview[16],
	float projection[16],
	int viewport[4])
{
	struct PaintStroke *stroke;
	float window[2];
	int hit;

	stroke = paint_stroke_new(C, NULL, NULL, NULL, NULL, 0);

	window[0] = x + stroke->vc.ar->winrct.xmin;
	window[1] = y + stroke->vc.ar->winrct.ymin;

	memcpy(modelview, stroke->vc.rv3d->viewmat, sizeof(float[16]));
	memcpy(projection, stroke->vc.rv3d->winmat, sizeof(float[16]));
	memcpy(viewport, stroke->mats.viewport, sizeof(int[4]));

	if (stroke->vc.obact->sculpt &&
		stroke->vc.obact->sculpt->pbvh &&
		sculpt_stroke_get_location(C, stroke, location, window)) 
	{
		*pixel_radius = 
			project_brush_radius(
				stroke->vc.rv3d,
				brush_unprojected_radius(stroke->brush),
				location,
				&stroke->mats);

		if (*pixel_radius == 0)
			*pixel_radius = brush_size(stroke->brush);

		mul_m4_v3(stroke->vc.obact->obmat, location);

		hit = 1;
	}
	else {
		Sculpt* sd    = CTX_data_tool_settings(C)->sculpt;
		Brush*  brush = paint_brush(&sd->paint);

		*pixel_radius = brush_size(brush);
		hit = 0;
	}

	paint_stroke_free(stroke);

	return hit;
}

static void set_brush_dot_location(float *modelview, float location[3], const char symm, const char axis, float angle)
{
	glLoadMatrixf(modelview);

	angle *= (float)(180.0/M_PI);

	switch (axis) {
		case 'X':
			glRotatef(angle, 1.0f, 0.0f, 0.0f);
			break;

		case 'Y':
			glRotatef(angle, 0.0f, 1.0f, 0.0f);
			break;

		case 'Z':
			glRotatef(angle, 0.0f, 0.0f, 1.0f);
			break;
	}

	glTranslatef(
		!(symm & SCULPT_SYMM_X) ? location[0]: -location[0],
		!(symm & SCULPT_SYMM_Y) ? location[1]: -location[1],
		!(symm & SCULPT_SYMM_Z) ? location[2]: -location[2]);
}

static void draw_brush_dot(GLUquadric *sphere, float radius)
{
	gluSphere(sphere, radius, 20, 20);
}

static void draw_radial_symmetry_dot(float *modelview, float location[3], const char symm, int radial_symm[3], const int axis, GLUquadric *sphere, float radius)
{
	int i;

	for(i = 1; i < radial_symm[axis-'X']; ++i) {
		const float angle = 2*M_PI*i/radial_symm[axis-'X'];
		set_brush_dot_location(modelview, location, symm, axis, angle);
		draw_brush_dot(sphere, radius);
	}
}

static void draw_symmetric_brush_dots(Sculpt *sd, float location[3], float col[3], float *modelview, float *projection, int viewport[4], float radius, int draw_first)
{
	int i;
	short symm= sd->flags & 7;

	GLUquadric* sphere;

	sphere = gluNewQuadric();

	glPushAttrib(
		GL_COLOR_BUFFER_BIT|
		GL_CURRENT_BIT|
		GL_DEPTH_BUFFER_BIT|
		GL_ENABLE_BIT|
		GL_LINE_BIT|
		GL_POLYGON_BIT|
		GL_STENCIL_BUFFER_BIT|
		GL_TRANSFORM_BIT|
		GL_VIEWPORT_BIT|
		GL_TEXTURE_BIT);

	glColor4f(col[0], col[1], col[2], 0.5f);

	glEnable(GL_BLEND);

	glViewport(viewport[0], viewport[1], viewport[2], viewport[3]);

	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadMatrixf(projection);

	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();

	glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
	glDepthMask(GL_FALSE);

	glEnable(GL_DEPTH_TEST);

	glEnable(GL_CULL_FACE);

	/* symm is a bit combination of XYZ - 1 is mirror X; 2 is Y; 3 is XY; 4 is Z; 5 is XZ; 6 is YZ; 7 is XYZ */ 
	for(i = 0; i <= symm; ++i) {
		if(i == 0 || (symm & i && (symm != 5 || i != 3) && (symm != 6 || (i != 3 && i != 5)))) {

			if (draw_first) {
				set_brush_dot_location(modelview, location, i, 0, 0);
				draw_brush_dot(sphere, radius);
			}

			draw_radial_symmetry_dot(modelview, location, i, sd->radial_symm, 'X', sphere, radius);
			draw_radial_symmetry_dot(modelview, location, i, sd->radial_symm, 'Y', sphere, radius);
			draw_radial_symmetry_dot(modelview, location, i, sd->radial_symm, 'Z', sphere, radius);
		}
	}

	glPopAttrib();
}

static void draw_fixed_overlay(Sculpt *sd, Brush *brush, ViewContext *vc, rctf* quad, float angle)
{
	glPushAttrib(
		GL_COLOR_BUFFER_BIT|
		GL_DEPTH_BUFFER_BIT|
		GL_ENABLE_BIT|
		GL_TRANSFORM_BIT|
		GL_CURRENT_BIT|
		GL_TEXTURE_BIT);

	if (paint_load_overlay_tex(sd, brush, vc->ar)) {
		glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
		glDepthMask(GL_FALSE);
		glDepthFunc(GL_ALWAYS);

		glEnable(GL_BLEND);

		glMatrixMode(GL_MODELVIEW);
		glPushMatrix();
		glLoadIdentity();

		glMatrixMode(GL_TEXTURE);
		glPushMatrix();
		glLoadIdentity();

		glTranslatef(0.5f, 0.5f, 0.0f);

		glRotatef(angle, 0.0f, 0.0f, 1.0f);

		glTranslatef(-0.5f, -0.5f, 0.0f);

		if (sd->draw_pressure && (brush->flag & BRUSH_SIZE_PRESSURE)) {
			glTranslatef(0.5f, 0.5f, 0.0f);
			glScalef(1.0f/sd->pressure_value, 1.0f/sd->pressure_value, 1);
			glTranslatef(-0.5f, -0.5f, 0.0f);
		}

		glColor4f(
			U.sculpt_paint_overlay_col[0],
			U.sculpt_paint_overlay_col[1],
			U.sculpt_paint_overlay_col[2],
			brush->texture_overlay_alpha / 100.0f);

		glBegin(GL_QUADS);
			glTexCoord2f(0.0f, 0.0f);
			glVertex2f(quad->xmin, quad->ymin);

			glTexCoord2f(1.0f, 0.0f);
			glVertex2f(quad->xmax, quad->ymin);

			glTexCoord2f(1.0f, 1.0f);
			glVertex2f(quad->xmax, quad->ymax);

			glTexCoord2f(0.0f, 1.0f);
			glVertex2f(quad->xmin, quad->ymax);
		glEnd();

		glPopMatrix();

		glMatrixMode(GL_MODELVIEW);
		glPopMatrix();
	}

	glPopAttrib();
}

void ED_draw_on_surface_cursor(float modelview[16], float projection[16], float col[3], float alpha, float size[3], int viewport[4], float location[3], float inner_radius, float outer_radius, int brush_size)
{
	GLUquadric* sphere;

	glPushAttrib(
		GL_COLOR_BUFFER_BIT|
		GL_CURRENT_BIT|
		GL_DEPTH_BUFFER_BIT|
		GL_ENABLE_BIT|
		GL_LINE_BIT|
		GL_POLYGON_BIT|
		GL_STENCIL_BUFFER_BIT|
		GL_TRANSFORM_BIT|
		GL_VIEWPORT_BIT|
		GL_TEXTURE_BIT);

	glColor4f(col[0], col[1], col[2], alpha);

	glEnable(GL_BLEND);

	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();
	glLoadMatrixf(modelview);

	glTranslatef(location[0], location[1], location[2]);

	glScalef(size[0], size[1], size[2]);

	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadMatrixf(projection);

	glViewport(viewport[0], viewport[1], viewport[2], viewport[3]);

	glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
	glDepthMask(GL_FALSE);

	glDisable(GL_CULL_FACE);

	glEnable(GL_DEPTH_TEST);

	glClearStencil(0);
	glClear(GL_STENCIL_BUFFER_BIT);
	glEnable(GL_STENCIL_TEST);

	glStencilFunc(GL_ALWAYS, 3, 0xFF);
	glStencilOp(GL_KEEP, GL_REPLACE, GL_KEEP);

	sphere = gluNewQuadric();

	gluSphere(sphere, outer_radius, 40, 40);

	glStencilFunc(GL_ALWAYS, 1, 0xFF);
	glStencilOp(GL_KEEP, GL_DECR, GL_KEEP);

	if (brush_size >= 8)
		gluSphere(sphere, inner_radius, 40, 40);

	glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);

	glStencilFunc(GL_EQUAL, 1, 0xFF);
	glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);

	gluSphere(sphere, outer_radius, 40, 40);

	glStencilFunc(GL_EQUAL, 3, 0xFF);
	glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);

	gluSphere(sphere, outer_radius, 40, 40);

	gluDeleteQuadric(sphere);

	glPopMatrix();

	glMatrixMode(GL_MODELVIEW);
	glPopMatrix();

	glPopAttrib();
}

static void stencil_brush_on_surface(float modelview[16], float projection[16], float size[3], int viewport[4], float location[3], float outer_radius)
{
	GLUquadric* sphere;

	glPushAttrib(
		GL_COLOR_BUFFER_BIT|
		GL_CURRENT_BIT|
		GL_DEPTH_BUFFER_BIT|
		GL_ENABLE_BIT|
		GL_LINE_BIT|
		GL_POLYGON_BIT|
		GL_STENCIL_BUFFER_BIT|
		GL_TRANSFORM_BIT|
		GL_VIEWPORT_BIT|
		GL_TEXTURE_BIT);

	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();
	glLoadMatrixf(modelview);

	glTranslatef(location[0], location[1], location[2]);

	glScalef(size[0], size[1], size[2]);

	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadMatrixf(projection);

	glViewport(viewport[0], viewport[1], viewport[2], viewport[3]);

	glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
	glDepthMask(GL_FALSE);

	glDisable(GL_CULL_FACE);

	glEnable(GL_DEPTH_TEST);

	glClearStencil(0);
	glClear(GL_STENCIL_BUFFER_BIT);
	glEnable(GL_STENCIL_TEST);

	glStencilFunc(GL_ALWAYS, 3, 0xFF);
	glStencilOp(GL_KEEP, GL_REPLACE, GL_KEEP);

	sphere = gluNewQuadric();

	gluSphere(sphere, outer_radius, 40, 40);

	glStencilFunc(GL_ALWAYS, 1, 0xFF);
	glStencilOp(GL_KEEP, GL_DECR, GL_KEEP);

	gluSphere(sphere, outer_radius, 40, 40);

	glPopMatrix();

	glMatrixMode(GL_MODELVIEW);
	glPopMatrix();

	glPopAttrib();
}

void ED_draw_fixed_overlay_on_surface(float modelview[16], float projection[16], float size[3], int viewport[4], float location[3], float outer_radius, Sculpt *sd, Brush *brush, ViewContext *vc, rctf* quad, float angle)
{
	stencil_brush_on_surface(modelview, projection, size, viewport, location, outer_radius);

	glPushAttrib(GL_STENCIL_BUFFER_BIT);

	glEnable(GL_STENCIL_TEST);
	glStencilFunc(GL_EQUAL, 2, 0xFF);
	glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);

	draw_fixed_overlay(sd, brush, vc, quad, angle);

	glPopAttrib();
}

typedef struct SphereTest {
	float radius_squared;
	float location[3];
	float dist;
} SphereTest;

static void sphere_test_init(float radius_squared, float location[3], SphereTest *test)
{
	test->radius_squared= radius_squared;
	copy_v3_v3(test->location, location);
}

static int sphere_test_fast(SphereTest *test, float co[3])
{
	return len_squared_v3v3(co, test->location) <= test->radius_squared;
}

static void add_norm_if(float view_vec[3], float out[3], float out_flip[3], float fno[3])
{
	if(!view_vec || dot_v3v3(view_vec, fno) > 0) {
		add_v3_v3(out, fno);
	} else {
		add_v3_v3(out_flip, fno); /* out_flip is used when out is {0,0,0} */
	}
}

static void PBVH_area_normal(float out[3], float view_vec[3], float radius, float location[3], PBVH* pbvh, PBVHNode **nodes, int totnode, int use_openmp)
{
	int n;

	float out_flip[3] = {0.0f, 0.0f, 0.0f};

	zero_v3(out);

	#pragma omp parallel for schedule(guided) if (use_openmp)
	for(n=0; n<totnode; n++) {
		PBVHVertexIter vd;
		SphereTest test;
		float private_an[3] = {0.0f, 0.0f, 0.0f};
		float private_out_flip[3] = {0.0f, 0.0f, 0.0f};

		sphere_test_init(radius, location, &test);

		BLI_pbvh_vertex_iter_begin(pbvh, nodes[n], vd, PBVH_ITER_UNIQUE) {
			if(sphere_test_fast(&test, vd.co)) {
				if(vd.no) {
					float fno[3];

					normal_short_to_float_v3(fno, vd.no);
					add_norm_if(view_vec, private_an, private_out_flip, fno);
				}
				else {
					add_norm_if(view_vec, private_an, private_out_flip, vd.fno);
				}
			}
		}
		BLI_pbvh_vertex_iter_end;

		#pragma omp critical
		{
			add_v3_v3(out, private_an);
			add_v3_v3(out_flip, private_out_flip);
		}
	}

	if (is_zero_v3(out))
		copy_v3_v3(out, out_flip);

	normalize_v3(out);
}

static void paint_sculpt_disp_vector(float out[3], int disp_type, float view_vec[3], float radius, float location[3], PBVH *pbvh, PBVHNode **nodes, int totnode, int use_openmp)
{
	switch (disp_type) {
		case SCULPT_DISP_DIR_VIEW:
			if (view_vec)
				copy_v3_v3(out, view_vec);
			else 
				zero_v3(out);

			break;

		case SCULPT_DISP_DIR_X:
			out[1] = 0.0;
			out[2] = 0.0;
			out[0] = 1.0;
			break;

		case SCULPT_DISP_DIR_Y:
			out[0] = 0.0;
			out[2] = 0.0;
			out[1] = 1.0;
			break;

		case SCULPT_DISP_DIR_Z:
			out[0] = 0.0;
			out[1] = 0.0;
			out[2] = 1.0;
			break;

		case SCULPT_DISP_DIR_AREA:
			PBVH_area_normal(out, view_vec, radius, location, pbvh, nodes, totnode, use_openmp);
			break;

		default:
			break;
	}
}

static void calc_brush_local_mat(float out[4][4], const Brush *brush, float up_vec[3], float location[3], float disp_vec[3])
{
	float mat[4][4];
	float scale[4][4];
	float tmat[4][4];

	// first row, x axis is perpendicular to both the up vector and the displacement vector
	cross_v3_v3v3(mat[0], up_vec, disp_vec);
	mat[0][3] = 0;

	// second row, y axis is perpendicular to the x axis and displacement vector
	cross_v3_v3v3(mat[1], disp_vec, mat[0]);
	mat[1][3] = 0;

	// third row, z axis is simply the displacement vector
	copy_v3_v3(mat[2], disp_vec);
	mat[2][3] = 0;

	// fourth row, the origin of the coordinate system is the location of the brush
	copy_v3_v3(mat[3], location);
	mat[3][3] = 1;

	// normalize the coordinate system so that points inside the brush are within a unit sphere
	normalize_m4(mat);
	scale_m4_fl(scale, brush_unprojected_radius(brush));
	mul_m4_m4m4(tmat, scale, mat);

	// the inverse of the matrix describing the coordinate system of the
	// brush is a matrix that will transform a point into 'local brush space'
	invert_m4_m4(out, tmat);
}

static void draw_wrapped_overlay(float modelview[16], float projection[16], float size[3], int viewport[4], float location[3], float unprojected_radius, Sculpt *sd, Brush *brush, ViewContext *vc, float angle, float up_vec[3])
{
	glPushAttrib(
		GL_COLOR_BUFFER_BIT|
		GL_CURRENT_BIT|
		GL_DEPTH_BUFFER_BIT|
		GL_ENABLE_BIT|
		GL_LINE_BIT|
		GL_POLYGON_BIT|
		GL_STENCIL_BUFFER_BIT|
		GL_TRANSFORM_BIT|
		GL_VIEWPORT_BIT|
		GL_TEXTURE_BIT);

	if (paint_load_overlay_tex(sd, brush, vc->ar)) {
		glMatrixMode(GL_MODELVIEW);
		glPushMatrix();
		glLoadMatrixf(modelview);

		glMatrixMode(GL_PROJECTION);
		glPushMatrix();
		glLoadMatrixf(projection);

		glMatrixMode(GL_TEXTURE);
		glPushMatrix();
		glLoadIdentity();
		glTranslatef(0.5f, 0.5f, 0.5f);
		glScalef(0.5f, 0.5f, 0.5f);

		//glTranslatef(ob->orig[0], ob->orig[1], ob->orig[2]);

		glScalef(size[0], size[1], size[2]);

		glRotatef(angle, 0, 0, 1);

		{
			float disp_vec[3];
			float view_vec[3];
			float brush_local_mat[4][4];

			PBVHNode **nodes;
			int totnode;

			viewvector(vc->rv3d, vc->rv3d->twmat[3], view_vec);

			BLI_pbvh_gather_nodes_in_sphere(
				vc->obact->sculpt->pbvh,
				location,
				brush_unprojected_radius(brush),
				&nodes,
				&totnode);

			paint_sculpt_disp_vector(
				disp_vec, 
				brush->sculpt_plane, 
				view_vec, 
				brush_unprojected_radius(brush), 
				location, 
				vc->obact->sculpt->pbvh, 
				nodes, 
				totnode, 
				sd->flags & SCULPT_USE_OPENMP);

			if (nodes)
				MEM_freeN(nodes);

			calc_brush_local_mat(
				brush_local_mat,
				brush,
				up_vec,
				location,
				disp_vec);

			glMultMatrixf(brush_local_mat);
		}

		{
			float plane_x[4]= {1,0,0,0};
			float plane_y[4]= {0,1,0,0};
			float plane_z[4]= {0,0,1,0};
			float plane_w[4]= {0,0,0,1};
			glTexGenf(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
			glTexGenf(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
			glTexGenf(GL_R, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
			glTexGenf(GL_Q, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
			glTexGenfv(GL_S, GL_OBJECT_PLANE, plane_x);
			glTexGenfv(GL_T, GL_OBJECT_PLANE, plane_y);
			glTexGenfv(GL_R, GL_OBJECT_PLANE, plane_z);
			glTexGenfv(GL_Q, GL_OBJECT_PLANE, plane_w);
			glEnable(GL_TEXTURE_GEN_S);
			glEnable(GL_TEXTURE_GEN_T);
			glEnable(GL_TEXTURE_GEN_R);
			glEnable(GL_TEXTURE_GEN_Q);
		}

		glViewport(viewport[0], viewport[1], viewport[2], viewport[3]);

		glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
		glDepthMask(GL_FALSE);

		glColor4f(
			U.sculpt_paint_overlay_col[0],
			U.sculpt_paint_overlay_col[1],
			U.sculpt_paint_overlay_col[2],
			brush->texture_overlay_alpha / 100.0f);

		glEnable(GL_BLEND);

		glEnable(GL_CULL_FACE);

		glDepthFunc(GL_LEQUAL);
		glEnable(GL_DEPTH_TEST);

		glPolygonOffset(-1, 1);
		glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
		glEnable(GL_POLYGON_OFFSET_FILL);

		BLI_pbvh_draw_nodes_in_sphere(vc->obact->sculpt->pbvh, location, unprojected_radius);

		glPopMatrix();

		glMatrixMode(GL_PROJECTION);
		glPopMatrix();

		glMatrixMode(GL_MODELVIEW);
		glPopMatrix();
	}

	glPopAttrib();
}

void ED_draw_wrapped_overlay_on_surface(float modelview[16], float projection[16], float size[3], int viewport[4], float location[3], float unprojected_radius, Sculpt *sd, Brush *brush, ViewContext *vc, float angle, float up_vec[3])
{
	stencil_brush_on_surface(modelview, projection, size, viewport, location, unprojected_radius);

	glPushAttrib(GL_STENCIL_BUFFER_BIT);

	glEnable(GL_STENCIL_TEST);
	glStencilFunc(GL_EQUAL, 2, 0xFF);
	glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);

	draw_wrapped_overlay(modelview, projection, size, viewport, location,  unprojected_radius, sd, brush, vc, angle, up_vec);

	glPopAttrib();
}

static void update_rake_delta(float out[3], float location[3], int x, int y, ViewContext *vc, float mat[4][4])
{
	static float old_location[3], old_delta[3];

	float delta[3], imat[4][4];

	/* compute 3d coordinate at same z from original location + mouse */
	initgrabz(vc->rv3d, old_location[0], old_location[1], old_location[2]);
	window_to_3d_delta(vc->ar, delta, x, y);

	/* compute delta to move verts by */
	sub_v3_v3v3(out, delta, old_delta);
	invert_m4_m4(imat, mat);
	mul_mat3_m4_v3(imat, out);

	copy_v3_v3(old_delta, delta);

	if (len_v3v3(old_location, location) > 1000)
		copy_v3_v3(old_location, location);
}

// XXX paint cursor now does a lot of the same work that is needed during a sculpt stroke
// problem: all this stuff was not intended to be used at this point, so things feel a
// bit hacked.  I've put lots of stuff in Brush that probably better goes in Paint
// Functions should be refactored so that they can be used between sculpt.c and
// paint_stroke.c clearly and optimally and the lines of communication between the
// two modules should be more clearly defined.
static void paint_draw_cursor(bContext *C, int x, int y, void *UNUSED(unused))
{
	Paint *paint = paint_get_active(CTX_data_scene(C));
	Brush *brush = paint_brush(paint);

	ViewContext vc;

	/* sd->last_angle, sd->last_y, sd->last_x, and set_brush_size need to be
       updated even if we are not drawing the cursor, so we cannot return
	   until they are updated. */

	/* can't use stroke vc here because this will be called during
	   mouse over too, not just during a stroke */	
	view3d_set_viewcontext(C, &vc);

	/* TODO: as sculpt and other paint modes are unified, this
	   special mode of drawing will go away */
	if (vc.obact->sculpt) {
		Sculpt *sd = CTX_data_tool_settings(C)->sculpt;

		int pixel_radius, viewport[4];
		float location[3], modelview[16], projection[16];

		int hit;

		int flip;
		int sign;

		float* col;
		float  alpha;

		const float root_alpha = brush_alpha(brush);
		float visual_strength = root_alpha*root_alpha;

		const float min_alpha = sd->sculpting ? 0.10f : 0.20f;
		const float max_alpha = sd->sculpting ? 0.40f : 0.80f;

		float angle;

		rctf quad;

		float rake_delta[3];

		/* XXX: This is here so that rake takes into
		   account the brush movements before the stroke
		   starts.  Is there a cleaner way? */
		{
			const float u = 0.5f;
			const float v = 1 - u;
			const float r = 20;

			const float dx = sd->last_x - x;
			const float dy = sd->last_y - y;

			if (dx*dx + dy*dy >= r*r) {
				sd->last_angle = atan2(dx, dy);

				sd->last_x = u*sd->last_x + v*x;
				sd->last_y = u*sd->last_y + v*y;
			}
		}

		/* can leave now if brush size is not locked and
		   drawing brush is not enabled */
		if(!brush_use_locked_size(brush) && !(paint->flags & PAINT_SHOW_BRUSH)) 
			return;

		hit = sculpt_get_brush_geometry(C, x, y, &pixel_radius, location, modelview, projection, viewport);

		if (brush_use_locked_size(brush))
			brush_set_size(brush, pixel_radius);

		/* XXX: need to determine if there is a condition that allows exiting
		   from this point */

		/* check if brush is subtracting, use different color then */
		/* XXX: no way currently to know state of pen flip or
		   invert key modifier without starting a stroke */
		flip = brush->flag & BRUSH_INVERTED ? -1 : 1;

		sign = flip * ((brush->flag & BRUSH_DIR_IN)? -1 : 1);

		if (sign < 0 &&
            ELEM6(brush->sculpt_tool,
				SCULPT_TOOL_DRAW,
				SCULPT_TOOL_GRAVITY,
				SCULPT_TOOL_INFLATE,
				SCULPT_TOOL_CLAY,
				SCULPT_TOOL_PINCH,
				SCULPT_TOOL_CREASE))
		{
			col = brush->sub_col;
		}
		else {
			col = brush->add_col;
		}

		alpha = (paint->flags & PAINT_SHOW_BRUSH_ON_SURFACE) ? min_alpha + (visual_strength*(max_alpha-min_alpha)) : 0.50f;

		if (sd->draw_anchored) {
			quad.xmin = sd->anchored_initial_mouse[0]-sd->anchored_size - vc.ar->winrct.xmin;
			quad.ymin = sd->anchored_initial_mouse[1]-sd->anchored_size - vc.ar->winrct.ymin;
			quad.xmax = sd->anchored_initial_mouse[0]+sd->anchored_size - vc.ar->winrct.xmin;
			quad.ymax = sd->anchored_initial_mouse[1]+sd->anchored_size - vc.ar->winrct.ymin;
		}
		else {
			const int size= brush_size(brush);
			quad.xmin= (float)x-size;
			quad.ymin= (float)y-size;
			quad.xmax= (float)x+size;
			quad.ymax= (float)y+size;
		}

		if (brush->flag & BRUSH_RAKE) {
			angle= sd->last_angle*(float)(180.0/M_PI);
		}
		else {
			angle= sd->special_rotation*(float)(180.0/M_PI);
		}

		angle -= brush->mtex.rot*(float)(180.0/M_PI);

		update_rake_delta(rake_delta, location, x+vc.ar->winrct.xmin, y+vc.ar->winrct.ymin, &vc, CTX_data_active_object(C)->obmat);

		/* draw overlay */
		if (!sd->sculpting &&
			(!hit || !(paint->flags & PAINT_SHOW_BRUSH_ON_SURFACE)) &&
			brush->flag & BRUSH_TEXTURE_OVERLAY)
		{
			if (!hit || brush->mtex.brush_map_mode == MTEX_MAP_MODE_FIXED) {
				draw_fixed_overlay(sd, brush, &vc, &quad, angle);
			}
			else if (brush->mtex.brush_map_mode == MTEX_MAP_MODE_WRAP) {
					float up_vec[3]= {0,1,0};
					Object *ob= CTX_data_active_object(C);

					// if raking, up is the direction of the mouse (grab delta),
					if (brush->flag & BRUSH_RAKE) {
						negate_v3_v3(up_vec, rake_delta);
						draw_wrapped_overlay(modelview, projection, ob->size, viewport, location, brush_unprojected_radius(brush), sd, brush, &vc, 0, up_vec);
					}
					// otherwise, it is the view up vector
					else {
						mul_mat3_m4_v3(vc.rv3d->viewinv, up_vec);
						draw_wrapped_overlay(modelview, projection, ob->size, viewport, location, brush_unprojected_radius(brush), sd, brush, &vc, angle, up_vec);
					}
			}
		}

		/* only do if brush is over the mesh */
		if (hit) {
			float projected_radius;
			float unprojected_radius;

			if (sd->draw_pressure && (brush->flag & BRUSH_ALPHA_PRESSURE))
				visual_strength *= sd->pressure_value;

			// don't show effect of strength past the soft limit
			if (visual_strength > 1) visual_strength = 1;

			if(sd->draw_anchored) {
				projected_radius = sd->anchored_size;
			}
			else {
				if(brush->flag & BRUSH_ANCHORED)
					projected_radius = 8;
				else
					projected_radius = brush_size(brush);
			}

			unprojected_radius =
				paint_calc_object_space_radius(vc, location, projected_radius);

			if (sd->draw_pressure && (brush->flag & BRUSH_SIZE_PRESSURE))
				unprojected_radius *= sd->pressure_value;

			if (!brush_use_locked_size(brush))
				brush_set_unprojected_radius(brush, unprojected_radius);

			/* can leave now if brush drawing is off */
			if(!(paint->flags & PAINT_SHOW_BRUSH))
				return;

#ifdef WITH_ONSURFACEBRUSH
			if (paint->flags & PAINT_SHOW_BRUSH_ON_SURFACE) {
				const float max_thickness= 0.12;
				const float min_thickness= 0.06;
				const float thickness=     1.0 - min_thickness - visual_strength*max_thickness;
				const float inner_radius=  sd->draw_anchored ? unprojected_radius                  : unprojected_radius*thickness;
				const float outer_radius=  sd->draw_anchored ? 1.0f/thickness * unprojected_radius : unprojected_radius;
				Object *ob= CTX_data_active_object(C);

				float *location0 = sd->draw_anchored ? sd->anchored_location : location;

				if (!sd->sculpting && brush->flag & BRUSH_TEXTURE_OVERLAY) {
					if (brush->mtex.brush_map_mode == MTEX_MAP_MODE_FIXED)
						ED_draw_fixed_overlay_on_surface(modelview, projection, ob->size, viewport, location0, outer_radius, sd, brush, &vc, &quad, angle);
					else if (brush->mtex.brush_map_mode == MTEX_MAP_MODE_WRAP) {
						float up_vec[3]= {0,1,0};

						// if raking, up is the direction of the mouse (grab delta),
						if (brush->flag & BRUSH_RAKE) {
							negate_v3_v3(up_vec, rake_delta);
							ED_draw_wrapped_overlay_on_surface(modelview, projection, ob->size, viewport, location0, outer_radius, sd, brush, &vc, 0, up_vec);
						}
						// otherwise, it is the view up vector
						else {
							mul_mat3_m4_v3(vc.rv3d->viewinv, up_vec);
							ED_draw_wrapped_overlay_on_surface(modelview, projection, ob->size, viewport, location0, outer_radius, sd, brush, &vc, angle, up_vec);
						}
					}
				}

				ED_draw_on_surface_cursor(modelview, projection, col, alpha, ob->size, viewport, location0, inner_radius, outer_radius, brush_size(brush));

				{
					float scale = 1.0f/(20.0f*(brush_size(brush)/100.0f));
					draw_symmetric_brush_dots(sd, sd->draw_anchored ? sd->anchored_location : location0, col, modelview, projection, viewport,scale*inner_radius, brush_size(brush) >= 8);
				}
			}
#endif
		}

#ifdef WITH_ONSURFACEBRUSH
		if (!hit || !(paint->flags & PAINT_SHOW_BRUSH_ON_SURFACE)) {
#endif
			glPushAttrib(
				GL_COLOR_BUFFER_BIT|
				GL_CURRENT_BIT|
				GL_DEPTH_BUFFER_BIT|
				GL_ENABLE_BIT|
				GL_LINE_BIT|
				GL_POLYGON_BIT|
				GL_STENCIL_BUFFER_BIT|
				GL_TRANSFORM_BIT|
				GL_VIEWPORT_BIT|
				GL_TEXTURE_BIT);

			glColor4f(col[0], col[1], col[2], alpha);

			glEnable(GL_BLEND);

			glEnable(GL_LINE_SMOOTH);

			if (sd->draw_anchored) {
				glTranslatef(sd->anchored_initial_mouse[0] - vc.ar->winrct.xmin, sd->anchored_initial_mouse[1] - vc.ar->winrct.ymin, 0.0f);
				glutil_draw_lined_arc(0.0f, (float)(M_PI*2.0), sd->anchored_size, 40);
				glTranslatef(-sd->anchored_initial_mouse[0] + vc.ar->winrct.xmin, -sd->anchored_initial_mouse[1] + vc.ar->winrct.xmin, 0.0f);
			}
			else {
				glTranslatef((float)x, (float)y, 0.0f);
				glutil_draw_lined_arc(0.0f, (float)(M_PI*2.0), brush_size(brush), 40);
				glTranslatef(-(float)x, -(float)y, 0.0f);
			}

			glPopAttrib();
#ifdef WITH_ONSURFACEBRUSH
		}
#endif
	}
	else {
		if(!(paint->flags & PAINT_SHOW_BRUSH))
			return;

		glColor4ubv(paint_get_active(CTX_data_scene(C))->paint_cursor_col);
		glEnable(GL_LINE_SMOOTH);
		glEnable(GL_BLEND);

		glTranslatef((float)x, (float)y, 0.0f);
		glutil_draw_lined_arc(0.0, M_PI*2.0, brush_size(brush), 40); // XXX: make sure this the right size to use in non-sculpt modes
		glTranslatef((float)-x, (float)-y, 0.0f);

		glDisable(GL_BLEND);
		glDisable(GL_LINE_SMOOTH);
	}
}

/* Put the location of the next stroke dot into the stroke RNA and apply it to the mesh */
static void paint_brush_stroke_add_step(bContext *C, wmOperator *op, wmEvent *event, float mouse_in[2])
{
	Paint *paint = paint_get_active(CTX_data_scene(C)); // XXX
	Brush *brush = paint_brush(paint); // XXX

	float mouse[3];

	PointerRNA itemptr;

	float location[3];

	float pressure;
	int   pen_flip;

	ViewContext vc; // XXX

	PaintStroke *stroke = op->customdata;

	view3d_set_viewcontext(C, &vc); // XXX

	/* Tablet */
	if(event->custom == EVT_DATA_TABLET) {
		wmTabletData *wmtab= event->customdata;

		pressure = (wmtab->Active != EVT_TABLET_NONE) ? wmtab->Pressure : 1;
		pen_flip = (wmtab->Active == EVT_TABLET_ERASER);
	}
	else {
		pressure = 1;
		pen_flip = 0;
	}

	// XXX: temporary check for sculpt mode until things are more unified
	if (vc.obact->sculpt) {
		float delta[3];

		brush_jitter_pos(brush, mouse_in, mouse);

		// XXX: meh, this is round about because brush_jitter_pos isn't written in the best way to be reused here
		if (brush->flag & BRUSH_JITTER_PRESSURE) {
			sub_v3_v3v3(delta, mouse, mouse_in);
			mul_v3_fl(delta, pressure);
			add_v3_v3v3(mouse, mouse_in, delta);
		}
	}
	else
		copy_v3_v3(mouse, mouse_in);

	/* XXX: can remove the if statement once all modes have this */
	if(stroke->get_location)
		stroke->get_location(C, stroke, location, mouse);
	else
		zero_v3(location);

	/* Add to stroke */
	RNA_collection_add(op->ptr, "stroke", &itemptr);

	RNA_float_set_array(&itemptr, "location",     location);
	RNA_float_set_array(&itemptr, "mouse",        mouse);
	RNA_boolean_set    (&itemptr, "pen_flip",     pen_flip);
	RNA_float_set      (&itemptr, "pressure", pressure);

	stroke->last_mouse_position[0] = mouse[0];
	stroke->last_mouse_position[1] = mouse[1];

	stroke->update_step(C, stroke, &itemptr);
}

/* Returns zero if no sculpt changes should be made, non-zero otherwise */
static int paint_smooth_stroke(PaintStroke *stroke, float output[2], wmEvent *event)
{
	output[0] = event->x; 
	output[1] = event->y;

	if ((stroke->brush->flag & BRUSH_SMOOTH_STROKE) &&  
	    !ELEM4(stroke->brush->sculpt_tool, SCULPT_TOOL_GRAB, SCULPT_TOOL_THUMB, SCULPT_TOOL_ROTATE, SCULPT_TOOL_SNAKE_HOOK) &&
	    !(stroke->brush->flag & BRUSH_ANCHORED) &&
	    !(stroke->brush->flag & BRUSH_RESTORE_MESH))
	{
		float u = stroke->brush->smooth_stroke_factor, v = 1.0f - u;
		float dx = stroke->last_mouse_position[0] - event->x, dy = stroke->last_mouse_position[1] - event->y;

		/* If the mouse is moving within the radius of the last move,
		   don't update the mouse position. This allows sharp turns. */
		if(dx*dx + dy*dy < stroke->brush->smooth_stroke_radius * stroke->brush->smooth_stroke_radius)
			return 0;

		output[0] = event->x * v + stroke->last_mouse_position[0] * u;
		output[1] = event->y * v + stroke->last_mouse_position[1] * u;
	}

	return 1;
}

/* For brushes with stroke spacing enabled, moves mouse in steps
   towards the final mouse location. */
static int paint_space_stroke(bContext *C, wmOperator *op, wmEvent *event, const float final_mouse[2])
{
	PaintStroke *stroke = op->customdata;
	int cnt = 0;

	if(paint_space_stroke_enabled(stroke->brush)) {
		float vec[2];
		float length, scale;
		float start_mouse[2];

		copy_v2_v2(start_mouse, stroke->last_mouse_position);
		sub_v2_v2v2(vec, final_mouse, start_mouse);

		length= len_v2(vec);

		if(length > FLT_EPSILON) {
			float pressure = 1;
			float dvec[2];
			float mouse[2];

			pressure = brush_use_size_pressure(stroke->brush) ? event_tablet_data(event, NULL) : 1.0;

			scale = (brush_size(stroke->brush)*pressure*stroke->brush->spacing/50.0f) / length;

			// XXX: this code checks for very small numbers, which could lead to 
			// a large number of iterations.  perhaps this code should just
			// bail out or break if numbers are too small.  Investigate this.

			if (scale < FLT_EPSILON) // make sure scale is big enough have an effect when added
				scale= FLT_EPSILON;

			if (stroke->brush->flag & BRUSH_ADAPTIVE_SPACE) {
				float t= 0;

				for(;;) {
					float f;
					float d;

					f= stroke->brush->adaptive_space_factor;
					CLAMP(f, 0.1f, 1); // make sure that adaptive strength never sets spacing to zero

					d= f*scale;
					CLAMP(d, FLT_EPSILON, scale); // d has to be big enough to increment t

					t += d;

					if (t > 1) break;

					mul_v2_v2fl(dvec, vec, t);
					add_v2_v2v2(mouse, start_mouse, dvec);

					paint_brush_stroke_add_step(C, op, event, mouse);

					cnt++;
				}
			}
			else {
				int i, steps;

				copy_v2_v2(mouse, start_mouse);
				mul_v2_fl(vec, scale);

				steps = (int)(1.0f / scale);

				for(i = 0; i < steps; ++i, ++cnt) {
					add_v2_v2(mouse, vec);
					paint_brush_stroke_add_step(C, op, event, mouse);
				}
			}
		}
	}

	return cnt;
}

/**** Public API ****/

PaintStroke *paint_stroke_new(bContext *C,
				  StrokeGetLocation get_location,
				  StrokeTestStart test_start,
				  StrokeUpdateStep update_step,
                  StrokeDone done, int event_type)
{
	PaintStroke *stroke = MEM_callocN(sizeof(PaintStroke), "PaintStroke");

	stroke->brush = paint_brush(paint_get_active(CTX_data_scene(C)));
	view3d_set_viewcontext(C, &stroke->vc);
	view3d_get_transformation(stroke->vc.ar, stroke->vc.rv3d, stroke->vc.obact, &stroke->mats);

	stroke->get_location = get_location;
	stroke->test_start = test_start;
	stroke->update_step = update_step;
	stroke->done = done;
	stroke->event_type= event_type;	/* for modal, return event */

	return stroke;
}

void paint_stroke_free(PaintStroke *stroke)
{
	MEM_freeN(stroke);
}

/* Returns zero if the stroke dots should not be spaced, non-zero otherwise */
int paint_space_stroke_enabled(Brush *br)
{
	return (br->flag & BRUSH_SPACE) &&
	       !(br->flag & BRUSH_ANCHORED) &&
	       !ELEM4(br->sculpt_tool, SCULPT_TOOL_GRAB, SCULPT_TOOL_THUMB, SCULPT_TOOL_ROTATE, SCULPT_TOOL_SNAKE_HOOK);
}

int paint_stroke_modal(bContext *C, wmOperator *op, wmEvent *event)
{
	PaintStroke *stroke = op->customdata;
	float mouse[2];
	int first= 0;

	if(!stroke->stroke_started) {
		stroke->last_mouse_position[0] = event->x;
		stroke->last_mouse_position[1] = event->y;
		stroke->stroke_started = stroke->test_start(C, op, event);

		if(stroke->stroke_started) {
			stroke->smooth_stroke_cursor =
				WM_paint_cursor_activate(CTX_wm_manager(C), paint_poll, paint_draw_smooth_stroke, stroke);

			if(stroke->brush->flag & BRUSH_AIRBRUSH)
				stroke->timer = WM_event_add_timer(CTX_wm_manager(C), CTX_wm_window(C), TIMER, stroke->brush->rate);
		}

		first= 1;
		//ED_region_tag_redraw(ar);
	}

	if(event->type == stroke->event_type && event->val == KM_RELEASE) {
		/* exit stroke, free data */
		if(stroke->smooth_stroke_cursor)
			WM_paint_cursor_end(CTX_wm_manager(C), stroke->smooth_stroke_cursor);

		if(stroke->timer)
			WM_event_remove_timer(CTX_wm_manager(C), CTX_wm_window(C), stroke->timer);

		stroke->done(C, stroke);
		MEM_freeN(stroke);
		return OPERATOR_FINISHED;
	}
	else if(first || ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE) || (event->type == TIMER && (event->customdata == stroke->timer))) {
		if(stroke->stroke_started) {
			if(paint_smooth_stroke(stroke, mouse, event)) {
				if(paint_space_stroke_enabled(stroke->brush)) {
					if(!paint_space_stroke(C, op, event, mouse)) {
						//ED_region_tag_redraw(ar);
					}
				}
				else {
					paint_brush_stroke_add_step(C, op, event, mouse);
				}
			}
			else {
				;//ED_region_tag_redraw(ar);
			}
		}
	}

	/* we want the stroke to have the first daub at the start location instead of waiting till we have moved the space distance */
	if(first &&
	   stroke->stroke_started &&
	   paint_space_stroke_enabled(stroke->brush) &&
	   !(stroke->brush->flag & BRUSH_ANCHORED) &&
	   !(stroke->brush->flag & BRUSH_SMOOTH_STROKE))
	{
		paint_brush_stroke_add_step(C, op, event, mouse);
	}
	
	return OPERATOR_RUNNING_MODAL;
}

int paint_stroke_exec(bContext *C, wmOperator *op)
{
	PaintStroke *stroke = op->customdata;

	/* only when executed for the first time */
	if(stroke->stroke_started == 0) {
		/* XXX stroke->last_mouse_position is unset, this may cause problems */
		stroke->test_start(C, op, NULL);
		stroke->stroke_started= 1;
	}

	RNA_BEGIN(op->ptr, itemptr, "stroke") {
		stroke->update_step(C, stroke, &itemptr);
	}
	RNA_END;

	stroke->done(C, stroke);

	MEM_freeN(stroke);
	op->customdata = NULL;

	return OPERATOR_FINISHED;
}

ViewContext *paint_stroke_view_context(PaintStroke *stroke)
{
	return &stroke->vc;
}

void *paint_stroke_mode_data(struct PaintStroke *stroke)
{
	return stroke->mode_data;
}

void paint_stroke_set_mode_data(PaintStroke *stroke, void *mode_data)
{
	stroke->mode_data = mode_data;
}

int paint_poll(bContext *C)
{
	Paint *p = paint_get_active(CTX_data_scene(C));
	Object *ob = CTX_data_active_object(C);

	return p && ob && paint_brush(p) &&
		CTX_wm_area(C)->spacetype == SPACE_VIEW3D &&
		CTX_wm_region(C)->regiontype == RGN_TYPE_WINDOW;
}

void paint_cursor_start(bContext *C, int (*poll)(bContext *C))
{
	Paint *p = paint_get_active(CTX_data_scene(C));

	if(p && !p->paint_cursor)
		p->paint_cursor = WM_paint_cursor_activate(CTX_wm_manager(C), poll, paint_draw_cursor, NULL);
}