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

view.c « src « blender « source - git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 24ee2f964796abc5207c46317956ead908753793 (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
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
/**
 * $Id$
 *
 * ***** BEGIN GPL/BL DUAL 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. The Blender
 * Foundation also sells licenses for use in proprietary software under
 * the Blender License.  See http://www.blender.org/BL/ for information
 * about this.
 *
 * 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
 * All rights reserved.
 *
 * Trackball math (in calctrackballvec())  Copyright (C) Silicon Graphics, Inc.
 *
 * The Original Code is: all of this file.
 *
 * Contributor(s): none yet.
 *
 * ***** END GPL/BL DUAL LICENSE BLOCK *****
 */

#include <math.h>
#include <string.h>

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#ifdef WIN32
#include <io.h>
#else
#include <unistd.h>
#endif   

#include "MEM_guardedalloc.h"

#include "BLI_blenlib.h"
#include "BLI_arithb.h"

#include "DNA_action_types.h"
#include "DNA_armature_types.h"
#include "DNA_camera_types.h"
#include "DNA_lamp_types.h"
#include "DNA_object_types.h"
#include "DNA_screen_types.h"
#include "DNA_scene_types.h"
#include "DNA_space_types.h"
#include "DNA_userdef_types.h"
#include "DNA_view3d_types.h"

#include "BKE_action.h"
#include "BKE_anim.h"
#include "BKE_global.h"
#include "BKE_main.h"
#include "BKE_object.h"
#include "BKE_sculpt.h"
#include "BKE_utildefines.h"

#include "BIF_transform.h"
#include "BIF_editparticle.h"
#include "BIF_gl.h"
#include "BIF_previewrender.h"
#include "BIF_mywindow.h"
#include "BIF_retopo.h"
#include "BIF_space.h"
#include "BIF_screen.h"
#include "BIF_toolbox.h"

#include "BSE_view.h"
#include "BSE_edit.h"		/* For countall */
#include "BSE_drawview.h"	/* For inner_play_anim_loop */

#include "BDR_drawobject.h"	/* For draw_object */
#include "BDR_editface.h"	/* For minmax_tface */
#include "BDR_sculptmode.h"

#include "mydevice.h"
#include "blendef.h"
#include "transform.h"

#include "PIL_time.h" /* smoothview */
#include <float.h>

#define TRACKBALLSIZE  (1.1)
#define BL_NEAR_CLIP 0.001


/* local prototypes ----------*/
void setcameratoview3d(void); /* windows.c & toets.c */

void persp_general(int a)
{
	/* for all window types, not 3D */
	
	if(a== 0) {
		glPushMatrix();
		glMatrixMode(GL_PROJECTION);
		glPushMatrix();
		glMatrixMode(GL_MODELVIEW);

		myortho2(-0.375, ((float)(curarea->winx))-0.375, -0.375, ((float)(curarea->winy))-0.375);
		glLoadIdentity();
	}
	else if(a== 1) {
		glMatrixMode(GL_PROJECTION);
		glPopMatrix();
		glMatrixMode(GL_MODELVIEW);
		glPopMatrix();
	}
}

void persp(int a)
{
	/* only 3D windows */

	if(curarea->spacetype!=SPACE_VIEW3D) persp_general(a);
	else if(a == PERSP_STORE) {		// only store
		glMatrixMode(GL_PROJECTION);
		mygetmatrix(G.vd->winmat1);	
		glMatrixMode(GL_MODELVIEW);
		mygetmatrix(G.vd->viewmat1); 
	}
	else if(a== PERSP_WIN) {		// only set
		myortho2(-0.375, (float)(curarea->winx)-0.375, -0.375, (float)(curarea->winy)-0.375);
		glLoadIdentity();
	}
	else if(a== PERSP_VIEW) {
		glMatrixMode(GL_PROJECTION);
		myloadmatrix(G.vd->winmat1); // put back
		Mat4CpyMat4(curarea->winmat, G.vd->winmat1); // to be sure? 
		glMatrixMode(GL_MODELVIEW); 
		myloadmatrix(G.vd->viewmat); // put back
		
	}
}


void initgrabz(float x, float y, float z)
{
	if(G.vd==NULL) return;
	G.vd->zfac= G.vd->persmat[0][3]*x+ G.vd->persmat[1][3]*y+ G.vd->persmat[2][3]*z+ G.vd->persmat[3][3];

	/* if x,y,z is exactly the viewport offset, zfac is 0 and we don't want that 
	 * (accounting for near zero values)
	 * */
	if (G.vd->zfac < 1.e-6f && G.vd->zfac > -1.e-6f) G.vd->zfac = 1.0f;
	
	/* Negative zfac means x, y, z was behind the camera (in perspective).
	 * This gives flipped directions, so revert back to ok default case.
	 */
	if (G.vd->zfac < 0.0f) G.vd->zfac = 1.0f;
}

void window_to_3d(float *vec, short mx, short my)
{
	/* always call initgrabz */
	float dx, dy;
	
	dx= 2.0f*mx*G.vd->zfac/curarea->winx;
	dy= 2.0f*my*G.vd->zfac/curarea->winy;
	
	vec[0]= (G.vd->persinv[0][0]*dx + G.vd->persinv[1][0]*dy);
	vec[1]= (G.vd->persinv[0][1]*dx + G.vd->persinv[1][1]*dy);
	vec[2]= (G.vd->persinv[0][2]*dx + G.vd->persinv[1][2]*dy);
}

void project_short(float *vec, short *adr)	/* clips */
{
	float fx, fy, vec4[4];

	adr[0]= IS_CLIPPED;
	
	if(G.vd->flag & V3D_CLIPPING) {
		if(view3d_test_clipping(G.vd, vec))
			return;
	}

	VECCOPY(vec4, vec);
	vec4[3]= 1.0;
	Mat4MulVec4fl(G.vd->persmat, vec4);
	
	if( vec4[3]>BL_NEAR_CLIP ) {	/* 0.001 is the NEAR clipping cutoff for picking */
		fx= (curarea->winx/2)*(1 + vec4[0]/vec4[3]);
		
		if( fx>0 && fx<curarea->winx) {
		
			fy= (curarea->winy/2)*(1 + vec4[1]/vec4[3]);
			
			if(fy>0.0 && fy< (float)curarea->winy) {
				adr[0]= floor(fx); 
				adr[1]= floor(fy);
			}
		}
	}
}

void project_int(float *vec, int *adr)
{
	float fx, fy, vec4[4];

	adr[0]= 2140000000.0f;
	VECCOPY(vec4, vec);
	vec4[3]= 1.0;
	
	Mat4MulVec4fl(G.vd->persmat, vec4);

	if( vec4[3]>BL_NEAR_CLIP ) {	/* 0.001 is the NEAR clipping cutoff for picking */
		fx= (curarea->winx/2)*(1 + vec4[0]/vec4[3]);
		
		if( fx>-2140000000.0f && fx<2140000000.0f) {
			fy= (curarea->winy/2)*(1 + vec4[1]/vec4[3]);
			
			if(fy>-2140000000.0f && fy<2140000000.0f) {
				adr[0]= floor(fx); 
				adr[1]= floor(fy);
			}
		}
	}
}

void project_short_noclip(float *vec, short *adr)
{
	float fx, fy, vec4[4];

	adr[0]= IS_CLIPPED;
	VECCOPY(vec4, vec);
	vec4[3]= 1.0;
	
	Mat4MulVec4fl(G.vd->persmat, vec4);

	if( vec4[3]>BL_NEAR_CLIP ) {	/* 0.001 is the NEAR clipping cutoff for picking */
		fx= (curarea->winx/2)*(1 + vec4[0]/vec4[3]);
		
		if( fx>-32700 && fx<32700) {
		
			fy= (curarea->winy/2)*(1 + vec4[1]/vec4[3]);
			
			if(fy>-32700.0 && fy<32700.0) {
				adr[0]= floor(fx); 
				adr[1]= floor(fy);
			}
		}
	}
}

void project_float(float *vec, float *adr)
{
	float vec4[4];
	
	adr[0]= IS_CLIPPED;
	VECCOPY(vec4, vec);
	vec4[3]= 1.0;
	
	Mat4MulVec4fl(G.vd->persmat, vec4);

	if( vec4[3]>BL_NEAR_CLIP ) {
		adr[0]= (curarea->winx/2.0)+(curarea->winx/2.0)*vec4[0]/vec4[3];	
		adr[1]= (curarea->winy/2.0)+(curarea->winy/2.0)*vec4[1]/vec4[3];
	}
}

void view3d_get_object_project_mat(ScrArea *area, Object *ob, float pmat[4][4], float vmat[4][4])
{
	if (area->spacetype!=SPACE_VIEW3D || !area->spacedata.first) {
		Mat4One(pmat);
		Mat4One(vmat);
	} else {
		View3D *vd = area->spacedata.first;

		Mat4MulMat4(vmat, ob->obmat, vd->viewmat);
		Mat4MulMat4(pmat, vmat, vd->winmat1);
		Mat4CpyMat4(vmat, ob->obmat);
	}
}

/* projectmat brings it to window coords, wmat to rotated world space */
void view3d_project_short_clip(ScrArea *area, float *vec, short *adr, float projmat[4][4], float wmat[4][4])
{
	View3D *v3d= area->spacedata.first;
	float fx, fy, vec4[4];

	adr[0]= IS_CLIPPED;
	
	/* clipplanes in eye space */
	if(v3d->flag & V3D_CLIPPING) {
		VECCOPY(vec4, vec);
		Mat4MulVecfl(wmat, vec4);
		if(view3d_test_clipping(v3d, vec4))
			return;
	}
	
	VECCOPY(vec4, vec);
	vec4[3]= 1.0;
	
	Mat4MulVec4fl(projmat, vec4);
	
	/* clipplanes in window space */
	if( vec4[3]>BL_NEAR_CLIP ) {	/* 0.001 is the NEAR clipping cutoff for picking */
		fx= (area->winx/2)*(1 + vec4[0]/vec4[3]);
		
		if( fx>0 && fx<area->winx) {
		
			fy= (area->winy/2)*(1 + vec4[1]/vec4[3]);
			
			if(fy>0.0 && fy< (float)area->winy) {
				adr[0]= floor(fx); 
				adr[1]= floor(fy);
			}
		}
	}
}

void view3d_project_short_noclip(ScrArea *area, float *vec, short *adr, float mat[4][4])
{
	float fx, fy, vec4[4];

	adr[0]= IS_CLIPPED;
	
	VECCOPY(vec4, vec);
	vec4[3]= 1.0;
	
	Mat4MulVec4fl(mat, vec4);

	if( vec4[3]>BL_NEAR_CLIP ) {	/* 0.001 is the NEAR clipping cutoff for picking */
		fx= (area->winx/2)*(1 + vec4[0]/vec4[3]);
		
		if( fx>-32700 && fx<32700) {
		
			fy= (area->winy/2)*(1 + vec4[1]/vec4[3]);
			
			if(fy>-32700.0 && fy<32700.0) {
				adr[0]= floor(fx); 
				adr[1]= floor(fy);
			}
		}
	}
}

void view3d_project_float(ScrArea *area, float *vec, float *adr, float mat[4][4])
{
	float vec4[4];
	
	adr[0]= IS_CLIPPED;
	VECCOPY(vec4, vec);
	vec4[3]= 1.0;
	
	Mat4MulVec4fl(mat, vec4);

	if( vec4[3]>FLT_EPSILON ) {
		adr[0] = (area->winx/2.0)+(area->winx/2.0)*vec4[0]/vec4[3];	
		adr[1] = (area->winy/2.0)+(area->winy/2.0)*vec4[1]/vec4[3];
	} else {
		adr[0] = adr[1] = 0.0;
	}
}

int boundbox_clip(float obmat[][4], BoundBox *bb)
{
	/* return 1: draw */
	
	float mat[4][4];
	float vec[4], min, max;
	int a, flag= -1, fl;
	
	if(bb==NULL) return 1;
	if(bb->flag & OB_BB_DISABLED) return 1;
	
	Mat4MulMat4(mat, obmat, G.vd->persmat);

	for(a=0; a<8; a++) {
		VECCOPY(vec, bb->vec[a]);
		vec[3]= 1.0;
		Mat4MulVec4fl(mat, vec);
		max= vec[3];
		min= -vec[3];

		fl= 0;
		if(vec[0] < min) fl+= 1;
		if(vec[0] > max) fl+= 2;
		if(vec[1] < min) fl+= 4;
		if(vec[1] > max) fl+= 8;
		if(vec[2] < min) fl+= 16;
		if(vec[2] > max) fl+= 32;
		
		flag &= fl;
		if(flag==0) return 1;
	}

	return 0;

}

void fdrawline(float x1, float y1, float x2, float y2)
{
	float v[2];

	glBegin(GL_LINE_STRIP);
	v[0] = x1; v[1] = y1;
	glVertex2fv(v);
	v[0] = x2; v[1] = y2;
	glVertex2fv(v);
	glEnd();
}

void fdrawbox(float x1, float y1, float x2, float y2)
{
	float v[2];

	glBegin(GL_LINE_STRIP);

	v[0] = x1; v[1] = y1;
	glVertex2fv(v);
	v[0] = x1; v[1] = y2;
	glVertex2fv(v);
	v[0] = x2; v[1] = y2;
	glVertex2fv(v);
	v[0] = x2; v[1] = y1;
	glVertex2fv(v);
	v[0] = x1; v[1] = y1;
	glVertex2fv(v);

	glEnd();
}

void sdrawline(short x1, short y1, short x2, short y2)
{
	short v[2];

	glBegin(GL_LINE_STRIP);
	v[0] = x1; v[1] = y1;
	glVertex2sv(v);
	v[0] = x2; v[1] = y2;
	glVertex2sv(v);
	glEnd();
}

void sdrawbox(short x1, short y1, short x2, short y2)
{
	short v[2];

	glBegin(GL_LINE_STRIP);

	v[0] = x1; v[1] = y1;
	glVertex2sv(v);
	v[0] = x1; v[1] = y2;
	glVertex2sv(v);
	v[0] = x2; v[1] = y2;
	glVertex2sv(v);
	v[0] = x2; v[1] = y1;
	glVertex2sv(v);
	v[0] = x1; v[1] = y1;
	glVertex2sv(v);

	glEnd();
}

/* the central math in this function was copied from trackball.cpp, sample code from the 
   Developers Toolbox series by SGI. */

/* trackball: better one than a full spherical solution */

void calctrackballvecfirst(rcti *area, short *mval, float *vec)
{
	float x, y, radius, d, z, t;
	
	radius= TRACKBALLSIZE;
	
	/* normalize x and y */
	x= (area->xmax + area->xmin)/2 -mval[0];
	x/= (float)((area->xmax - area->xmin)/2);
	y= (area->ymax + area->ymin)/2 -mval[1];
	y/= (float)((area->ymax - area->ymin)/2);
	
	d = sqrt(x*x + y*y);
	if (d < radius*M_SQRT1_2)  	/* Inside sphere */
		z = sqrt(radius*radius - d*d);
	else
	{ 			/* On hyperbola */
		t = radius / M_SQRT2;
		z = t*t / d;
	}

	vec[0]= x;
	vec[1]= y;
	vec[2]= -z;		/* yah yah! */

	if( fabs(vec[2])>fabs(vec[1]) && fabs(vec[2])>fabs(vec[0]) ) {
		vec[0]= 0.0;
		vec[1]= 0.0;
		if(vec[2]>0.0) vec[2]= 1.0; else vec[2]= -1.0;
	}
	else if( fabs(vec[1])>fabs(vec[0]) && fabs(vec[1])>fabs(vec[2]) ) {
		vec[0]= 0.0;
		vec[2]= 0.0;
		if(vec[1]>0.0) vec[1]= 1.0; else vec[1]= -1.0;
	}
	else  {
		vec[1]= 0.0;
		vec[2]= 0.0;
		if(vec[0]>0.0) vec[0]= 1.0; else vec[0]= -1.0;
	}
}

void calctrackballvec(rcti *area, short *mval, float *vec)
{
	float x, y, radius, d, z, t;
	
	radius= TRACKBALLSIZE;
	
	/* x en y normalizeren */
	x= (area->xmax + area->xmin)/2 -mval[0];
	x/= (float)((area->xmax - area->xmin)/4);
	y= (area->ymax + area->ymin)/2 -mval[1];
	y/= (float)((area->ymax - area->ymin)/2);
	
	d = sqrt(x*x + y*y);
	if (d < radius*M_SQRT1_2)  	/* Inside sphere */
		z = sqrt(radius*radius - d*d);
	else
	{ 			/* On hyperbola */
		t = radius / M_SQRT2;
		z = t*t / d;
	}

	vec[0]= x;
	vec[1]= y;
	vec[2]= -z;		/* yah yah! */

}


// ndof scaling will be moved to user setting.
// In the mean time this is just a place holder.

// Note: scaling in the plugin and ghostwinlay.c
// should be removed. With driver default setting,
// each axis returns approx. +-200 max deflection.

// The values I selected are based on the older
// polling i/f. With event i/f, the sensistivity
// can be increased for improved response from
// small deflections of the device input.


// lukep notes : i disagree on the range.
// the normal 3Dconnection driver give +/-400
// on defaut range in other applications
// and up to +/- 1000 if set to maximum
// because i remove the scaling by delta,
// which was a bad idea as it depend of the system
// speed and os, i changed the scaling values, but 
// those are still not ok


float ndof_axis_scale[6] = {
	+0.01,	// Tx
	+0.01,	// Tz
	+0.01,	// Ty
	+0.0015,	// Rx
	+0.0015,	// Rz
	+0.0015	// Ry
};

// statics for controlling G.vd->dist corrections.
// viewmoveNDOF zeros and adjusts G.vd->ofs.
// viewmove restores based on dz_flag state.

int dz_flag = 0;
float m_dist;

void viewmoveNDOFfly(int mode)
{
    int i;
    float phi;
    float dval[7];
	// static fval[6] for low pass filter; device input vector is dval[6]
	static float fval[6];
    float tvec[3],rvec[3];
    float q1[4];
	float mat[3][3];
	float upvec[3];


    /*----------------------------------------------------
	 * sometimes this routine is called from headerbuttons
     * viewmove needs to refresh the screen
     */
	areawinset(curarea->win);


	// fetch the current state of the ndof device
	getndof(dval);

	if (G.vd->ndoffilter)
		filterNDOFvalues(fval);

//	for(i=0;i<7;i++) printf("%f ",dval[i]);
//		printf("\n");


	// Scale input values

//	if(dval[6] == 0) return; // guard against divide by zero

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

		// user scaling
		dval[i] = dval[i] * ndof_axis_scale[i];

		// non-linear scaling
		if(dval[i]<0.0f)
			dval[i] = -1.0f * dval[i] * dval[i];
		else
			dval[i] = dval[i] * dval[i];
	}


	// low pass filter with zero crossing reset

	for(i=0;i<6;i++) {
		if((dval[i] * fval[i]) >= 0)
			dval[i] = (fval[i] * 15 + dval[i]) / 16;
		else
			fval[i] = 0;
	}


	// force perspective mode. This is a hack and is
	// incomplete. It doesn't actually effect the view
	// until the first draw and doesn't update the menu
	// to reflect persp mode.

	G.vd->persp = 1;


	// Correct the distance jump if G.vd->dist != 0

	// This is due to a side effect of the original
	// mouse view rotation code. The rotation point is
	// set a distance in front of the viewport to
	// make rotating with the mouse look better.
	// The distance effect is written at a low level
	// in the view management instead of the mouse
	// view function. This means that all other view
	// movement devices must subtract this from their
	// view transformations.

	if(G.vd->dist != 0.0) {
		dz_flag = 1;
		m_dist = G.vd->dist;
		upvec[0] = upvec[1] = 0;
		upvec[2] = G.vd->dist;
		Mat3CpyMat4(mat, G.vd->viewinv);
		Mat3MulVecfl(mat, upvec);
		VecSubf(G.vd->ofs, G.vd->ofs, upvec);
		G.vd->dist = 0.0;
	}


	// Apply rotation

	rvec[0] = -dval[3];
	rvec[1] = -dval[4];
	rvec[2] = dval[5];

	// rotate device x and y by view z

	Mat3CpyMat4(mat, G.vd->viewinv);
	mat[2][2] = 0.0f;
	Mat3MulVecfl(mat, rvec);

	// rotate the view

	phi = Normalize(rvec);
	if(phi != 0) {
		VecRotToQuat(rvec,phi,q1);
		QuatMul(G.vd->viewquat, G.vd->viewquat, q1);
	}


	// Apply translation

	tvec[0] = dval[0];
	tvec[1] = dval[1];
	tvec[2] = -dval[2];

	// the next three lines rotate the x and y translation coordinates
	// by the current z axis angle

	Mat3CpyMat4(mat, G.vd->viewinv);
	mat[2][2] = 0.0f;
	Mat3MulVecfl(mat, tvec);

	// translate the view

	VecSubf(G.vd->ofs, G.vd->ofs, tvec);


	/*----------------------------------------------------
     * refresh the screen
     */
    scrarea_do_windraw(curarea);
    screen_swapbuffers();

	// update render preview window

	BIF_view3d_previewrender_signal(curarea, PR_DBASE|PR_DISPRECT);
}

void viewmove(int mode)
{
	Object *ob = OBACT;
	float firstvec[3], newvec[3], dvec[3];
	float reverse, oldquat[4], q1[4], si, phi, dist0;
	float ofs[3], obofs[3]= {0.0f, 0.0f, 0.0f};
	int firsttime=1;
	short mvalball[2], mval[2], mvalo[2], mval_area[2];
	short use_sel = 0;
	short preview3d_event= 1;
	
	// locals for dist correction
	float mat[3][3];
	float upvec[3];

		/* 3D window may not be defined */
	if( !G.vd ) {
		fprintf( stderr, "G.vd == NULL in viewmove()\n" );
		return;
	}
	
		// dist correction from other movement devices
		
	if(dz_flag) {
		dz_flag = 0;
		G.vd->dist = m_dist;
		upvec[0] = upvec[1] = 0;
		upvec[2] = G.vd->dist;
		Mat3CpyMat4(mat, G.vd->viewinv);
		Mat3MulVecfl(mat, upvec);
		VecAddf(G.vd->ofs, G.vd->ofs, upvec);
	}


		
	/* sometimes this routine is called from headerbuttons */

	areawinset(curarea->win);
	
	initgrabz(-G.vd->ofs[0], -G.vd->ofs[1], -G.vd->ofs[2]);
	
	QUATCOPY(oldquat, G.vd->viewquat);
	
	getmouseco_areawin(mval_area);	/* for zoom to mouse loc */
	getmouseco_sc(mvalo);		/* work with screen coordinates because of trackball function */
	mvalball[0]= mvalo[0];			/* needed for turntable to work */
	mvalball[1]= mvalo[1];
	dist0= G.vd->dist;
	
	calctrackballvec(&curarea->winrct, mvalo, firstvec);

	/* cumultime(0); */

	if(!G.obedit && (G.f & G_SCULPTMODE) && ob && G.vd->pivot_last) {
		use_sel= 1;
		VecCopyf(ofs, G.vd->ofs);

		VecCopyf(obofs, sculpt_data()->pivot);
		Mat4MulVecfl(ob->obmat, obofs);
		obofs[0]= -obofs[0];
		obofs[1]= -obofs[1];
		obofs[2]= -obofs[2];
	}
	else if (ob && (U.uiflag & USER_ORBIT_SELECTION)) {
		use_sel = 1;
		
		VECCOPY(ofs, G.vd->ofs);
		
		/* If there's no selection, obofs is unmodified, so <0,0,0> */
		calculateTransformCenter(V3D_CENTROID, obofs);
		VecMulf(obofs, -1.0f);
	}
	else
		ofs[0] = ofs[1] = ofs[2] = 0.0f;

	reverse= 1.0f;
	if (G.vd->persmat[2][1] < 0.0f)
		reverse= -1.0f;

	while(TRUE) {
		getmouseco_sc(mval);
		
		// if playanim = alt+A, screenhandlers are for animated UI, python, etc
		if(mval[0]!=mvalo[0] || mval[1]!=mvalo[1] || (G.f & G_PLAYANIM) || do_screenhandlers(G.curscreen)) {
			
			if(firsttime) {
				
				firsttime= 0;
				/* are we translating, rotating or zooming? */
				if(mode==0) {
					if(G.vd->view!=0) scrarea_queue_headredraw(curarea);	/*for button */
					G.vd->view= 0;
				}
				if(G.vd->persp==2 && mode!=1 && G.vd->camera) {
					G.vd->persp= 1;
					scrarea_do_windraw(curarea);
					scrarea_queue_headredraw(curarea);
				}
			}

			if(mode==0) {	/* view rotate */
				if (U.uiflag & USER_AUTOPERSP) G.vd->persp= 1;

				if (U.flag & USER_TRACKBALL) mvalball[0]= mval[0];
				mvalball[1]= mval[1];
				
				calctrackballvec(&curarea->winrct, mvalball, newvec);
				
				VecSubf(dvec, newvec, firstvec);
				
				si= sqrt(dvec[0]*dvec[0]+ dvec[1]*dvec[1]+ dvec[2]*dvec[2]);
				si/= (2.0*TRACKBALLSIZE);
			
				if (U.flag & USER_TRACKBALL) {
					Crossf(q1+1, firstvec, newvec);
	
					Normalize(q1+1);
	
					/* Allow for rotation beyond the interval
					 * [-pi, pi] */
					while (si > 1.0)
						si -= 2.0;
		
					/* This relation is used instead of
					 * phi = asin(si) so that the angle
					 * of rotation is linearly proportional
					 * to the distance that the mouse is
					 * dragged. */
					phi = si * M_PI / 2.0;
		
					si= sin(phi);
					q1[0]= cos(phi);
					q1[1]*= si;
					q1[2]*= si;
					q1[3]*= si;	
					QuatMul(G.vd->viewquat, q1, oldquat);

					if (use_sel) {
						/* compute the post multiplication quat, to rotate the offset correctly */
						QUATCOPY(q1, oldquat);
						QuatConj(q1);
						QuatMul(q1, q1, G.vd->viewquat);

						QuatConj(q1); /* conj == inv for unit quat */
						VECCOPY(G.vd->ofs, ofs);
						VecSubf(G.vd->ofs, G.vd->ofs, obofs);
						QuatMulVecf(q1, G.vd->ofs);
						VecAddf(G.vd->ofs, G.vd->ofs, obofs);
					}
				} else {
					/* New turntable view code by John Aughey */

					float m[3][3];
					float m_inv[3][3];
					float xvec[3] = {1,0,0};
					/* Sensitivity will control how fast the viewport rotates.  0.0035 was
					   obtained experimentally by looking at viewport rotation sensitivities
					   on other modeling programs. */
					/* Perhaps this should be a configurable user parameter. */
					const float sensitivity = 0.0035;

					/* Get the 3x3 matrix and its inverse from the quaternion */
					QuatToMat3(G.vd->viewquat, m);
					Mat3Inv(m_inv,m);

					/* Determine the direction of the x vector (for rotating up and down) */
					/* This can likely be compuated directly from the quaternion. */
					Mat3MulVecfl(m_inv,xvec);

					/* Perform the up/down rotation */
					phi = sensitivity * -(mval[1] - mvalo[1]);
					si = sin(phi);
					q1[0] = cos(phi);
					q1[1] = si * xvec[0];
					q1[2] = si * xvec[1];
					q1[3] = si * xvec[2];
					QuatMul(G.vd->viewquat, G.vd->viewquat, q1);

					if (use_sel) {
						QuatConj(q1); /* conj == inv for unit quat */
						VecSubf(G.vd->ofs, G.vd->ofs, obofs);
						QuatMulVecf(q1, G.vd->ofs);
						VecAddf(G.vd->ofs, G.vd->ofs, obofs);
					}

					/* Perform the orbital rotation */
					phi = sensitivity * reverse * (mval[0] - mvalo[0]);
					q1[0] = cos(phi);
					q1[1] = q1[2] = 0.0;
					q1[3] = sin(phi);
					QuatMul(G.vd->viewquat, G.vd->viewquat, q1);

					if (use_sel) {
						QuatConj(q1);
						VecSubf(G.vd->ofs, G.vd->ofs, obofs);
						QuatMulVecf(q1, G.vd->ofs);
						VecAddf(G.vd->ofs, G.vd->ofs, obofs);
					}
				}
			}
			else if(mode==1) {	/* translate */
				if(G.vd->persp==2) {
					float max= (float)MAX2(curarea->winx, curarea->winy);

					G.vd->camdx += (mvalo[0]-mval[0])/(max);
					G.vd->camdy += (mvalo[1]-mval[1])/(max);
					CLAMP(G.vd->camdx, -1.0f, 1.0f);
					CLAMP(G.vd->camdy, -1.0f, 1.0f);
					preview3d_event= 0;
				}
				else {
					window_to_3d(dvec, mval[0]-mvalo[0], mval[1]-mvalo[1]);
					VecAddf(G.vd->ofs, G.vd->ofs, dvec);
				}
			}
			else if(mode==2) {
				float zfac=1.0;
				if(U.viewzoom==USER_ZOOM_CONT) {
					// oldstyle zoom
					zfac = 1.0+(float)(mvalo[0]-mval[0]+mvalo[1]-mval[1])/1000.0;
				}
				else if(U.viewzoom==USER_ZOOM_SCALE) {
					int ctr[2], len1, len2;
					// method which zooms based on how far you move the mouse
					
					ctr[0] = (curarea->winrct.xmax + curarea->winrct.xmin)/2;
					ctr[1] = (curarea->winrct.ymax + curarea->winrct.ymin)/2;
					
					len1 = (int)sqrt((ctr[0] - mval[0])*(ctr[0] - mval[0]) + (ctr[1] - mval[1])*(ctr[1] - mval[1])) + 5;
					len2 = (int)sqrt((ctr[0] - mvalo[0])*(ctr[0] - mvalo[0]) + (ctr[1] - mvalo[1])*(ctr[1] - mvalo[1])) + 5;
					
					zfac = dist0 * ((float)len2/len1) / G.vd->dist;
				}
				else {	/* USER_ZOOM_DOLLY */
					float len1 = (curarea->winrct.ymax - mval[1]) + 5;
					float len2 = (curarea->winrct.ymax - mvalo[1]) + 5;
					zfac = dist0 * (2.0*((len2/len1)-1.0) + 1.0) / G.vd->dist;
				}

				if(zfac != 1.0 && zfac*G.vd->dist > 0.001*G.vd->grid && 
					zfac*G.vd->dist < 10.0*G.vd->far)
					view_zoom_mouseloc(zfac, mval_area);
				
				/* these limits are in toets.c too */
				if(G.vd->dist<0.001*G.vd->grid) G.vd->dist= 0.001*G.vd->grid;
				if(G.vd->dist>10.0*G.vd->far) G.vd->dist=10.0*G.vd->far;
				
				mval[1]= mvalo[1]; /* preserve first value */
				mval[0]= mvalo[0];
				
				if(G.vd->persp==0 || G.vd->persp==2) preview3d_event= 0;
			}
			
			mvalo[0]= mval[0];
			mvalo[1]= mval[1];

			if(G.f & G_PLAYANIM) inner_play_anim_loop(0, 0);
			if(G.f & G_SIMULATION) break;

			/* If in retopo paint mode, update lines */
			if(retopo_mesh_paint_check() && G.vd->retopo_view_data) {
				G.vd->retopo_view_data->queue_matrix_update= 1;
				retopo_paint_view_update(G.vd);
			}

			scrarea_do_windraw(curarea);
			screen_swapbuffers();
		}
		else {
			short val;
			unsigned short event;
			/* we need to empty the queue... when you do this very long it overflows */
			while(qtest()) event= extern_qread(&val);
			
			BIF_wait_for_statechange();
		}
		
		/* this in the end, otherwise get_mbut does not work on a PC... */
		if( !(get_mbut() & (L_MOUSE|M_MOUSE))) break;
	}

	if(G.vd->depths) G.vd->depths->damaged= 1;
	retopo_queue_updates(G.vd);
	allqueue(REDRAWVIEW3D, 0);

	if(preview3d_event) 
		BIF_view3d_previewrender_signal(curarea, PR_DBASE|PR_DISPRECT);
	else
		BIF_view3d_previewrender_signal(curarea, PR_PROJECTED);

}
 
void view_zoom_mouseloc(float dfac, short *mouseloc)
{
	if(U.uiflag & USER_ZOOM_TO_MOUSEPOS) {
		short vb[2];
		float dvec[3];
		float tvec[3];
		float tpos[3];
		float new_dist;

		/* find the current window width and height */
		vb[0] = G.vd->area->winx;
		vb[1] = G.vd->area->winy;
		
		tpos[0] = -G.vd->ofs[0];
		tpos[1] = -G.vd->ofs[1];
		tpos[2] = -G.vd->ofs[2];

		/* Project cursor position into 3D space */
		initgrabz(tpos[0], tpos[1], tpos[2]);
		window_to_3d(dvec, mouseloc[0]-vb[0]/2, mouseloc[1]-vb[1]/2);

		/* Calculate view target position for dolly */
		tvec[0] = -(tpos[0] + dvec[0]);
		tvec[1] = -(tpos[1] + dvec[1]);
		tvec[2] = -(tpos[2] + dvec[2]);

		/* Offset to target position and dolly */
		new_dist = G.vd->dist * dfac;
		
		VECCOPY(G.vd->ofs, tvec);
		G.vd->dist = new_dist;
		
		/* Calculate final offset */
		dvec[0] = tvec[0] + dvec[0] * dfac;
		dvec[1] = tvec[1] + dvec[1] * dfac;
		dvec[2] = tvec[2] + dvec[2] * dfac;
		
		VECCOPY(G.vd->ofs, dvec);
	} else {
		G.vd->dist *= dfac;
	}
}

void viewmoveNDOF(int mode)
{
    static double prevTime = 0.0;

    int i;
    float fval[7];
    float dvec[3];
    float sbadjust = 1.0f;
    float len;
    double now, frametime;
	short use_sel = 0;
	Object *ob = OBACT;
    float m[3][3];
    float m_inv[3][3];
    float xvec[3] = {1,0,0};
    float yvec[3] = {0,-1,0};
    float zvec[3] = {0,0,1};
	float phi, si;
    float q1[4];
    float obofs[3];
    float reverse;
    float diff[4];
    float d, curareaX, curareaY;

    /* Sensitivity will control how fast the view rotates.  The value was
     * obtained experimentally by tweaking until the author didn't get dizzy watching.
     * Perhaps this should be a configurable user parameter. 
     */
    float psens = 0.005f * (float) U.ndof_pan;   /* pan sensitivity */
    float rsens = 0.005f * (float) U.ndof_rotate;  /* rotate sensitivity */
    float zsens = 0.3f;   /* zoom sensitivity */

    const float minZoom = -30.0f;
    const float maxZoom = 300.0f;

	//reset view type
	G.vd->view = 0;
//printf("passing here \n");
//
	if (G.obedit==NULL && ob && !(ob->flag & OB_POSEMODE)) {
		use_sel = 1;
	}

    /*----------------------------------------------------
	 * sometimes this routine is called from headerbuttons
     * viewmove needs to refresh the screen
     */
	areawinset(curarea->win);

    /*----------------------------------------------------
     * record how much time has passed. clamp at 10 Hz
     * pretend the previous frame occured at the clamped time 
     */
//    now = PIL_check_seconds_timer();
 //   frametime = (now - prevTime);
 //   if (frametime > 0.1f){        /* if more than 1/10s */
 //       frametime = 1.0f/60.0;      /* clamp at 1/60s so no jumps when starting to move */
//    }
//    prevTime = now;
 //   sbadjust *= 60 * frametime;             /* normalize ndof device adjustments to 100Hz for framerate independence */

    /* fetch the current state of the ndof device */
    getndof(fval);
 //           printf(" motion command %f %f %f %f %f %f %f \n", fval[0], fval[1], fval[2],
 //           							 fval[3], fval[4], fval[5], fval[6]);
			if (G.vd->ndoffilter)
				filterNDOFvalues(fval);
	
	
	// put scaling back here, was previously in ghostwinlay
            fval[0] = fval[0]  * (1.0f/800.0f);
            fval[1] = fval[1]  * (1.0f/800.0f);
            fval[2] = fval[2] * (1.0f/800.0f);
            fval[3] = fval[3]  * 0.00005f;
            fval[4] = fval[4]  * 0.00005f;
            fval[5] = fval[5] * 0.00005f;
            fval[6] = fval[6]  / 1000000.0f;
			
	// scale more if not in perspective mode
			if (G.vd->persp == 0) {
				fval[0] = fval[0] * 0.05f;
				fval[1] = fval[1] * 0.05f;
				fval[2] = fval[2] * 0.05f;
				fval[3] = fval[3] * 0.9f;
				fval[4] = fval[4] * 0.9f;
				fval[5] = fval[5] * 0.9f;
				zsens *= 8;
			}
			
	
    /* set object offset */
	if (ob) {
		obofs[0] = -ob->obmat[3][0];
		obofs[1] = -ob->obmat[3][1];
		obofs[2] = -ob->obmat[3][2];
	}
	else {
		VECCOPY(obofs, G.vd->ofs);
	}

    /* calc an adjustment based on distance from camera */
    if (ob) {
        VecSubf(diff, obofs, G.vd->ofs);
        d = VecLength(diff);
    }
    else {
        d = 1.0f;
    }
    reverse = (G.vd->persmat[2][1] < 0.0f) ? -1.0f : 1.0f;

    /*----------------------------------------------------
     * ndof device pan 
     */
    psens *= 1.0f + d;
    curareaX = sbadjust * psens * fval[0];
    curareaY = sbadjust * psens * fval[1];
    dvec[0] = curareaX * G.vd->persinv[0][0] + curareaY * G.vd->persinv[1][0];
    dvec[1] = curareaX * G.vd->persinv[0][1] + curareaY * G.vd->persinv[1][1];
    dvec[2] = curareaX * G.vd->persinv[0][2] + curareaY * G.vd->persinv[1][2];
    VecAddf(G.vd->ofs, G.vd->ofs, dvec);

    /*----------------------------------------------------
     * ndof device dolly 
     */
    len = zsens * sbadjust * fval[2];

    if (G.vd->persp==2) {
        if(G.vd->persp==2) {
            G.vd->camzoom+= 10.0f * -len;
        }
        if (G.vd->camzoom < minZoom) G.vd->camzoom = minZoom;
        else if (G.vd->camzoom > maxZoom) G.vd->camzoom = maxZoom;
    }
    else if ((G.vd->dist> 0.001*G.vd->grid) && (G.vd->dist<10.0*G.vd->far)) {
        G.vd->dist*=(1.0 + len);
    }


    /*----------------------------------------------------
     * ndof device turntable
     * derived from the turntable code in viewmove
     */

    /* Get the 3x3 matrix and its inverse from the quaternion */
    QuatToMat3(G.vd->viewquat, m);
    Mat3Inv(m_inv,m);

    /* Determine the direction of the x vector (for rotating up and down) */
    /* This can likely be compuated directly from the quaternion. */
    Mat3MulVecfl(m_inv,xvec);
    Mat3MulVecfl(m_inv,yvec);
    Mat3MulVecfl(m_inv,zvec);

    /* Perform the up/down rotation */
    phi = sbadjust * rsens * /*0.5f * */ fval[3]; /* spin vertically half as fast as horizontally */
    si = sin(phi);
    q1[0] = cos(phi);
    q1[1] = si * xvec[0];
    q1[2] = si * xvec[1];
    q1[3] = si * xvec[2];
    QuatMul(G.vd->viewquat, G.vd->viewquat, q1);

    if (use_sel) {
        QuatConj(q1); /* conj == inv for unit quat */
        VecSubf(G.vd->ofs, G.vd->ofs, obofs);
        QuatMulVecf(q1, G.vd->ofs);
        VecAddf(G.vd->ofs, G.vd->ofs, obofs);
    }

    /* Perform the orbital rotation */
    /* Perform the orbital rotation 
       If the seen Up axis is parallel to the zoom axis, rotation should be
       achieved with a pure Roll motion (no Spin) on the device. When you start 
       to tilt, moving from Top to Side view, Spinning will increasingly become 
       more relevant while the Roll component will decrease. When a full 
       Side view is reached, rotations around the world's Up axis are achieved
       with a pure Spin-only motion.  In other words the control of the spinning
       around the world's Up axis should move from the device's Spin axis to the
       device's Roll axis depending on the orientation of the world's Up axis 
       relative to the screen. */
    //phi = sbadjust * rsens * reverse * fval[4];  /* spin the knob, y axis */
    phi = sbadjust * rsens * (yvec[2] * fval[4] + zvec[2] * fval[5]);
    q1[0] = cos(phi);
    q1[1] = q1[2] = 0.0;
    q1[3] = sin(phi);
    QuatMul(G.vd->viewquat, G.vd->viewquat, q1);

    if (use_sel) {
        QuatConj(q1);
        VecSubf(G.vd->ofs, G.vd->ofs, obofs);
        QuatMulVecf(q1, G.vd->ofs);
        VecAddf(G.vd->ofs, G.vd->ofs, obofs);
    }

    /*----------------------------------------------------
     * refresh the screen
     */
    scrarea_do_windraw(curarea);
    screen_swapbuffers();
}


/* Gets the lens and clipping values from a camera of lamp type object */
void object_view_settings(Object *ob, float *lens, float *clipsta, float *clipend)
{	
	if (!ob) return;
	
	if(ob->type==OB_LAMP ) {
		Lamp *la = ob->data;
		if (lens) {
			float x1, fac;
			fac= cos( M_PI*la->spotsize/360.0);
			x1= saacos(fac);
			*lens= 16.0*fac/sin(x1);
		}
		if (clipsta)	*clipsta= la->clipsta;
		if (clipend)	*clipend= la->clipend;
	}
	else if(ob->type==OB_CAMERA) {
		Camera *cam= ob->data;
		if (lens)		*lens= cam->lens;
		if (clipsta)	*clipsta= cam->clipsta;
		if (clipend)	*clipend= cam->clipend;
	}
}


int get_view3d_viewplane(int winxi, int winyi, rctf *viewplane, float *clipsta, float *clipend, float *pixsize)
{
	Camera *cam=NULL;
	float lens, fac, x1, y1, x2, y2;
	float winx= (float)winxi, winy= (float)winyi;
	int orth= 0;
	
	lens= G.vd->lens;	
	
	*clipsta= G.vd->near;
	*clipend= G.vd->far;

/*	
 * Cant use this since we need the fac and x1 values set
 * if(G.vd->persp==2)
		object_view_settings(G.vd->camera, &lens, &(*clipsta), &(*clipend));*/
	
	if(G.vd->persp==2) {
		if(G.vd->camera) {
			if(G.vd->camera->type==OB_LAMP ) {
				Lamp *la;
				
				la= G.vd->camera->data;
				fac= cos( M_PI*la->spotsize/360.0);
				
				x1= saacos(fac);
				lens= 16.0*fac/sin(x1);
		
				*clipsta= la->clipsta;
				*clipend= la->clipend;
			}
			else if(G.vd->camera->type==OB_CAMERA) {
				cam= G.vd->camera->data;
				lens= cam->lens;
				*clipsta= cam->clipsta;
				*clipend= cam->clipend;
			}
		}
	}
	
	if(G.vd->persp==0) {
		if(winx>winy) x1= -G.vd->dist;
		else x1= -winx*G.vd->dist/winy;
		x2= -x1;

		if(winx>winy) y1= -winy*G.vd->dist/winx;
		else y1= -G.vd->dist;
		y2= -y1;
		
		*clipend *= 0.5;	// otherwise too extreme low zbuffer quality
		*clipsta= - *clipend;
		orth= 1;
	}
	else {
		/* fac for zoom, also used for camdx */
		if(G.vd->persp==2) {
			fac= (1.41421+( (float)G.vd->camzoom )/50.0);
			fac*= fac;
		}
		else fac= 2.0;
		
		/* viewplane size depends... */
		if(cam && cam->type==CAM_ORTHO) {
			/* ortho_scale == 1 means exact 1 to 1 mapping */
			float dfac= 2.0*cam->ortho_scale/fac;
			
			if(winx>winy) x1= -dfac;
			else x1= -winx*dfac/winy;
			x2= -x1;
			
			if(winx>winy) y1= -winy*dfac/winx;
			else y1= -dfac;
			y2= -y1;
			orth= 1;
		}
		else {
			float dfac;
			
			if(winx>winy) dfac= 64.0/(fac*winx*lens);
			else dfac= 64.0/(fac*winy*lens);
			
			x1= - *clipsta * winx*dfac;
			x2= -x1;
			y1= - *clipsta * winy*dfac;
			y2= -y1;
			orth= 0;
		}
		/* cam view offset */
		if(cam) {
			float dx= 0.5*fac*G.vd->camdx*(x2-x1);
			float dy= 0.5*fac*G.vd->camdy*(y2-y1);
			x1+= dx;
			x2+= dx;
			y1+= dy;
			y2+= dy;
		}
	}

	if(pixsize) {
		float viewfac;

		if(orth) {
			viewfac= (winx >= winy)? winx: winy;
			*pixsize= 1.0f/viewfac;
		}
		else {
			viewfac= (((winx >= winy)? winx: winy)*lens)/32.0;
			*pixsize= *clipsta/viewfac;
		}
	}
	
	viewplane->xmin= x1;
	viewplane->ymin= y1;
	viewplane->xmax= x2;
	viewplane->ymax= y2;
	
	return orth;
}

/* important to not set windows active in here, can be renderwin for example */
void setwinmatrixview3d(int winx, int winy, rctf *rect)		/* rect: for picking */
{
	rctf viewplane;
	float clipsta, clipend, x1, y1, x2, y2;
	int orth;
	
	orth= get_view3d_viewplane(winx, winy, &viewplane, &clipsta, &clipend, NULL);
//	printf("%d %d %f %f %f %f %f %f\n", winx, winy, viewplane.xmin, viewplane.ymin, viewplane.xmax, viewplane.ymax, clipsta, clipend);
	x1= viewplane.xmin;
	y1= viewplane.ymin;
	x2= viewplane.xmax;
	y2= viewplane.ymax;
	
	if(rect) {		/* picking */
		rect->xmin/= (float)curarea->winx;
		rect->xmin= x1+rect->xmin*(x2-x1);
		rect->ymin/= (float)curarea->winy;
		rect->ymin= y1+rect->ymin*(y2-y1);
		rect->xmax/= (float)curarea->winx;
		rect->xmax= x1+rect->xmax*(x2-x1);
		rect->ymax/= (float)curarea->winy;
		rect->ymax= y1+rect->ymax*(y2-y1);
		
		if(orth) myortho(rect->xmin, rect->xmax, rect->ymin, rect->ymax, -clipend, clipend);
		else mywindow(rect->xmin, rect->xmax, rect->ymin, rect->ymax, clipsta, clipend);
		
	}
	else {
		if(orth) myortho(x1, x2, y1, y2, clipsta, clipend);
		else mywindow(x1, x2, y1, y2, clipsta, clipend);
	}

	/* not sure what this was for? (ton) */
	glMatrixMode(GL_PROJECTION);
	mygetmatrix(curarea->winmat);
	glMatrixMode(GL_MODELVIEW);
}

void obmat_to_viewmat(Object *ob, short smooth)
{
	float bmat[4][4];
	float tmat[3][3];

	Mat4CpyMat4(bmat, ob->obmat);
	Mat4Ortho(bmat);
	Mat4Invert(G.vd->viewmat, bmat);
	
	/* view quat calculation, needed for add object */
	Mat3CpyMat4(tmat, G.vd->viewmat);
	if (smooth) {
		float new_quat[4];
		if (G.vd->persp==2 && G.vd->camera) {
			/* were from a camera view */
			
			float orig_ofs[3];
			float orig_dist= G.vd->dist;
			float orig_lens= G.vd->lens;
			VECCOPY(orig_ofs, G.vd->ofs);
			
			/* Switch from camera view */
			Mat3ToQuat(tmat, new_quat);
			
			G.vd->persp=1;
			G.vd->dist= 0.0;
			
			view_settings_from_ob(G.vd->camera, G.vd->ofs, NULL, NULL, &G.vd->lens);
			smooth_view(G.vd, orig_ofs, new_quat, &orig_dist, &orig_lens);
			
			G.vd->persp=2; /* just to be polite, not needed */
			
		} else {
			Mat3ToQuat(tmat, new_quat);
			smooth_view(G.vd, NULL, new_quat, NULL, NULL);
		}
	} else {
		Mat3ToQuat(tmat, G.vd->viewquat);
	}
}

/* dont set windows active in in here, is used by renderwin too */
void setviewmatrixview3d()
{
	if(G.vd->persp>=2) {	    /* obs/camera */
		if(G.vd->camera) {
			where_is_object(G.vd->camera);	
			obmat_to_viewmat(G.vd->camera, 0);
		}
		else {
			QuatToMat4(G.vd->viewquat, G.vd->viewmat);
			G.vd->viewmat[3][2]-= G.vd->dist;
		}
	}
	else {
		
		QuatToMat4(G.vd->viewquat, G.vd->viewmat);
		if(G.vd->persp==1) G.vd->viewmat[3][2]-= G.vd->dist;
		if(G.vd->ob_centre) {
			Object *ob= G.vd->ob_centre;
			float vec[3];
			
			VECCOPY(vec, ob->obmat[3]);
			if(ob->type==OB_ARMATURE && G.vd->ob_centre_bone[0]) {
				bPoseChannel *pchan= get_pose_channel(ob->pose, G.vd->ob_centre_bone);
				if(pchan) {
					VECCOPY(vec, pchan->pose_mat[3]);
					Mat4MulVecfl(ob->obmat, vec);
				}
			}
			i_translate(-vec[0], -vec[1], -vec[2], G.vd->viewmat);
		}
		else i_translate(G.vd->ofs[0], G.vd->ofs[1], G.vd->ofs[2], G.vd->viewmat);
	}
}

void setcameratoview3d(void)
{
	Object *ob;
	float dvec[3];

	ob= G.vd->camera;
	dvec[0]= G.vd->dist*G.vd->viewinv[2][0];
	dvec[1]= G.vd->dist*G.vd->viewinv[2][1];
	dvec[2]= G.vd->dist*G.vd->viewinv[2][2];					
	VECCOPY(ob->loc, dvec);
	VecSubf(ob->loc, ob->loc, G.vd->ofs);
	G.vd->viewquat[0]= -G.vd->viewquat[0];
	if (ob->transflag & OB_QUAT) {
		QUATCOPY(ob->quat, G.vd->viewquat);
	} else {
		QuatToEul(G.vd->viewquat, ob->rot);
	}
	G.vd->viewquat[0]= -G.vd->viewquat[0];
}

/* IGLuint-> GLuint*/
/* Warning: be sure to account for a negative return value
 *   This is an error, "Too many objects in select buffer"
 *   and no action should be taken (can crash blender) if this happens
 */
short  view3d_opengl_select(unsigned int *buffer, unsigned int bufsize, short x1, short y1, short x2, short y2)
{
	rctf rect;
	short mval[2], code, hits;

	G.f |= G_PICKSEL;
	
	if(x1==0 && x2==0 && y1==0 && y2==0) {
		getmouseco_areawin(mval);
		rect.xmin= mval[0]-12;	// seems to be default value for bones only now
		rect.xmax= mval[0]+12;
		rect.ymin= mval[1]-12;
		rect.ymax= mval[1]+12;
	}
	else {
		rect.xmin= x1;
		rect.xmax= x2;
		rect.ymin= y1;
		rect.ymax= y2;
	}
	/* get rid of overlay button matrix */
	persp(PERSP_VIEW);
	setwinmatrixview3d(curarea->winx, curarea->winy, &rect);
	Mat4MulMat4(G.vd->persmat, G.vd->viewmat, curarea->winmat);
	
	if(G.vd->drawtype > OB_WIRE) {
		G.vd->zbuf= TRUE;
		glEnable(GL_DEPTH_TEST);
	}

	if(G.vd->flag & V3D_CLIPPING)
		view3d_set_clipping(G.vd);
	
	glSelectBuffer( bufsize, (GLuint *)buffer);
	glRenderMode(GL_SELECT);
	glInitNames();	/* these two calls whatfor? It doesnt work otherwise */
	glPushName(-1);
	code= 1;
	
	if(G.obedit && G.obedit->type==OB_MBALL) {
		draw_object(BASACT, DRAW_PICKING|DRAW_CONSTCOLOR);
	}
	else if ((G.obedit && G.obedit->type==OB_ARMATURE)) {
		draw_object(BASACT, DRAW_PICKING|DRAW_CONSTCOLOR);
	}
	else {
		Base *base;
		
		G.vd->xray= TRUE;	// otherwise it postpones drawing
		for(base= G.scene->base.first; base; base= base->next) {
			if(base->lay & G.vd->lay) {
				
				if (base->object->restrictflag & OB_RESTRICT_SELECT)
					base->selcol= 0;
				else {
					base->selcol= code;
					glLoadName(code);
					draw_object(base, DRAW_PICKING|DRAW_CONSTCOLOR);
					
					/* we draw group-duplicators for selection too */
					if((base->object->transflag & OB_DUPLI) && base->object->dup_group) {
						ListBase *lb;
						DupliObject *dob;
						Base tbase;
						
						tbase.flag= OB_FROMDUPLI;
						lb= object_duplilist(G.scene, base->object);
						
						for(dob= lb->first; dob; dob= dob->next) {
							tbase.object= dob->ob;
							Mat4CpyMat4(dob->ob->obmat, dob->mat);
							
							draw_object(&tbase, DRAW_PICKING|DRAW_CONSTCOLOR);
							
							Mat4CpyMat4(dob->ob->obmat, dob->omat);
						}
						free_object_duplilist(lb);
					}
					code++;
				}				
			}
		}
		G.vd->xray= FALSE;	// restore
	}
	
	glPopName();	/* see above (pushname) */
	hits= glRenderMode(GL_RENDER);

	G.f &= ~G_PICKSEL;
	setwinmatrixview3d(curarea->winx, curarea->winy, NULL);
	Mat4MulMat4(G.vd->persmat, G.vd->viewmat, curarea->winmat);
	
	if(G.vd->drawtype > OB_WIRE) {
		G.vd->zbuf= 0;
		glDisable(GL_DEPTH_TEST);
	}
	persp(PERSP_WIN);
	
	if(G.vd->flag & V3D_CLIPPING)
		view3d_clr_clipping();
	
	if(hits<0) error("Too many objects in select buffer");
	
	return hits;
}

float *give_cursor()
{
	if(G.vd && G.vd->localview) return G.vd->cursor;
	else return G.scene->cursor;
}

unsigned int free_localbit()
{
	unsigned int lay;
	ScrArea *sa;
	bScreen *sc;
	
	lay= 0;
	
	/* sometimes we loose a localview: when an area is closed */
	/* check all areas: which localviews are in use? */
	sc= G.main->screen.first;
	while(sc) {
		sa= sc->areabase.first;
		while(sa) {
			SpaceLink *sl= sa->spacedata.first;
			while(sl) {
				if(sl->spacetype==SPACE_VIEW3D) {
					View3D *v3d= (View3D*) sl;
					lay |= v3d->lay;
				}
				sl= sl->next;
			}
			sa= sa->next;
		}
		sc= sc->id.next;
	}
	
	if( (lay & 0x01000000)==0) return 0x01000000;
	if( (lay & 0x02000000)==0) return 0x02000000;
	if( (lay & 0x04000000)==0) return 0x04000000;
	if( (lay & 0x08000000)==0) return 0x08000000;
	if( (lay & 0x10000000)==0) return 0x10000000;
	if( (lay & 0x20000000)==0) return 0x20000000;
	if( (lay & 0x40000000)==0) return 0x40000000;
	if( (lay & 0x80000000)==0) return 0x80000000;
	
	return 0;
}


void initlocalview()
{
	Base *base;
	float size = 0.0, min[3], max[3], afm[3];
	unsigned int locallay;
	int ok=0;

	if(G.vd->localvd) return;

	INIT_MINMAX(min, max);

	locallay= free_localbit();

	if(locallay==0) {
		error("Sorry,  no more than 8 localviews");
		ok= 0;
	}
	else {
		if(G.obedit) {
			minmax_object(G.obedit, min, max);
			
			ok= 1;
		
			BASACT->lay |= locallay;
			G.obedit->lay= BASACT->lay;
		}
		else {
			base= FIRSTBASE;
			while(base) {
				if TESTBASE(base)  {
					minmax_object(base->object, min, max);
					base->lay |= locallay;
					base->object->lay= base->lay;
					ok= 1;
				}
				base= base->next;
			}
		}
		
		afm[0]= (max[0]-min[0]);
		afm[1]= (max[1]-min[1]);
		afm[2]= (max[2]-min[2]);
		size= 0.7*MAX3(afm[0], afm[1], afm[2]);
		if(size<=0.01) size= 0.01;
	}
	
	if(ok) {
		G.vd->localvd= MEM_mallocN(sizeof(View3D), "localview");
		memcpy(G.vd->localvd, G.vd, sizeof(View3D));

		G.vd->ofs[0]= -(min[0]+max[0])/2.0;
		G.vd->ofs[1]= -(min[1]+max[1])/2.0;
		G.vd->ofs[2]= -(min[2]+max[2])/2.0;

		G.vd->dist= size;

		// correction for window aspect ratio
		if(curarea->winy>2 && curarea->winx>2) {
			size= (float)curarea->winx/(float)curarea->winy;
			if(size<1.0) size= 1.0/size;
			G.vd->dist*= size;
		}
		
		if (G.vd->persp>1) G.vd->persp= 1;
		if (G.vd->near> 0.1) G.vd->near= 0.1;
		
		G.vd->cursor[0]= -G.vd->ofs[0];
		G.vd->cursor[1]= -G.vd->ofs[1];
		G.vd->cursor[2]= -G.vd->ofs[2];

		G.vd->lay= locallay;
		
		countall();
		scrarea_queue_winredraw(curarea);
	}
	else {
		/* clear flags */ 
		base= FIRSTBASE;
		while(base) {
			if( base->lay & locallay ) {
				base->lay-= locallay;
				if(base->lay==0) base->lay= G.vd->layact;
				if(base->object != G.obedit) base->flag |= SELECT;
				base->object->lay= base->lay;
			}
			base= base->next;
		}
		scrarea_queue_headredraw(curarea);
		
		G.vd->localview= 0;
	}
	BIF_view3d_previewrender_signal(curarea, PR_DBASE|PR_DISPRECT);
}

void centerview()	/* like a localview without local! */
{
	Object *ob= OBACT;
	float size, min[3], max[3], afm[3];
	int ok=0;
	
	/* SMOOTHVIEW */
	float new_ofs[3];
	float new_dist;
	
	INIT_MINMAX(min, max);

	if (G.f & G_WEIGHTPAINT) {
		/* hardcoded exception, we look for the one selected armature */
		/* this is weak code this way, we should make a generic active/selection callback interface once... */
		Base *base;
		for(base=FIRSTBASE; base; base= base->next) {
			if(TESTBASELIB(base)) {
				if(base->object->type==OB_ARMATURE)
					if(base->object->flag & OB_POSEMODE)
						break;
			}
		}
		if(base)
			ob= base->object;
	}
	
	
	if(G.obedit) {
		ok = minmax_verts(min, max);	/* only selected */
	}
	else if(ob && (ob->flag & OB_POSEMODE)) {
		if(ob->pose) {
			bArmature *arm= ob->data;
			bPoseChannel *pchan;
			float vec[3];
			
			for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
				if(pchan->bone->flag & BONE_SELECTED) {
					if(pchan->bone->layer & arm->layer) {
						ok= 1;
						VECCOPY(vec, pchan->pose_head);
						Mat4MulVecfl(ob->obmat, vec);
						DO_MINMAX(vec, min, max);
						VECCOPY(vec, pchan->pose_tail);
						Mat4MulVecfl(ob->obmat, vec);
						DO_MINMAX(vec, min, max);
					}
				}
			}
		}
	}
	else if (FACESEL_PAINT_TEST) {
		ok= minmax_tface(min, max);
	}
	else if (G.f & G_PARTICLEEDIT) {
		ok= PE_minmax(min, max);
	}
	else {
		Base *base= FIRSTBASE;
		while(base) {
			if TESTBASE(base)  {
				minmax_object(base->object, min, max);
				/* account for duplis */
				minmax_object_duplis(base->object, min, max);
				
				ok= 1;
			}
			base= base->next;
		}
	}
	
	if(ok==0) return;
	
	afm[0]= (max[0]-min[0]);
	afm[1]= (max[1]-min[1]);
	afm[2]= (max[2]-min[2]);
	size= 0.7*MAX3(afm[0], afm[1], afm[2]);
	
	if(size <= G.vd->near*1.5) size= G.vd->near*1.5;
	
	new_ofs[0]= -(min[0]+max[0])/2.0;
	new_ofs[1]= -(min[1]+max[1])/2.0;
	new_ofs[2]= -(min[2]+max[2])/2.0;
	
	new_dist = size;

	/* correction for window aspect ratio */
	if(curarea->winy>2 && curarea->winx>2) {
		size= (float)curarea->winx/(float)curarea->winy;
		if(size<1.0) size= 1.0/size;
		new_dist*= size;
	}
	
	G.vd->cursor[0]= -new_ofs[0];
	G.vd->cursor[1]= -new_ofs[1];
	G.vd->cursor[2]= -new_ofs[2];
	
	if (G.vd->persp==2 && G.vd->camera) {
		float orig_lens= G.vd->lens;
		
		G.vd->persp=1;
		G.vd->dist= 0.0;
		view_settings_from_ob(G.vd->camera, G.vd->ofs, NULL, NULL, &G.vd->lens);
		smooth_view(G.vd, new_ofs, NULL, &new_dist, &orig_lens);
	} else {
		if(G.vd->persp>=2)
			G.vd->persp= 1;
		
		smooth_view(G.vd, new_ofs, NULL, &new_dist, NULL);
	}
	scrarea_queue_winredraw(curarea);
	BIF_view3d_previewrender_signal(curarea, PR_DBASE|PR_DISPRECT);

}


void restore_localviewdata(View3D *vd)
{
	if(vd->localvd==0) return;
	
	VECCOPY(vd->ofs, vd->localvd->ofs);
	vd->dist= vd->localvd->dist;
	vd->persp= vd->localvd->persp;
	vd->view= vd->localvd->view;
	vd->near= vd->localvd->near;
	vd->far= vd->localvd->far;
	vd->lay= vd->localvd->lay;
	vd->layact= vd->localvd->layact;
	vd->drawtype= vd->localvd->drawtype;
	vd->camera= vd->localvd->camera;
	QUATCOPY(vd->viewquat, vd->localvd->viewquat);
	
}

void endlocalview(ScrArea *sa)
{
	View3D *v3d;
	struct Base *base;
	unsigned int locallay;
	
	if(sa->spacetype!=SPACE_VIEW3D) return;
	v3d= sa->spacedata.first;
	
	if(v3d->localvd) {
		
		locallay= v3d->lay & 0xFF000000;
		
		restore_localviewdata(v3d);
		
		MEM_freeN(v3d->localvd);
		v3d->localvd= 0;
		v3d->localview= 0;

		/* for when in other window the layers have changed */
		if(v3d->scenelock) v3d->lay= G.scene->lay;
		
		base= FIRSTBASE;
		while(base) {
			if( base->lay & locallay ) {
				base->lay-= locallay;
				if(base->lay==0) base->lay= v3d->layact;
				if(base->object != G.obedit) {
					base->flag |= SELECT;
					base->object->flag |= SELECT;
				}
				base->object->lay= base->lay;
			}
			base= base->next;
		}

		countall();
		allqueue(REDRAWVIEW3D, 0);	/* because of select */
		allqueue(REDRAWOOPS, 0);	/* because of select */
		BIF_view3d_previewrender_signal(curarea, PR_DBASE|PR_DISPRECT);
	} 
}

void view3d_home(int center)
{
	Base *base;
	float size, min[3], max[3], afm[3];
	int ok= 1, onedone=0;

	if(center) {
		min[0]= min[1]= min[2]= 0.0;
		max[0]= max[1]= max[2]= 0.0;
	}
	else {
		INIT_MINMAX(min, max);
	}
	
	for(base= FIRSTBASE; base; base= base->next) {
		if(base->lay & G.vd->lay) {
			onedone= 1;
			minmax_object(base->object, min, max);
		}
	}
	if(!onedone) return;
	
	afm[0]= (max[0]-min[0]);
	afm[1]= (max[1]-min[1]);
	afm[2]= (max[2]-min[2]);
	size= 0.7*MAX3(afm[0], afm[1], afm[2]);
	if(size==0.0) ok= 0;
		
	if(ok) {
		float new_dist;
		float new_ofs[3];
		
		new_dist = size;
		new_ofs[0]= -(min[0]+max[0])/2.0;
		new_ofs[1]= -(min[1]+max[1])/2.0;
		new_ofs[2]= -(min[2]+max[2])/2.0;
		
		// correction for window aspect ratio
		if(curarea->winy>2 && curarea->winx>2) {
			size= (float)curarea->winx/(float)curarea->winy;
			if(size<1.0) size= 1.0/size;
			new_dist*= size;
		}
		
		if (G.vd->persp==2 && G.vd->camera) {
			/* switch out of camera view */
			float orig_lens= G.vd->lens;
			
			G.vd->persp=1;
			G.vd->dist= 0.0;
			view_settings_from_ob(G.vd->camera, G.vd->ofs, NULL, NULL, &G.vd->lens);
			smooth_view(G.vd, new_ofs, NULL, &new_dist, &orig_lens);
			
		} else {
			if(G.vd->persp>=2) G.vd->persp= 1;
			smooth_view(G.vd, new_ofs, NULL, &new_dist, NULL);
		}
		scrarea_queue_winredraw(curarea);
	}
	BIF_view3d_previewrender_signal(curarea, PR_DBASE|PR_DISPRECT);

}


void view3d_align_axis_to_vector(View3D *v3d, int axisidx, float vec[3])
{
	float alignaxis[3] = {0.0, 0.0, 0.0};
	float norm[3], axis[3], angle, new_quat[4];

	if(axisidx > 0) alignaxis[axisidx-1]= 1.0;
	else alignaxis[-axisidx-1]= -1.0;

	VECCOPY(norm, vec);
	Normalize(norm);

	angle= acos(Inpf(alignaxis, norm));
	Crossf(axis, alignaxis, norm);
	VecRotToQuat(axis, -angle, new_quat);

	v3d->view= 0;
	
	if (v3d->persp==2 && v3d->camera) {
		/* switch out of camera view */
		float orig_ofs[3];
		float orig_dist= v3d->dist;
		float orig_lens= v3d->lens;

		VECCOPY(orig_ofs, v3d->ofs);
		G.vd->persp=1;
		G.vd->dist= 0.0;
		view_settings_from_ob(v3d->camera, v3d->ofs, NULL, NULL, &v3d->lens);
		smooth_view(G.vd, orig_ofs, new_quat, &orig_dist, &orig_lens);
	} else {
		if (v3d->persp>=2) v3d->persp= 1; /* switch out of camera mode */
		smooth_view(v3d, NULL, new_quat, NULL, NULL);
	}
}



/* SMOOTHVIEW */
void smooth_view(View3D *v3d, float *ofs, float *quat, float *dist, float *lens)
{
	/* View Animation enabled */
	if (U.smooth_viewtx) {
		int i;
		char changed = 0;
		float step = 0.0, step_inv;
		float orig_dist;
		float orig_lens;
		float orig_quat[4];
		float orig_ofs[3];
		
		double time_allowed, time_current, time_start;
		
		/* if there is no difference, return */
		changed = 0; /* zero means no difference */
		if (dist) {
			if ((*dist) != v3d->dist)
				changed = 1;
		}
		
		if (lens) {
			if ((*lens) != v3d->lens)
				changed = 1;
		}
		
		if (!changed && ofs) {
			if ((ofs[0]!=v3d->ofs[0]) ||
				(ofs[1]!=v3d->ofs[1]) ||
				(ofs[2]!=v3d->ofs[2]) )
				changed = 1;
		}
		
		if (!changed && quat ) {
			if ((quat[0]!=v3d->viewquat[0]) ||
				(quat[1]!=v3d->viewquat[1]) ||
				(quat[2]!=v3d->viewquat[2]) ||
				(quat[3]!=v3d->viewquat[3]) )
				changed = 1;
		}
		
		/* The new view is different from teh old one
		 * so animate the view */
		if (changed) {
			
			/* store original values */
			VECCOPY(orig_ofs,	v3d->ofs);
			QUATCOPY(orig_quat,	v3d->viewquat);
			orig_dist =			v3d->dist;
			orig_lens =			v3d->lens;
			
			time_allowed= (float)U.smooth_viewtx / 1000.0;
			time_current = time_start = PIL_check_seconds_timer();
			
			/* if this is view rotation only
			 * we can decrease the time allowed by
			 * the angle between quats 
			 * this means small rotations wont lag */
			 if (quat && !ofs && !dist) {
			 	float vec1[3], vec2[3];
			 	VECCOPY(vec1, quat);
			 	VECCOPY(vec2, v3d->viewquat);
			 	Normalize(vec1);
			 	Normalize(vec2);
			 	/* scale the time allowed by the rotation */
			 	time_allowed *= NormalizedVecAngle2(vec1, vec2)/(M_PI/2); 
			 }
			
			while (time_start + time_allowed > time_current) {
				
				step =  (float)((time_current-time_start) / time_allowed);
				
				/* ease in/out */
				if (step < 0.5)	step = pow(step*2, 2)/2;
				else			step = 1-(pow(2*(1-step) ,2)/2);
				
				step_inv = 1-step;
				
				if (ofs)
					for (i=0; i<3; i++)
						v3d->ofs[i] = ofs[i]*step + orig_ofs[i]*step_inv;
				
				
				if (quat)
					QuatInterpol(v3d->viewquat, orig_quat, quat, step);
					
				if (dist)
					v3d->dist = ((*dist)*step) + (orig_dist*step_inv);
				
				if (lens)
					v3d->lens = ((*lens)*step) + (orig_lens*step_inv);
				
				/*redraw the view*/
				scrarea_do_windraw(curarea);
				screen_swapbuffers();
				
				time_current= PIL_check_seconds_timer();
			}
		}
	}
	
	/* set these values even if animation is enabled because flaot
	 * error will make then not quite accurate */
	if (ofs)
		VECCOPY(v3d->ofs, ofs);
	if (quat)
		QUATCOPY(v3d->viewquat, quat);
	if (dist)
		v3d->dist = *dist;
	if (lens)
		v3d->lens = *lens;
	
}



/* Gets the view trasnformation from a camera
 * currently dosnt take camzoom into account
 * 
 * The dist is not modified for this function, if NULL its assimed zero
 * */
void view_settings_from_ob(Object *ob, float *ofs, float *quat, float *dist, float *lens)
{	
	float bmat[4][4];
	float imat[4][4];
	float tmat[3][3];
	
	if (!ob) return;
	
	/* Offset */
	if (ofs) {
		where_is_object(ob);
		VECCOPY(ofs, ob->obmat[3]);
		VecMulf(ofs, -1.0f); /*flip the vector*/
	}
	
	/* Quat */
	if (quat) {
		Mat4CpyMat4(bmat, ob->obmat);
		Mat4Ortho(bmat);
		Mat4Invert(imat, bmat);
		Mat3CpyMat4(tmat, imat);
		Mat3ToQuat(tmat, quat);
	}
	
	if (dist) {
		float vec[3];
		Mat3CpyMat4(tmat, ob->obmat);
		
		vec[0]= vec[1] = 0.0;
		vec[2]= -(*dist);
		Mat3MulVecfl(tmat, vec);
		VecSubf(ofs, ofs, vec);
	}
	
	/* Lens */
	if (lens)
		object_view_settings(ob, lens, NULL, NULL);
}

/* For use with smooth view
 * 
 * the current view is unchanged, blend between the current view and the
 * camera view
 * */
void smooth_view_to_camera(View3D *v3d)
{
	if (!U.smooth_viewtx || !v3d->camera || G.vd->persp != 2) {
		return;
	} else {
		Object *ob = v3d->camera;
		
		float orig_ofs[3];
		float orig_dist=v3d->dist;
		float orig_lens=v3d->lens;
		float new_dist=0.0;
		float new_lens=35.0;
		float new_quat[4];
		float new_ofs[3];
		
		VECCOPY(orig_ofs, v3d->ofs);
		
		view_settings_from_ob(ob, new_ofs, new_quat, NULL, &new_lens);
		
		G.vd->persp=1;
		smooth_view(v3d, new_ofs, new_quat, &new_dist, &new_lens);
		VECCOPY(v3d->ofs, orig_ofs);
		v3d->lens= orig_lens;
		v3d->dist = orig_dist; /* restore the dist */
		
		v3d->camera = ob;
		v3d->persp=2;
	}
}