]> de.git.xonotic.org Git - xonotic/netradiant.git/blob - radiant/selection.cpp
Merge commit '0709fce07d9c630ca0455ebeb58e3806427ca8ce' into garux-merge
[xonotic/netradiant.git] / radiant / selection.cpp
1 /*
2    Copyright (C) 2001-2006, William Joseph.
3    All Rights Reserved.
4
5    This file is part of GtkRadiant.
6
7    GtkRadiant is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    GtkRadiant is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with GtkRadiant; if not, write to the Free Software
19    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20  */
21
22 #include "selection.h"
23 #include "globaldefs.h"
24
25 #include "debugging/debugging.h"
26
27 #include <map>
28 #include <list>
29 #include <set>
30
31 #include "windowobserver.h"
32 #include "iundo.h"
33 #include "ientity.h"
34 #include "cullable.h"
35 #include "renderable.h"
36 #include "selectable.h"
37 #include "editable.h"
38
39 #include "math/frustum.h"
40 #include "signal/signal.h"
41 #include "generic/object.h"
42 #include "selectionlib.h"
43 #include "render.h"
44 #include "view.h"
45 #include "renderer.h"
46 #include "stream/stringstream.h"
47 #include "eclasslib.h"
48 #include "generic/bitfield.h"
49 #include "generic/static.h"
50 #include "pivot.h"
51 #include "stringio.h"
52 #include "container/container.h"
53
54 #include "grid.h"
55
56 TextOutputStream& ostream_write( TextOutputStream& t, const Vector4& v ){
57         return t << "[ " << v.x() << " " << v.y() << " " << v.z() << " " << v.w() << " ]";
58 }
59
60 TextOutputStream& ostream_write( TextOutputStream& t, const Matrix4& m ){
61         return t << "[ " << m.x() << " " << m.y() << " " << m.z() << " " << m.t() << " ]";
62 }
63
64 struct Pivot2World
65 {
66         Matrix4 m_worldSpace;
67         Matrix4 m_viewpointSpace;
68         Matrix4 m_viewplaneSpace;
69         Vector3 m_axis_screen;
70
71         void update( const Matrix4& pivot2world, const Matrix4& modelview, const Matrix4& projection, const Matrix4& viewport ){
72                 Pivot2World_worldSpace( m_worldSpace, pivot2world, modelview, projection, viewport );
73                 Pivot2World_viewpointSpace( m_viewpointSpace, m_axis_screen, pivot2world, modelview, projection, viewport );
74                 Pivot2World_viewplaneSpace( m_viewplaneSpace, pivot2world, modelview, projection, viewport );
75         }
76 };
77
78
79 void point_for_device_point( Vector3& point, const Matrix4& device2object, const float x, const float y, const float z ){
80         // transform from normalised device coords to object coords
81         point = vector4_projected( matrix4_transformed_vector4( device2object, Vector4( x, y, z, 1 ) ) );
82 }
83
84 void ray_for_device_point( Ray& ray, const Matrix4& device2object, const float x, const float y ){
85         // point at x, y, zNear
86         point_for_device_point( ray.origin, device2object, x, y, -1 );
87
88         // point at x, y, zFar
89         point_for_device_point( ray.direction, device2object, x, y, 1 );
90
91         // construct ray
92         vector3_subtract( ray.direction, ray.origin );
93         vector3_normalise( ray.direction );
94 }
95
96 bool sphere_intersect_ray( const Vector3& origin, float radius, const Ray& ray, Vector3& intersection ){
97         intersection = vector3_subtracted( origin, ray.origin );
98         const double a = vector3_dot( intersection, ray.direction );
99         const double d = radius * radius - ( vector3_dot( intersection, intersection ) - a * a );
100
101         if ( d > 0 ) {
102                 intersection = vector3_added( ray.origin, vector3_scaled( ray.direction, a - sqrt( d ) ) );
103                 return true;
104         }
105         else
106         {
107                 intersection = vector3_added( ray.origin, vector3_scaled( ray.direction, a ) );
108                 return false;
109         }
110 }
111
112 void ray_intersect_ray( const Ray& ray, const Ray& other, Vector3& intersection ){
113         intersection = vector3_subtracted( ray.origin, other.origin );
114         //float a = 1;//vector3_dot(ray.direction, ray.direction);        // always >= 0
115         double dot = vector3_dot( ray.direction, other.direction );
116         //float c = 1;//vector3_dot(other.direction, other.direction);        // always >= 0
117         double d = vector3_dot( ray.direction, intersection );
118         double e = vector3_dot( other.direction, intersection );
119         double D = 1 - dot * dot; //a*c - dot*dot;       // always >= 0
120
121         if ( D < 0.000001 ) {
122                 // the lines are almost parallel
123                 intersection = vector3_added( other.origin, vector3_scaled( other.direction, e ) );
124         }
125         else
126         {
127                 intersection = vector3_added( other.origin, vector3_scaled( other.direction, ( e - dot * d ) / D ) );
128         }
129 }
130
131 const Vector3 g_origin( 0, 0, 0 );
132 const float g_radius = 64;
133
134 void point_on_sphere( Vector3& point, const Matrix4& device2object, const float x, const float y ){
135         Ray ray;
136         ray_for_device_point( ray, device2object, x, y );
137         sphere_intersect_ray( g_origin, g_radius, ray, point );
138 }
139
140 void point_on_axis( Vector3& point, const Vector3& axis, const Matrix4& device2object, const float x, const float y ){
141         Ray ray;
142         ray_for_device_point( ray, device2object, x, y );
143         ray_intersect_ray( ray, Ray( Vector3( 0, 0, 0 ), axis ), point );
144 }
145
146 void point_on_plane( Vector3& point, const Matrix4& device2object, const float x, const float y ){
147         Matrix4 object2device( matrix4_full_inverse( device2object ) );
148         point = vector4_projected( matrix4_transformed_vector4( device2object, Vector4( x, y, object2device[14] / object2device[15], 1 ) ) );
149 }
150
151 //! a and b are unit vectors .. returns angle in radians
152 inline float angle_between( const Vector3& a, const Vector3& b ){
153         return static_cast<float>( 2.0 * atan2(
154                                                                    vector3_length( vector3_subtracted( a, b ) ),
155                                                                    vector3_length( vector3_added( a, b ) )
156                                                                    ) );
157 }
158
159
160 #if GDEF_DEBUG
161 class test_quat
162 {
163 public:
164 test_quat( const Vector3& from, const Vector3& to ){
165         Vector4 quaternion( quaternion_for_unit_vectors( from, to ) );
166         Matrix4 matrix( matrix4_rotation_for_quaternion( quaternion_multiplied_by_quaternion( quaternion, c_quaternion_identity ) ) );
167 }
168 private:
169 };
170
171 static test_quat bleh( g_vector3_axis_x, g_vector3_axis_y );
172 #endif
173
174 //! axis is a unit vector
175 inline void constrain_to_axis( Vector3& vec, const Vector3& axis ){
176         vec = vector3_normalised( vector3_added( vec, vector3_scaled( axis, -vector3_dot( vec, axis ) ) ) );
177 }
178
179 //! a and b are unit vectors .. a and b must be orthogonal to axis .. returns angle in radians
180 float angle_for_axis( const Vector3& a, const Vector3& b, const Vector3& axis ){
181         if ( vector3_dot( axis, vector3_cross( a, b ) ) > 0.0 ) {
182                 return angle_between( a, b );
183         }
184         else{
185                 return -angle_between( a, b );
186         }
187 }
188
189 float distance_for_axis( const Vector3& a, const Vector3& b, const Vector3& axis ){
190         return static_cast<float>( vector3_dot( b, axis ) - vector3_dot( a, axis ) );
191 }
192
193 class Manipulatable
194 {
195 public:
196 virtual void Construct( const Matrix4& device2manip, const float x, const float y, const AABB bounds, const Vector3 transform_origin ) = 0;
197 virtual void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox ) = 0;
198 };
199
200 void transform_local2object( Matrix4& object, const Matrix4& local, const Matrix4& local2object ){
201         object = matrix4_multiplied_by_matrix4(
202                 matrix4_multiplied_by_matrix4( local2object, local ),
203                 matrix4_full_inverse( local2object )
204                 );
205 }
206
207 class Rotatable
208 {
209 public:
210 virtual ~Rotatable() = default;
211 virtual void rotate( const Quaternion& rotation ) = 0;
212 };
213
214 class RotateFree : public Manipulatable
215 {
216 Vector3 m_start;
217 Rotatable& m_rotatable;
218 public:
219 RotateFree( Rotatable& rotatable )
220         : m_rotatable( rotatable ){
221 }
222 void Construct( const Matrix4& device2manip, const float x, const float y, const AABB bounds, const Vector3 transform_origin ){
223         point_on_sphere( m_start, device2manip, x, y );
224         vector3_normalise( m_start );
225 }
226 void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox ){
227         Vector3 current;
228         point_on_sphere( current, device2manip, x, y );
229
230         if( snap ){
231                 Vector3 axis( 0, 0, 0 );
232                 for( std::size_t i = 0; i < 3; ++i ){
233                         if( current[i] == 0.0f ){
234                                 axis[i] = 1.0f;
235                                 break;
236                         }
237                 }
238                 if( vector3_length_squared( axis ) != 0 ){
239                         constrain_to_axis( current, axis );
240                         m_rotatable.rotate( quaternion_for_axisangle( axis, float_snapped( angle_for_axis( m_start, current, axis ), static_cast<float>( c_pi / 12.0 ) ) ) );
241                         return;
242                 }
243         }
244
245         vector3_normalise( current );
246         m_rotatable.rotate( quaternion_for_unit_vectors( m_start, current ) );
247 }
248 };
249
250 class RotateAxis : public Manipulatable
251 {
252 Vector3 m_axis;
253 Vector3 m_start;
254 Rotatable& m_rotatable;
255 public:
256 RotateAxis( Rotatable& rotatable )
257         : m_rotatable( rotatable ){
258 }
259 void Construct( const Matrix4& device2manip, const float x, const float y, const AABB bounds, const Vector3 transform_origin ){
260         point_on_sphere( m_start, device2manip, x, y );
261         constrain_to_axis( m_start, m_axis );
262 }
263 /// \brief Converts current position to a normalised vector orthogonal to axis.
264 void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox ){
265         Vector3 current;
266         point_on_sphere( current, device2manip, x, y );
267         constrain_to_axis( current, m_axis );
268
269         if( snap ){
270                 m_rotatable.rotate( quaternion_for_axisangle( m_axis, float_snapped( angle_for_axis( m_start, current, m_axis ), static_cast<float>( c_pi / 12.0 ) ) ) );
271         }
272         else{
273                 m_rotatable.rotate( quaternion_for_axisangle( m_axis, angle_for_axis( m_start, current, m_axis ) ) );
274         }
275 }
276
277 void SetAxis( const Vector3& axis ){
278         m_axis = axis;
279 }
280 };
281
282 void translation_local2object( Vector3& object, const Vector3& local, const Matrix4& local2object ){
283         object = matrix4_get_translation_vec3(
284                 matrix4_multiplied_by_matrix4(
285                         matrix4_translated_by_vec3( local2object, local ),
286                         matrix4_full_inverse( local2object )
287                         )
288                 );
289 }
290
291 class Translatable
292 {
293 public:
294 virtual ~Translatable() = default;
295 virtual void translate( const Vector3& translation ) = 0;
296 };
297
298 class TranslateAxis : public Manipulatable
299 {
300 Vector3 m_start;
301 Vector3 m_axis;
302 Translatable& m_translatable;
303 AABB m_bounds;
304 public:
305 TranslateAxis( Translatable& translatable )
306         : m_translatable( translatable ){
307 }
308 void Construct( const Matrix4& device2manip, const float x, const float y, const AABB bounds, const Vector3 transform_origin ){
309         point_on_axis( m_start, m_axis, device2manip, x, y );
310         m_bounds = bounds;
311 }
312 void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox ){
313         Vector3 current;
314         point_on_axis( current, m_axis, device2manip, x, y );
315         current = vector3_scaled( m_axis, distance_for_axis( m_start, current, m_axis ) );
316
317         translation_local2object( current, current, manip2object );
318         if( snapbbox ){
319                 float grid = GetSnapGridSize();
320                 Vector3 maxs( m_bounds.origin + m_bounds.extents );
321                 Vector3 mins( m_bounds.origin - m_bounds.extents );
322 //              globalOutputStream() << "current: " << current << "\n";
323                 for( std::size_t i = 0; i < 3; ++i ){
324                         if( m_axis[i] != 0.f ){
325                                 float snapto1 = float_snapped( maxs[i] + current[i] , grid );
326                                 float snapto2 = float_snapped( mins[i] + current[i] , grid );
327
328                                 float dist1 = fabs( fabs( maxs[i] + current[i] ) - fabs( snapto1 ) );
329                                 float dist2 = fabs( fabs( mins[i] + current[i] ) - fabs( snapto2 ) );
330
331 //                              globalOutputStream() << "maxs[i] + current[i]: " << maxs[i] + current[i]  << "    snapto1: " << snapto1 << "   dist1: " << dist1 << "\n";
332 //                              globalOutputStream() << "mins[i] + current[i]: " << mins[i] + current[i]  << "    snapto2: " << snapto2 << "   dist2: " << dist2 << "\n";
333                                 current[i] = dist2 > dist1 ? snapto1 - maxs[i] : snapto2 - mins[i];
334                         }
335                 }
336         }
337         else{
338                 vector3_snap( current, GetSnapGridSize() );
339         }
340
341         m_translatable.translate( current );
342 }
343
344 void SetAxis( const Vector3& axis ){
345         m_axis = axis;
346 }
347 };
348
349 class TranslateFree : public Manipulatable
350 {
351 private:
352 Vector3 m_start;
353 Translatable& m_translatable;
354 AABB m_bounds;
355 public:
356 TranslateFree( Translatable& translatable )
357         : m_translatable( translatable ){
358 }
359 void Construct( const Matrix4& device2manip, const float x, const float y, const AABB bounds, const Vector3 transform_origin ){
360         point_on_plane( m_start, device2manip, x, y );
361         m_bounds = bounds;
362 }
363 void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox ){
364         Vector3 current;
365         point_on_plane( current, device2manip, x, y );
366         current = vector3_subtracted( current, m_start );
367
368         if( snap ){
369                 for ( std::size_t i = 0; i < 3 ; ++i ){
370                         if( fabs( current[i] ) >= fabs( current[(i + 1) % 3] ) ){
371                                 current[(i + 1) % 3] = 0.0f;
372                         }
373                         else{
374                                 current[i] = 0.0f;
375                         }
376                 }
377         }
378
379         translation_local2object( current, current, manip2object );
380         if( snapbbox ){
381                 float grid = GetSnapGridSize();
382                 Vector3 maxs( m_bounds.origin + m_bounds.extents );
383                 Vector3 mins( m_bounds.origin - m_bounds.extents );
384 //              globalOutputStream() << "current: " << current << "\n";
385                 for( std::size_t i = 0; i < 3; ++i ){
386                         if( current[i] != 0.f ){
387                                 float snapto1 = float_snapped( maxs[i] + current[i] , grid );
388                                 float snapto2 = float_snapped( mins[i] + current[i] , grid );
389
390                                 float dist1 = fabs( fabs( maxs[i] + current[i] ) - fabs( snapto1 ) );
391                                 float dist2 = fabs( fabs( mins[i] + current[i] ) - fabs( snapto2 ) );
392
393                                 current[i] = dist2 > dist1 ? snapto1 - maxs[i] : snapto2 - mins[i];
394                         }
395                 }
396         }
397         else{
398                 vector3_snap( current, GetSnapGridSize() );
399         }
400
401         m_translatable.translate( current );
402 }
403 };
404
405 class Scalable
406 {
407 public:
408 virtual ~Scalable() = default;
409 virtual void scale( const Vector3& scaling ) = 0;
410 };
411
412
413 class ScaleAxis : public Manipulatable
414 {
415 private:
416 Vector3 m_start;
417 Vector3 m_axis;
418 Scalable& m_scalable;
419
420 Vector3 m_choosen_extent;
421 AABB m_bounds;
422
423 public:
424 ScaleAxis( Scalable& scalable )
425         : m_scalable( scalable ){
426 }
427 void Construct( const Matrix4& device2manip, const float x, const float y, const AABB bounds, const Vector3 transform_origin ){
428         point_on_axis( m_start, m_axis, device2manip, x, y );
429
430         m_choosen_extent = Vector3(
431                                         std::max( bounds.origin[0] + bounds.extents[0] - transform_origin[0], - bounds.origin[0] + bounds.extents[0] + transform_origin[0] ),
432                                         std::max( bounds.origin[1] + bounds.extents[1] - transform_origin[1], - bounds.origin[1] + bounds.extents[1] + transform_origin[1] ),
433                                         std::max( bounds.origin[2] + bounds.extents[2] - transform_origin[2], - bounds.origin[2] + bounds.extents[2] + transform_origin[2] )
434                                                         );
435         m_bounds = bounds;
436 }
437 void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox ){
438         //globalOutputStream() << "manip2object: " << manip2object << "  device2manip: " << device2manip << "  x: " << x << "  y:" << y <<"\n";
439         Vector3 current;
440         point_on_axis( current, m_axis, device2manip, x, y );
441         Vector3 delta = vector3_subtracted( current, m_start );
442
443         translation_local2object( delta, delta, manip2object );
444         vector3_snap( delta, GetSnapGridSize() );
445
446         Vector3 start( vector3_snapped( m_start, GetSnapGridSize() != 0.0f ? GetSnapGridSize() : 0.001f ) );
447         for ( std::size_t i = 0; i < 3 ; ++i ){ //prevent snapping to 0 with big gridsize
448                 if( float_snapped( m_start[i], 0.001f ) != 0.0f && start[i] == 0.0f ){
449                         start[i] = GetSnapGridSize();
450                 }
451         }
452         //globalOutputStream() << "m_start: " << m_start << "   start: " << start << "   delta: " << delta <<"\n";
453         Vector3 scale(
454                 start[0] == 0 ? 1 : 1 + delta[0] / start[0],
455                 start[1] == 0 ? 1 : 1 + delta[1] / start[1],
456                 start[2] == 0 ? 1 : 1 + delta[2] / start[2]
457                 );
458
459         for( std::size_t i = 0; i < 3; i++ ){
460                 if( m_choosen_extent[i] > 0.0625f && m_axis[i] != 0.f ){ //epsilon to prevent super high scale for set of models, having really small extent, formed by origins
461                         scale[i] = ( m_choosen_extent[i] + delta[i] ) / m_choosen_extent[i];
462                         if( snapbbox ){
463                                 float snappdwidth = float_snapped( scale[i] * m_bounds.extents[i] * 2.f, GetSnapGridSize() );
464                                 scale[i] = snappdwidth / ( m_bounds.extents[i] * 2.f );
465                         }
466                 }
467         }
468         if( snap ){
469                 for( std::size_t i = 0; i < 3; i++ ){
470                         if( scale[i] == 1.0f ){
471                                 scale[i] = vector3_dot( scale, m_axis );
472                         }
473                 }
474         }
475         //globalOutputStream() << "scale: " << scale <<"\n";
476         m_scalable.scale( scale );
477 }
478
479 void SetAxis( const Vector3& axis ){
480         m_axis = axis;
481 }
482 };
483
484 class ScaleFree : public Manipulatable
485 {
486 private:
487 Vector3 m_start;
488 Scalable& m_scalable;
489
490 Vector3 m_choosen_extent;
491 AABB m_bounds;
492
493 public:
494 ScaleFree( Scalable& scalable )
495         : m_scalable( scalable ){
496 }
497 void Construct( const Matrix4& device2manip, const float x, const float y, const AABB bounds, const Vector3 transform_origin ){
498         point_on_plane( m_start, device2manip, x, y );
499
500         m_choosen_extent = Vector3(
501                                         std::max( bounds.origin[0] + bounds.extents[0] - transform_origin[0], - bounds.origin[0] + bounds.extents[0] + transform_origin[0] ),
502                                         std::max( bounds.origin[1] + bounds.extents[1] - transform_origin[1], - bounds.origin[1] + bounds.extents[1] + transform_origin[1] ),
503                                         std::max( bounds.origin[2] + bounds.extents[2] - transform_origin[2], - bounds.origin[2] + bounds.extents[2] + transform_origin[2] )
504                                                         );
505         m_bounds = bounds;
506 }
507 void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox ){
508         Vector3 current;
509         point_on_plane( current, device2manip, x, y );
510         Vector3 delta = vector3_subtracted( current, m_start );
511
512         translation_local2object( delta, delta, manip2object );
513         vector3_snap( delta, GetSnapGridSize() );
514
515         Vector3 start( vector3_snapped( m_start, GetSnapGridSize() != 0.0f ? GetSnapGridSize() : 0.001f ) );
516         for ( std::size_t i = 0; i < 3 ; ++i ){ //prevent snapping to 0 with big gridsize
517                 if( float_snapped( m_start[i], 0.001f ) != 0.0f && start[i] == 0.0f ){
518                         start[i] = GetSnapGridSize();
519                 }
520         }
521         Vector3 scale(
522                 start[0] == 0 ? 1 : 1 + delta[0] / start[0],
523                 start[1] == 0 ? 1 : 1 + delta[1] / start[1],
524                 start[2] == 0 ? 1 : 1 + delta[2] / start[2]
525                 );
526
527         //globalOutputStream() << "m_start: " << m_start << "   start: " << start << "   delta: " << delta <<"\n";
528         for( std::size_t i = 0; i < 3; i++ ){
529                 if( m_choosen_extent[i] > 0.0625f ){
530                         scale[i] = ( m_choosen_extent[i] + delta[i] ) / m_choosen_extent[i];
531                         if( snapbbox && start[i] != 0.f ){
532                                 float snappdwidth = float_snapped( scale[i] * m_bounds.extents[i] * 2.f, GetSnapGridSize() );
533                                 scale[i] = snappdwidth / ( m_bounds.extents[i] * 2.f );
534                         }
535                 }
536         }
537         //globalOutputStream() << "pre snap scale: " << scale <<"\n";
538         if( snap ){
539                 float bestscale = scale[0];
540                 for( std::size_t i = 1; i < 3; i++ ){
541                         //if( fabs( 1.0f - fabs( scale[i] ) ) > fabs( 1.0f - fabs( bestscale ) ) ){
542                         if( fabs( scale[i] ) > fabs( bestscale ) && scale[i] != 1.0f ){ //harder to scale down with this, but glitchier with upper one
543                                 bestscale = scale[i];
544                         }
545                         //globalOutputStream() << "bestscale: " << bestscale <<"\n";
546                 }
547                 for( std::size_t i = 0; i < 3; i++ ){
548                         if( start[i] != 0.0f ){ // !!!!check grid == 0 case
549                                 scale[i] = ( scale[i] < 0.0f ) ? -fabs( bestscale ) : fabs( bestscale );
550                         }
551                 }
552         }
553         //globalOutputStream() << "scale: " << scale <<"\n";
554         m_scalable.scale( scale );
555 }
556 };
557
558
559
560
561
562
563
564
565
566
567 class RenderableClippedPrimitive : public OpenGLRenderable
568 {
569 struct primitive_t
570 {
571         PointVertex m_points[9];
572         std::size_t m_count;
573 };
574 Matrix4 m_inverse;
575 std::vector<primitive_t> m_primitives;
576 public:
577 Matrix4 m_world;
578
579 void render( RenderStateFlags state ) const {
580         for ( std::size_t i = 0; i < m_primitives.size(); ++i )
581         {
582                 glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( PointVertex ), &m_primitives[i].m_points[0].colour );
583                 glVertexPointer( 3, GL_FLOAT, sizeof( PointVertex ), &m_primitives[i].m_points[0].vertex );
584                 switch ( m_primitives[i].m_count )
585                 {
586                 case 1: break;
587                 case 2: glDrawArrays( GL_LINES, 0, GLsizei( m_primitives[i].m_count ) ); break;
588                 default: glDrawArrays( GL_POLYGON, 0, GLsizei( m_primitives[i].m_count ) ); break;
589                 }
590         }
591 }
592
593 void construct( const Matrix4& world2device ){
594         m_inverse = matrix4_full_inverse( world2device );
595         m_world = g_matrix4_identity;
596 }
597
598 void insert( const Vector4 clipped[9], std::size_t count ){
599         add_one();
600
601         m_primitives.back().m_count = count;
602         for ( std::size_t i = 0; i < count; ++i )
603         {
604                 Vector3 world_point( vector4_projected( matrix4_transformed_vector4( m_inverse, clipped[i] ) ) );
605                 m_primitives.back().m_points[i].vertex = vertex3f_for_vector3( world_point );
606         }
607 }
608
609 void destroy(){
610         m_primitives.clear();
611 }
612 private:
613 void add_one(){
614         m_primitives.push_back( primitive_t() );
615
616         const Colour4b colour_clipped( 255, 127, 0, 255 );
617
618         for ( std::size_t i = 0; i < 9; ++i )
619                 m_primitives.back().m_points[i].colour = colour_clipped;
620 }
621 };
622
623 #if GDEF_DEBUG
624 #define DEBUG_SELECTION
625 #endif
626
627 #if defined( DEBUG_SELECTION )
628 Shader* g_state_clipped;
629 RenderableClippedPrimitive g_render_clipped;
630 #endif
631
632
633 #if 0
634 // dist_Point_to_Line(): get the distance of a point to a line.
635 //    Input:  a Point P and a Line L (in any dimension)
636 //    Return: the shortest distance from P to L
637 float
638 dist_Point_to_Line( Point P, Line L ){
639         Vector v = L.P1 - L.P0;
640         Vector w = P - L.P0;
641
642         double c1 = dot( w,v );
643         double c2 = dot( v,v );
644         double b = c1 / c2;
645
646         Point Pb = L.P0 + b * v;
647         return d( P, Pb );
648 }
649 #endif
650
651 class Segment3D
652 {
653 typedef Vector3 point_type;
654 public:
655 Segment3D( const point_type& _p0, const point_type& _p1 )
656         : p0( _p0 ), p1( _p1 ){
657 }
658
659 point_type p0, p1;
660 };
661
662 typedef Vector3 Point3D;
663
664 inline double vector3_distance_squared( const Point3D& a, const Point3D& b ){
665         return vector3_length_squared( b - a );
666 }
667
668 // get the distance of a point to a segment.
669 Point3D segment_closest_point_to_point( const Segment3D& segment, const Point3D& point ){
670         Vector3 v = segment.p1 - segment.p0;
671         Vector3 w = point - segment.p0;
672
673         double c1 = vector3_dot( w,v );
674         if ( c1 <= 0 ) {
675                 return segment.p0;
676         }
677
678         double c2 = vector3_dot( v,v );
679         if ( c2 <= c1 ) {
680                 return segment.p1;
681         }
682
683         return Point3D( segment.p0 + v * ( c1 / c2 ) );
684 }
685
686 double segment_dist_to_point_3d( const Segment3D& segment, const Point3D& point ){
687         return vector3_distance_squared( point, segment_closest_point_to_point( segment, point ) );
688 }
689
690 typedef Vector3 point_t;
691 typedef const Vector3* point_iterator_t;
692
693 // crossing number test for a point in a polygon
694 // This code is patterned after [Franklin, 2000]
695 bool point_test_polygon_2d( const point_t& P, point_iterator_t start, point_iterator_t finish ){
696         std::size_t crossings = 0;
697
698         // loop through all edges of the polygon
699         for ( point_iterator_t prev = finish - 1, cur = start; cur != finish; prev = cur, ++cur )
700         {  // edge from (*prev) to (*cur)
701                 if ( ( ( ( *prev )[1] <= P[1] ) && ( ( *cur )[1] > P[1] ) ) // an upward crossing
702                          || ( ( ( *prev )[1] > P[1] ) && ( ( *cur )[1] <= P[1] ) ) ) { // a downward crossing
703                                                                                       // compute the actual edge-ray intersect x-coordinate
704                         float vt = (float)( P[1] - ( *prev )[1] ) / ( ( *cur )[1] - ( *prev )[1] );
705                         if ( P[0] < ( *prev )[0] + vt * ( ( *cur )[0] - ( *prev )[0] ) ) { // P[0] < intersect
706                                 ++crossings; // a valid crossing of y=P[1] right of P[0]
707                         }
708                 }
709         }
710         return ( crossings & 0x1 ) != 0; // 0 if even (out), and 1 if odd (in)
711 }
712
713 inline double triangle_signed_area_XY( const Vector3& p0, const Vector3& p1, const Vector3& p2 ){
714         return ( ( p1[0] - p0[0] ) * ( p2[1] - p0[1] ) ) - ( ( p2[0] - p0[0] ) * ( p1[1] - p0[1] ) );
715 }
716
717 enum clipcull_t
718 {
719         eClipCullNone,
720         eClipCullCW,
721         eClipCullCCW,
722 };
723
724
725 inline SelectionIntersection select_point_from_clipped( Vector4& clipped ){
726         return SelectionIntersection( clipped[2] / clipped[3], static_cast<float>( vector3_length_squared( Vector3( clipped[0] / clipped[3], clipped[1] / clipped[3], 0 ) ) ) );
727 }
728
729 void BestPoint( std::size_t count, Vector4 clipped[9], SelectionIntersection& best, clipcull_t cull ){
730         Vector3 normalised[9];
731
732         {
733                 for ( std::size_t i = 0; i < count; ++i )
734                 {
735                         normalised[i][0] = clipped[i][0] / clipped[i][3];
736                         normalised[i][1] = clipped[i][1] / clipped[i][3];
737                         normalised[i][2] = clipped[i][2] / clipped[i][3];
738                 }
739         }
740
741         if ( cull != eClipCullNone && count > 2 ) {
742                 double signed_area = triangle_signed_area_XY( normalised[0], normalised[1], normalised[2] );
743
744                 if ( ( cull == eClipCullCW && signed_area > 0 )
745                          || ( cull == eClipCullCCW && signed_area < 0 ) ) {
746                         return;
747                 }
748         }
749
750         if ( count == 2 ) {
751                 Segment3D segment( normalised[0], normalised[1] );
752                 Point3D point = segment_closest_point_to_point( segment, Vector3( 0, 0, 0 ) );
753                 assign_if_closer( best, SelectionIntersection( point.z(), 0 ) );
754         }
755         else if ( count > 2 && !point_test_polygon_2d( Vector3( 0, 0, 0 ), normalised, normalised + count ) ) {
756                 point_iterator_t end = normalised + count;
757                 for ( point_iterator_t previous = end - 1, current = normalised; current != end; previous = current, ++current )
758                 {
759                         Segment3D segment( *previous, *current );
760                         Point3D point = segment_closest_point_to_point( segment, Vector3( 0, 0, 0 ) );
761                         float depth = point.z();
762                         point.z() = 0;
763                         float distance = static_cast<float>( vector3_length_squared( point ) );
764
765                         assign_if_closer( best, SelectionIntersection( depth, distance ) );
766                 }
767         }
768         else if ( count > 2 ) {
769                 assign_if_closer(
770                         best,
771                         SelectionIntersection(
772                                 static_cast<float>( ray_distance_to_plane(
773                                                                                 Ray( Vector3( 0, 0, 0 ), Vector3( 0, 0, 1 ) ),
774                                                                                 plane3_for_points( normalised[0], normalised[1], normalised[2] )
775                                                                                 ) ),
776                                 0
777                                 )
778                         );
779         }
780
781 #if defined( DEBUG_SELECTION )
782         if ( count >= 2 ) {
783                 g_render_clipped.insert( clipped, count );
784         }
785 #endif
786 }
787
788 void LineStrip_BestPoint( const Matrix4& local2view, const PointVertex* vertices, const std::size_t size, SelectionIntersection& best ){
789         Vector4 clipped[2];
790         for ( std::size_t i = 0; ( i + 1 ) < size; ++i )
791         {
792                 const std::size_t count = matrix4_clip_line( local2view, vertex3f_to_vector3( vertices[i].vertex ), vertex3f_to_vector3( vertices[i + 1].vertex ), clipped );
793                 BestPoint( count, clipped, best, eClipCullNone );
794         }
795 }
796
797 void LineLoop_BestPoint( const Matrix4& local2view, const PointVertex* vertices, const std::size_t size, SelectionIntersection& best ){
798         Vector4 clipped[2];
799         for ( std::size_t i = 0; i < size; ++i )
800         {
801                 const std::size_t count = matrix4_clip_line( local2view, vertex3f_to_vector3( vertices[i].vertex ), vertex3f_to_vector3( vertices[( i + 1 ) % size].vertex ), clipped );
802                 BestPoint( count, clipped, best, eClipCullNone );
803         }
804 }
805
806 void Line_BestPoint( const Matrix4& local2view, const PointVertex vertices[2], SelectionIntersection& best ){
807         Vector4 clipped[2];
808         const std::size_t count = matrix4_clip_line( local2view, vertex3f_to_vector3( vertices[0].vertex ), vertex3f_to_vector3( vertices[1].vertex ), clipped );
809         BestPoint( count, clipped, best, eClipCullNone );
810 }
811
812 void Circle_BestPoint( const Matrix4& local2view, clipcull_t cull, const PointVertex* vertices, const std::size_t size, SelectionIntersection& best ){
813         Vector4 clipped[9];
814         for ( std::size_t i = 0; i < size; ++i )
815         {
816                 const std::size_t count = matrix4_clip_triangle( local2view, g_vector3_identity, vertex3f_to_vector3( vertices[i].vertex ), vertex3f_to_vector3( vertices[( i + 1 ) % size].vertex ), clipped );
817                 BestPoint( count, clipped, best, cull );
818         }
819 }
820
821 void Quad_BestPoint( const Matrix4& local2view, clipcull_t cull, const PointVertex* vertices, SelectionIntersection& best ){
822         Vector4 clipped[9];
823         {
824                 const std::size_t count = matrix4_clip_triangle( local2view, vertex3f_to_vector3( vertices[0].vertex ), vertex3f_to_vector3( vertices[1].vertex ), vertex3f_to_vector3( vertices[3].vertex ), clipped );
825                 BestPoint( count, clipped, best, cull );
826         }
827         {
828                 const std::size_t count = matrix4_clip_triangle( local2view, vertex3f_to_vector3( vertices[1].vertex ), vertex3f_to_vector3( vertices[2].vertex ), vertex3f_to_vector3( vertices[3].vertex ), clipped );
829                 BestPoint( count, clipped, best, cull );
830         }
831 }
832
833 struct FlatShadedVertex
834 {
835         Vertex3f vertex;
836         Colour4b colour;
837         Normal3f normal;
838
839         FlatShadedVertex(){
840         }
841 };
842
843
844 typedef FlatShadedVertex* FlatShadedVertexIterator;
845 void Triangles_BestPoint( const Matrix4& local2view, clipcull_t cull, FlatShadedVertexIterator first, FlatShadedVertexIterator last, SelectionIntersection& best ){
846         for ( FlatShadedVertexIterator x( first ), y( first + 1 ), z( first + 2 ); x != last; x += 3, y += 3, z += 3 )
847         {
848                 Vector4 clipped[9];
849                 BestPoint(
850                         matrix4_clip_triangle(
851                                 local2view,
852                                 reinterpret_cast<const Vector3&>( ( *x ).vertex ),
853                                 reinterpret_cast<const Vector3&>( ( *y ).vertex ),
854                                 reinterpret_cast<const Vector3&>( ( *z ).vertex ),
855                                 clipped
856                                 ),
857                         clipped,
858                         best,
859                         cull
860                         );
861         }
862 }
863
864
865 typedef std::multimap<SelectionIntersection, Selectable*> SelectableSortedSet;
866
867 class SelectionPool : public Selector
868 {
869 SelectableSortedSet m_pool;
870 SelectionIntersection m_intersection;
871 Selectable* m_selectable;
872
873 public:
874 void pushSelectable( Selectable& selectable ){
875         m_intersection = SelectionIntersection();
876         m_selectable = &selectable;
877 }
878 void popSelectable(){
879         addSelectable( m_intersection, m_selectable );
880         m_intersection = SelectionIntersection();
881 }
882 void addIntersection( const SelectionIntersection& intersection ){
883         assign_if_closer( m_intersection, intersection );
884 }
885 void addSelectable( const SelectionIntersection& intersection, Selectable* selectable ){
886         if ( intersection.valid() ) {
887                 m_pool.insert( SelectableSortedSet::value_type( intersection, selectable ) );
888         }
889 }
890
891 typedef SelectableSortedSet::iterator iterator;
892
893 iterator begin(){
894         return m_pool.begin();
895 }
896 iterator end(){
897         return m_pool.end();
898 }
899
900 bool failed(){
901         return m_pool.empty();
902 }
903 };
904
905
906 const Colour4b g_colour_sphere( 0, 0, 0, 255 );
907 const Colour4b g_colour_screen( 0, 255, 255, 255 );
908 const Colour4b g_colour_selected( 255, 255, 0, 255 );
909
910 inline const Colour4b& colourSelected( const Colour4b& colour, bool selected ){
911         return ( selected ) ? g_colour_selected : colour;
912 }
913
914 template<typename remap_policy>
915 inline void draw_semicircle( const std::size_t segments, const float radius, PointVertex* vertices, remap_policy remap ){
916         const double increment = c_pi / double(segments << 2);
917
918         std::size_t count = 0;
919         float x = radius;
920         float y = 0;
921         remap_policy::set( vertices[segments << 2].vertex, -radius, 0, 0 );
922         while ( count < segments )
923         {
924                 PointVertex* i = vertices + count;
925                 PointVertex* j = vertices + ( ( segments << 1 ) - ( count + 1 ) );
926
927                 PointVertex* k = i + ( segments << 1 );
928                 PointVertex* l = j + ( segments << 1 );
929
930 #if 0
931                 PointVertex* m = i + ( segments << 2 );
932                 PointVertex* n = j + ( segments << 2 );
933                 PointVertex* o = k + ( segments << 2 );
934                 PointVertex* p = l + ( segments << 2 );
935 #endif
936
937                 remap_policy::set( i->vertex, x,-y, 0 );
938                 remap_policy::set( k->vertex,-y,-x, 0 );
939 #if 0
940                 remap_policy::set( m->vertex,-x, y, 0 );
941                 remap_policy::set( o->vertex, y, x, 0 );
942 #endif
943
944                 ++count;
945
946                 {
947                         const double theta = increment * count;
948                         x = static_cast<float>( radius * cos( theta ) );
949                         y = static_cast<float>( radius * sin( theta ) );
950                 }
951
952                 remap_policy::set( j->vertex, y,-x, 0 );
953                 remap_policy::set( l->vertex,-x,-y, 0 );
954 #if 0
955                 remap_policy::set( n->vertex,-y, x, 0 );
956                 remap_policy::set( p->vertex, x, y, 0 );
957 #endif
958         }
959 }
960
961 class Manipulator
962 {
963 public:
964 virtual Manipulatable* GetManipulatable() = 0;
965 virtual void testSelect( const View& view, const Matrix4& pivot2world ){
966 }
967 virtual void render( Renderer& renderer, const VolumeTest& volume, const Matrix4& pivot2world ){
968 }
969 virtual void setSelected( bool select ) = 0;
970 virtual bool isSelected() const = 0;
971 };
972
973
974 inline Vector3 normalised_safe( const Vector3& self ){
975         if ( vector3_equal( self, g_vector3_identity ) ) {
976                 return g_vector3_identity;
977         }
978         return vector3_normalised( self );
979 }
980
981
982 class RotateManipulator : public Manipulator
983 {
984 struct RenderableCircle : public OpenGLRenderable
985 {
986         Array<PointVertex> m_vertices;
987
988         RenderableCircle( std::size_t size ) : m_vertices( size ){
989         }
990         void render( RenderStateFlags state ) const {
991                 glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( PointVertex ), &m_vertices.data()->colour );
992                 glVertexPointer( 3, GL_FLOAT, sizeof( PointVertex ), &m_vertices.data()->vertex );
993                 glDrawArrays( GL_LINE_LOOP, 0, GLsizei( m_vertices.size() ) );
994         }
995         void setColour( const Colour4b& colour ){
996                 for ( Array<PointVertex>::iterator i = m_vertices.begin(); i != m_vertices.end(); ++i )
997                 {
998                         ( *i ).colour = colour;
999                 }
1000         }
1001 };
1002
1003 struct RenderableSemiCircle : public OpenGLRenderable
1004 {
1005         Array<PointVertex> m_vertices;
1006
1007         RenderableSemiCircle( std::size_t size ) : m_vertices( size ){
1008         }
1009         void render( RenderStateFlags state ) const {
1010                 glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( PointVertex ), &m_vertices.data()->colour );
1011                 glVertexPointer( 3, GL_FLOAT, sizeof( PointVertex ), &m_vertices.data()->vertex );
1012                 glDrawArrays( GL_LINE_STRIP, 0, GLsizei( m_vertices.size() ) );
1013         }
1014         void setColour( const Colour4b& colour ){
1015                 for ( Array<PointVertex>::iterator i = m_vertices.begin(); i != m_vertices.end(); ++i )
1016                 {
1017                         ( *i ).colour = colour;
1018                 }
1019         }
1020 };
1021
1022 RotateFree m_free;
1023 RotateAxis m_axis;
1024 Vector3 m_axis_screen;
1025 RenderableSemiCircle m_circle_x;
1026 RenderableSemiCircle m_circle_y;
1027 RenderableSemiCircle m_circle_z;
1028 RenderableCircle m_circle_screen;
1029 RenderableCircle m_circle_sphere;
1030 SelectableBool m_selectable_x;
1031 SelectableBool m_selectable_y;
1032 SelectableBool m_selectable_z;
1033 SelectableBool m_selectable_screen;
1034 SelectableBool m_selectable_sphere;
1035 Pivot2World m_pivot;
1036 Matrix4 m_local2world_x;
1037 Matrix4 m_local2world_y;
1038 Matrix4 m_local2world_z;
1039 bool m_circle_x_visible;
1040 bool m_circle_y_visible;
1041 bool m_circle_z_visible;
1042 public:
1043 static Shader* m_state_outer;
1044
1045 RotateManipulator( Rotatable& rotatable, std::size_t segments, float radius ) :
1046         m_free( rotatable ),
1047         m_axis( rotatable ),
1048         m_circle_x( ( segments << 2 ) + 1 ),
1049         m_circle_y( ( segments << 2 ) + 1 ),
1050         m_circle_z( ( segments << 2 ) + 1 ),
1051         m_circle_screen( segments << 3 ),
1052         m_circle_sphere( segments << 3 ){
1053         draw_semicircle( segments, radius, m_circle_x.m_vertices.data(), RemapYZX() );
1054         draw_semicircle( segments, radius, m_circle_y.m_vertices.data(), RemapZXY() );
1055         draw_semicircle( segments, radius, m_circle_z.m_vertices.data(), RemapXYZ() );
1056
1057         draw_circle( segments, radius * 1.15f, m_circle_screen.m_vertices.data(), RemapXYZ() );
1058         draw_circle( segments, radius, m_circle_sphere.m_vertices.data(), RemapXYZ() );
1059
1060         m_selectable_sphere.setSelected( true );
1061 }
1062
1063
1064 void UpdateColours(){
1065         m_circle_x.setColour( colourSelected( g_colour_x, m_selectable_x.isSelected() ) );
1066         m_circle_y.setColour( colourSelected( g_colour_y, m_selectable_y.isSelected() ) );
1067         m_circle_z.setColour( colourSelected( g_colour_z, m_selectable_z.isSelected() ) );
1068         m_circle_screen.setColour( colourSelected( g_colour_screen, m_selectable_screen.isSelected() ) );
1069         m_circle_sphere.setColour( colourSelected( g_colour_sphere, false ) );
1070 }
1071
1072 void updateCircleTransforms(){
1073         Vector3 localViewpoint( matrix4_transformed_direction( matrix4_transposed( m_pivot.m_worldSpace ), vector4_to_vector3( m_pivot.m_viewpointSpace.z() ) ) );
1074
1075         m_circle_x_visible = !vector3_equal_epsilon( g_vector3_axis_x, localViewpoint, 1e-6f );
1076         if ( m_circle_x_visible ) {
1077                 m_local2world_x = g_matrix4_identity;
1078                 vector4_to_vector3( m_local2world_x.y() ) = normalised_safe(
1079                         vector3_cross( g_vector3_axis_x, localViewpoint )
1080                         );
1081                 vector4_to_vector3( m_local2world_x.z() ) = normalised_safe(
1082                         vector3_cross( vector4_to_vector3( m_local2world_x.x() ), vector4_to_vector3( m_local2world_x.y() ) )
1083                         );
1084                 matrix4_premultiply_by_matrix4( m_local2world_x, m_pivot.m_worldSpace );
1085         }
1086
1087         m_circle_y_visible = !vector3_equal_epsilon( g_vector3_axis_y, localViewpoint, 1e-6f );
1088         if ( m_circle_y_visible ) {
1089                 m_local2world_y = g_matrix4_identity;
1090                 vector4_to_vector3( m_local2world_y.z() ) = normalised_safe(
1091                         vector3_cross( g_vector3_axis_y, localViewpoint )
1092                         );
1093                 vector4_to_vector3( m_local2world_y.x() ) = normalised_safe(
1094                         vector3_cross( vector4_to_vector3( m_local2world_y.y() ), vector4_to_vector3( m_local2world_y.z() ) )
1095                         );
1096                 matrix4_premultiply_by_matrix4( m_local2world_y, m_pivot.m_worldSpace );
1097         }
1098
1099         m_circle_z_visible = !vector3_equal_epsilon( g_vector3_axis_z, localViewpoint, 1e-6f );
1100         if ( m_circle_z_visible ) {
1101                 m_local2world_z = g_matrix4_identity;
1102                 vector4_to_vector3( m_local2world_z.x() ) = normalised_safe(
1103                         vector3_cross( g_vector3_axis_z, localViewpoint )
1104                         );
1105                 vector4_to_vector3( m_local2world_z.y() ) = normalised_safe(
1106                         vector3_cross( vector4_to_vector3( m_local2world_z.z() ), vector4_to_vector3( m_local2world_z.x() ) )
1107                         );
1108                 matrix4_premultiply_by_matrix4( m_local2world_z, m_pivot.m_worldSpace );
1109         }
1110 }
1111
1112 void render( Renderer& renderer, const VolumeTest& volume, const Matrix4& pivot2world ){
1113         m_pivot.update( pivot2world, volume.GetModelview(), volume.GetProjection(), volume.GetViewport() );
1114         updateCircleTransforms();
1115
1116         // temp hack
1117         UpdateColours();
1118
1119         renderer.SetState( m_state_outer, Renderer::eWireframeOnly );
1120         renderer.SetState( m_state_outer, Renderer::eFullMaterials );
1121
1122         renderer.addRenderable( m_circle_screen, m_pivot.m_viewpointSpace );
1123         renderer.addRenderable( m_circle_sphere, m_pivot.m_viewpointSpace );
1124
1125         if ( m_circle_x_visible ) {
1126                 renderer.addRenderable( m_circle_x, m_local2world_x );
1127         }
1128         if ( m_circle_y_visible ) {
1129                 renderer.addRenderable( m_circle_y, m_local2world_y );
1130         }
1131         if ( m_circle_z_visible ) {
1132                 renderer.addRenderable( m_circle_z, m_local2world_z );
1133         }
1134 }
1135 void testSelect( const View& view, const Matrix4& pivot2world ){
1136         m_pivot.update( pivot2world, view.GetModelview(), view.GetProjection(), view.GetViewport() );
1137         updateCircleTransforms();
1138
1139         SelectionPool selector;
1140
1141         {
1142                 {
1143                         Matrix4 local2view( matrix4_multiplied_by_matrix4( view.GetViewMatrix(), m_local2world_x ) );
1144
1145 #if defined( DEBUG_SELECTION )
1146                         g_render_clipped.construct( view.GetViewMatrix() );
1147 #endif
1148
1149                         SelectionIntersection best;
1150                         LineStrip_BestPoint( local2view, m_circle_x.m_vertices.data(), m_circle_x.m_vertices.size(), best );
1151                         selector.addSelectable( best, &m_selectable_x );
1152                 }
1153
1154                 {
1155                         Matrix4 local2view( matrix4_multiplied_by_matrix4( view.GetViewMatrix(), m_local2world_y ) );
1156
1157 #if defined( DEBUG_SELECTION )
1158                         g_render_clipped.construct( view.GetViewMatrix() );
1159 #endif
1160
1161                         SelectionIntersection best;
1162                         LineStrip_BestPoint( local2view, m_circle_y.m_vertices.data(), m_circle_y.m_vertices.size(), best );
1163                         selector.addSelectable( best, &m_selectable_y );
1164                 }
1165
1166                 {
1167                         Matrix4 local2view( matrix4_multiplied_by_matrix4( view.GetViewMatrix(), m_local2world_z ) );
1168
1169 #if defined( DEBUG_SELECTION )
1170                         g_render_clipped.construct( view.GetViewMatrix() );
1171 #endif
1172
1173                         SelectionIntersection best;
1174                         LineStrip_BestPoint( local2view, m_circle_z.m_vertices.data(), m_circle_z.m_vertices.size(), best );
1175                         selector.addSelectable( best, &m_selectable_z );
1176                 }
1177         }
1178
1179         {
1180                 Matrix4 local2view( matrix4_multiplied_by_matrix4( view.GetViewMatrix(), m_pivot.m_viewpointSpace ) );
1181
1182                 {
1183                         SelectionIntersection best;
1184                         LineLoop_BestPoint( local2view, m_circle_screen.m_vertices.data(), m_circle_screen.m_vertices.size(), best );
1185                         selector.addSelectable( best, &m_selectable_screen );
1186                 }
1187
1188                 {
1189                         SelectionIntersection best;
1190                         Circle_BestPoint( local2view, eClipCullCW, m_circle_sphere.m_vertices.data(), m_circle_sphere.m_vertices.size(), best );
1191                         selector.addSelectable( best, &m_selectable_sphere );
1192                 }
1193         }
1194
1195         m_axis_screen = m_pivot.m_axis_screen;
1196
1197         if ( !selector.failed() ) {
1198                 ( *selector.begin() ).second->setSelected( true );
1199         }
1200 }
1201
1202 Manipulatable* GetManipulatable(){
1203         if ( m_selectable_x.isSelected() ) {
1204                 m_axis.SetAxis( g_vector3_axis_x );
1205                 return &m_axis;
1206         }
1207         else if ( m_selectable_y.isSelected() ) {
1208                 m_axis.SetAxis( g_vector3_axis_y );
1209                 return &m_axis;
1210         }
1211         else if ( m_selectable_z.isSelected() ) {
1212                 m_axis.SetAxis( g_vector3_axis_z );
1213                 return &m_axis;
1214         }
1215         else if ( m_selectable_screen.isSelected() ) {
1216                 m_axis.SetAxis( m_axis_screen );
1217                 return &m_axis;
1218         }
1219         else{
1220                 return &m_free;
1221         }
1222 }
1223
1224 void setSelected( bool select ){
1225         m_selectable_x.setSelected( select );
1226         m_selectable_y.setSelected( select );
1227         m_selectable_z.setSelected( select );
1228         m_selectable_screen.setSelected( select );
1229 }
1230 bool isSelected() const {
1231         return m_selectable_x.isSelected()
1232                    | m_selectable_y.isSelected()
1233                    | m_selectable_z.isSelected()
1234                    | m_selectable_screen.isSelected()
1235                    | m_selectable_sphere.isSelected();
1236 }
1237 };
1238
1239 Shader* RotateManipulator::m_state_outer;
1240
1241
1242 const float arrowhead_length = 16;
1243 const float arrowhead_radius = 4;
1244
1245 inline void draw_arrowline( const float length, PointVertex* line, const std::size_t axis ){
1246         ( *line++ ).vertex = vertex3f_identity;
1247         ( *line ).vertex = vertex3f_identity;
1248         vertex3f_to_array( ( *line ).vertex )[axis] = length - arrowhead_length;
1249 }
1250
1251 template<typename VertexRemap, typename NormalRemap>
1252 inline void draw_arrowhead( const std::size_t segments, const float length, FlatShadedVertex* vertices, VertexRemap, NormalRemap ){
1253         std::size_t head_tris = ( segments << 3 );
1254         const double head_segment = c_2pi / head_tris;
1255         for ( std::size_t i = 0; i < head_tris; ++i )
1256         {
1257                 {
1258                         FlatShadedVertex& point = vertices[i * 6 + 0];
1259                         VertexRemap::x( point.vertex ) = length - arrowhead_length;
1260                         VertexRemap::y( point.vertex ) = arrowhead_radius * static_cast<float>( cos( i * head_segment ) );
1261                         VertexRemap::z( point.vertex ) = arrowhead_radius * static_cast<float>( sin( i * head_segment ) );
1262                         NormalRemap::x( point.normal ) = arrowhead_radius / arrowhead_length;
1263                         NormalRemap::y( point.normal ) = static_cast<float>( cos( i * head_segment ) );
1264                         NormalRemap::z( point.normal ) = static_cast<float>( sin( i * head_segment ) );
1265                 }
1266                 {
1267                         FlatShadedVertex& point = vertices[i * 6 + 1];
1268                         VertexRemap::x( point.vertex ) = length;
1269                         VertexRemap::y( point.vertex ) = 0;
1270                         VertexRemap::z( point.vertex ) = 0;
1271                         NormalRemap::x( point.normal ) = arrowhead_radius / arrowhead_length;
1272                         NormalRemap::y( point.normal ) = static_cast<float>( cos( ( i + 0.5 ) * head_segment ) );
1273                         NormalRemap::z( point.normal ) = static_cast<float>( sin( ( i + 0.5 ) * head_segment ) );
1274                 }
1275                 {
1276                         FlatShadedVertex& point = vertices[i * 6 + 2];
1277                         VertexRemap::x( point.vertex ) = length - arrowhead_length;
1278                         VertexRemap::y( point.vertex ) = arrowhead_radius * static_cast<float>( cos( ( i + 1 ) * head_segment ) );
1279                         VertexRemap::z( point.vertex ) = arrowhead_radius * static_cast<float>( sin( ( i + 1 ) * head_segment ) );
1280                         NormalRemap::x( point.normal ) = arrowhead_radius / arrowhead_length;
1281                         NormalRemap::y( point.normal ) = static_cast<float>( cos( ( i + 1 ) * head_segment ) );
1282                         NormalRemap::z( point.normal ) = static_cast<float>( sin( ( i + 1 ) * head_segment ) );
1283                 }
1284
1285                 {
1286                         FlatShadedVertex& point = vertices[i * 6 + 3];
1287                         VertexRemap::x( point.vertex ) = length - arrowhead_length;
1288                         VertexRemap::y( point.vertex ) = 0;
1289                         VertexRemap::z( point.vertex ) = 0;
1290                         NormalRemap::x( point.normal ) = -1;
1291                         NormalRemap::y( point.normal ) = 0;
1292                         NormalRemap::z( point.normal ) = 0;
1293                 }
1294                 {
1295                         FlatShadedVertex& point = vertices[i * 6 + 4];
1296                         VertexRemap::x( point.vertex ) = length - arrowhead_length;
1297                         VertexRemap::y( point.vertex ) = arrowhead_radius * static_cast<float>( cos( i * head_segment ) );
1298                         VertexRemap::z( point.vertex ) = arrowhead_radius * static_cast<float>( sin( i * head_segment ) );
1299                         NormalRemap::x( point.normal ) = -1;
1300                         NormalRemap::y( point.normal ) = 0;
1301                         NormalRemap::z( point.normal ) = 0;
1302                 }
1303                 {
1304                         FlatShadedVertex& point = vertices[i * 6 + 5];
1305                         VertexRemap::x( point.vertex ) = length - arrowhead_length;
1306                         VertexRemap::y( point.vertex ) = arrowhead_radius * static_cast<float>( cos( ( i + 1 ) * head_segment ) );
1307                         VertexRemap::z( point.vertex ) = arrowhead_radius * static_cast<float>( sin( ( i + 1 ) * head_segment ) );
1308                         NormalRemap::x( point.normal ) = -1;
1309                         NormalRemap::y( point.normal ) = 0;
1310                         NormalRemap::z( point.normal ) = 0;
1311                 }
1312         }
1313 }
1314
1315 template<typename Triple>
1316 class TripleRemapXYZ
1317 {
1318 public:
1319 static float& x( Triple& triple ){
1320         return triple.x();
1321 }
1322 static float& y( Triple& triple ){
1323         return triple.y();
1324 }
1325 static float& z( Triple& triple ){
1326         return triple.z();
1327 }
1328 };
1329
1330 template<typename Triple>
1331 class TripleRemapYZX
1332 {
1333 public:
1334 static float& x( Triple& triple ){
1335         return triple.y();
1336 }
1337 static float& y( Triple& triple ){
1338         return triple.z();
1339 }
1340 static float& z( Triple& triple ){
1341         return triple.x();
1342 }
1343 };
1344
1345 template<typename Triple>
1346 class TripleRemapZXY
1347 {
1348 public:
1349 static float& x( Triple& triple ){
1350         return triple.z();
1351 }
1352 static float& y( Triple& triple ){
1353         return triple.x();
1354 }
1355 static float& z( Triple& triple ){
1356         return triple.y();
1357 }
1358 };
1359
1360 void vector3_print( const Vector3& v ){
1361         globalOutputStream() << "( " << v.x() << " " << v.y() << " " << v.z() << " )";
1362 }
1363
1364 class TranslateManipulator : public Manipulator
1365 {
1366 struct RenderableArrowLine : public OpenGLRenderable
1367 {
1368         PointVertex m_line[2];
1369
1370         RenderableArrowLine(){
1371         }
1372         void render( RenderStateFlags state ) const {
1373                 glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( PointVertex ), &m_line[0].colour );
1374                 glVertexPointer( 3, GL_FLOAT, sizeof( PointVertex ), &m_line[0].vertex );
1375                 glDrawArrays( GL_LINES, 0, 2 );
1376         }
1377         void setColour( const Colour4b& colour ){
1378                 m_line[0].colour = colour;
1379                 m_line[1].colour = colour;
1380         }
1381 };
1382 struct RenderableArrowHead : public OpenGLRenderable
1383 {
1384         Array<FlatShadedVertex> m_vertices;
1385
1386         RenderableArrowHead( std::size_t size )
1387                 : m_vertices( size ){
1388         }
1389         void render( RenderStateFlags state ) const {
1390                 glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( FlatShadedVertex ), &m_vertices.data()->colour );
1391                 glVertexPointer( 3, GL_FLOAT, sizeof( FlatShadedVertex ), &m_vertices.data()->vertex );
1392                 glNormalPointer( GL_FLOAT, sizeof( FlatShadedVertex ), &m_vertices.data()->normal );
1393                 glDrawArrays( GL_TRIANGLES, 0, GLsizei( m_vertices.size() ) );
1394         }
1395         void setColour( const Colour4b& colour ){
1396                 for ( Array<FlatShadedVertex>::iterator i = m_vertices.begin(); i != m_vertices.end(); ++i )
1397                 {
1398                         ( *i ).colour = colour;
1399                 }
1400         }
1401 };
1402 struct RenderableQuad : public OpenGLRenderable
1403 {
1404         PointVertex m_quad[4];
1405         void render( RenderStateFlags state ) const {
1406                 glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( PointVertex ), &m_quad[0].colour );
1407                 glVertexPointer( 3, GL_FLOAT, sizeof( PointVertex ), &m_quad[0].vertex );
1408                 glDrawArrays( GL_LINE_LOOP, 0, 4 );
1409         }
1410         void setColour( const Colour4b& colour ){
1411                 m_quad[0].colour = colour;
1412                 m_quad[1].colour = colour;
1413                 m_quad[2].colour = colour;
1414                 m_quad[3].colour = colour;
1415         }
1416 };
1417
1418 TranslateFree m_free;
1419 TranslateAxis m_axis;
1420 RenderableArrowLine m_arrow_x;
1421 RenderableArrowLine m_arrow_y;
1422 RenderableArrowLine m_arrow_z;
1423 RenderableArrowHead m_arrow_head_x;
1424 RenderableArrowHead m_arrow_head_y;
1425 RenderableArrowHead m_arrow_head_z;
1426 RenderableQuad m_quad_screen;
1427 SelectableBool m_selectable_x;
1428 SelectableBool m_selectable_y;
1429 SelectableBool m_selectable_z;
1430 SelectableBool m_selectable_screen;
1431 Pivot2World m_pivot;
1432 public:
1433 static Shader* m_state_wire;
1434 static Shader* m_state_fill;
1435
1436 TranslateManipulator( Translatable& translatable, std::size_t segments, float length ) :
1437         m_free( translatable ),
1438         m_axis( translatable ),
1439         m_arrow_head_x( 3 * 2 * ( segments << 3 ) ),
1440         m_arrow_head_y( 3 * 2 * ( segments << 3 ) ),
1441         m_arrow_head_z( 3 * 2 * ( segments << 3 ) ){
1442         draw_arrowline( length, m_arrow_x.m_line, 0 );
1443         draw_arrowhead( segments, length, m_arrow_head_x.m_vertices.data(), TripleRemapXYZ<Vertex3f>(), TripleRemapXYZ<Normal3f>() );
1444         draw_arrowline( length, m_arrow_y.m_line, 1 );
1445         draw_arrowhead( segments, length, m_arrow_head_y.m_vertices.data(), TripleRemapYZX<Vertex3f>(), TripleRemapYZX<Normal3f>() );
1446         draw_arrowline( length, m_arrow_z.m_line, 2 );
1447         draw_arrowhead( segments, length, m_arrow_head_z.m_vertices.data(), TripleRemapZXY<Vertex3f>(), TripleRemapZXY<Normal3f>() );
1448
1449         draw_quad( 16, m_quad_screen.m_quad );
1450 }
1451
1452 void UpdateColours(){
1453         m_arrow_x.setColour( colourSelected( g_colour_x, m_selectable_x.isSelected() ) );
1454         m_arrow_head_x.setColour( colourSelected( g_colour_x, m_selectable_x.isSelected() ) );
1455         m_arrow_y.setColour( colourSelected( g_colour_y, m_selectable_y.isSelected() ) );
1456         m_arrow_head_y.setColour( colourSelected( g_colour_y, m_selectable_y.isSelected() ) );
1457         m_arrow_z.setColour( colourSelected( g_colour_z, m_selectable_z.isSelected() ) );
1458         m_arrow_head_z.setColour( colourSelected( g_colour_z, m_selectable_z.isSelected() ) );
1459         m_quad_screen.setColour( colourSelected( g_colour_screen, m_selectable_screen.isSelected() ) );
1460 }
1461
1462 bool manipulator_show_axis( const Pivot2World& pivot, const Vector3& axis ){
1463         return fabs( vector3_dot( pivot.m_axis_screen, axis ) ) < 0.95;
1464 }
1465
1466 void render( Renderer& renderer, const VolumeTest& volume, const Matrix4& pivot2world ){
1467         m_pivot.update( pivot2world, volume.GetModelview(), volume.GetProjection(), volume.GetViewport() );
1468
1469         // temp hack
1470         UpdateColours();
1471
1472         Vector3 x = vector3_normalised( vector4_to_vector3( m_pivot.m_worldSpace.x() ) );
1473         bool show_x = manipulator_show_axis( m_pivot, x );
1474
1475         Vector3 y = vector3_normalised( vector4_to_vector3( m_pivot.m_worldSpace.y() ) );
1476         bool show_y = manipulator_show_axis( m_pivot, y );
1477
1478         Vector3 z = vector3_normalised( vector4_to_vector3( m_pivot.m_worldSpace.z() ) );
1479         bool show_z = manipulator_show_axis( m_pivot, z );
1480
1481         renderer.SetState( m_state_wire, Renderer::eWireframeOnly );
1482         renderer.SetState( m_state_wire, Renderer::eFullMaterials );
1483
1484         if ( show_x ) {
1485                 renderer.addRenderable( m_arrow_x, m_pivot.m_worldSpace );
1486         }
1487         if ( show_y ) {
1488                 renderer.addRenderable( m_arrow_y, m_pivot.m_worldSpace );
1489         }
1490         if ( show_z ) {
1491                 renderer.addRenderable( m_arrow_z, m_pivot.m_worldSpace );
1492         }
1493
1494         renderer.addRenderable( m_quad_screen, m_pivot.m_viewplaneSpace );
1495
1496         renderer.SetState( m_state_fill, Renderer::eWireframeOnly );
1497         renderer.SetState( m_state_fill, Renderer::eFullMaterials );
1498
1499         if ( show_x ) {
1500                 renderer.addRenderable( m_arrow_head_x, m_pivot.m_worldSpace );
1501         }
1502         if ( show_y ) {
1503                 renderer.addRenderable( m_arrow_head_y, m_pivot.m_worldSpace );
1504         }
1505         if ( show_z ) {
1506                 renderer.addRenderable( m_arrow_head_z, m_pivot.m_worldSpace );
1507         }
1508 }
1509 void testSelect( const View& view, const Matrix4& pivot2world ){
1510         m_pivot.update( pivot2world, view.GetModelview(), view.GetProjection(), view.GetViewport() );
1511
1512         SelectionPool selector;
1513
1514         Vector3 x = vector3_normalised( vector4_to_vector3( m_pivot.m_worldSpace.x() ) );
1515         bool show_x = manipulator_show_axis( m_pivot, x );
1516
1517         Vector3 y = vector3_normalised( vector4_to_vector3( m_pivot.m_worldSpace.y() ) );
1518         bool show_y = manipulator_show_axis( m_pivot, y );
1519
1520         Vector3 z = vector3_normalised( vector4_to_vector3( m_pivot.m_worldSpace.z() ) );
1521         bool show_z = manipulator_show_axis( m_pivot, z );
1522
1523         {
1524                 Matrix4 local2view( matrix4_multiplied_by_matrix4( view.GetViewMatrix(), m_pivot.m_viewpointSpace ) );
1525
1526                 {
1527                         SelectionIntersection best;
1528                         Quad_BestPoint( local2view, eClipCullCW, m_quad_screen.m_quad, best );
1529                         if ( best.valid() ) {
1530                                 best = SelectionIntersection( 0, 0 );
1531                                 selector.addSelectable( best, &m_selectable_screen );
1532                         }
1533                 }
1534         }
1535
1536         {
1537                 Matrix4 local2view( matrix4_multiplied_by_matrix4( view.GetViewMatrix(), m_pivot.m_worldSpace ) );
1538
1539 #if defined( DEBUG_SELECTION )
1540                 g_render_clipped.construct( view.GetViewMatrix() );
1541 #endif
1542
1543                 if ( show_x ) {
1544                         SelectionIntersection best;
1545                         Line_BestPoint( local2view, m_arrow_x.m_line, best );
1546                         Triangles_BestPoint( local2view, eClipCullCW, m_arrow_head_x.m_vertices.begin(), m_arrow_head_x.m_vertices.end(), best );
1547                         selector.addSelectable( best, &m_selectable_x );
1548                 }
1549
1550                 if ( show_y ) {
1551                         SelectionIntersection best;
1552                         Line_BestPoint( local2view, m_arrow_y.m_line, best );
1553                         Triangles_BestPoint( local2view, eClipCullCW, m_arrow_head_y.m_vertices.begin(), m_arrow_head_y.m_vertices.end(), best );
1554                         selector.addSelectable( best, &m_selectable_y );
1555                 }
1556
1557                 if ( show_z ) {
1558                         SelectionIntersection best;
1559                         Line_BestPoint( local2view, m_arrow_z.m_line, best );
1560                         Triangles_BestPoint( local2view, eClipCullCW, m_arrow_head_z.m_vertices.begin(), m_arrow_head_z.m_vertices.end(), best );
1561                         selector.addSelectable( best, &m_selectable_z );
1562                 }
1563         }
1564
1565         if ( !selector.failed() ) {
1566                 ( *selector.begin() ).second->setSelected( true );
1567         }
1568 }
1569
1570 Manipulatable* GetManipulatable(){
1571         if ( m_selectable_x.isSelected() ) {
1572                 m_axis.SetAxis( g_vector3_axis_x );
1573                 return &m_axis;
1574         }
1575         else if ( m_selectable_y.isSelected() ) {
1576                 m_axis.SetAxis( g_vector3_axis_y );
1577                 return &m_axis;
1578         }
1579         else if ( m_selectable_z.isSelected() ) {
1580                 m_axis.SetAxis( g_vector3_axis_z );
1581                 return &m_axis;
1582         }
1583         else
1584         {
1585                 return &m_free;
1586         }
1587 }
1588
1589 void setSelected( bool select ){
1590         m_selectable_x.setSelected( select );
1591         m_selectable_y.setSelected( select );
1592         m_selectable_z.setSelected( select );
1593         m_selectable_screen.setSelected( select );
1594 }
1595 bool isSelected() const {
1596         return m_selectable_x.isSelected()
1597                    | m_selectable_y.isSelected()
1598                    | m_selectable_z.isSelected()
1599                    | m_selectable_screen.isSelected();
1600 }
1601 };
1602
1603 Shader* TranslateManipulator::m_state_wire;
1604 Shader* TranslateManipulator::m_state_fill;
1605
1606 class ScaleManipulator : public Manipulator
1607 {
1608 struct RenderableArrow : public OpenGLRenderable
1609 {
1610         PointVertex m_line[2];
1611
1612         void render( RenderStateFlags state ) const {
1613                 glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( PointVertex ), &m_line[0].colour );
1614                 glVertexPointer( 3, GL_FLOAT, sizeof( PointVertex ), &m_line[0].vertex );
1615                 glDrawArrays( GL_LINES, 0, 2 );
1616         }
1617         void setColour( const Colour4b& colour ){
1618                 m_line[0].colour = colour;
1619                 m_line[1].colour = colour;
1620         }
1621 };
1622 struct RenderableQuad : public OpenGLRenderable
1623 {
1624         PointVertex m_quad[4];
1625         void render( RenderStateFlags state ) const {
1626                 glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( PointVertex ), &m_quad[0].colour );
1627                 glVertexPointer( 3, GL_FLOAT, sizeof( PointVertex ), &m_quad[0].vertex );
1628                 glDrawArrays( GL_QUADS, 0, 4 );
1629         }
1630         void setColour( const Colour4b& colour ){
1631                 m_quad[0].colour = colour;
1632                 m_quad[1].colour = colour;
1633                 m_quad[2].colour = colour;
1634                 m_quad[3].colour = colour;
1635         }
1636 };
1637
1638 ScaleFree m_free;
1639 ScaleAxis m_axis;
1640 RenderableArrow m_arrow_x;
1641 RenderableArrow m_arrow_y;
1642 RenderableArrow m_arrow_z;
1643 RenderableQuad m_quad_screen;
1644 SelectableBool m_selectable_x;
1645 SelectableBool m_selectable_y;
1646 SelectableBool m_selectable_z;
1647 SelectableBool m_selectable_screen;
1648 Pivot2World m_pivot;
1649 public:
1650 ScaleManipulator( Scalable& scalable, std::size_t segments, float length ) :
1651         m_free( scalable ),
1652         m_axis( scalable ){
1653         draw_arrowline( length, m_arrow_x.m_line, 0 );
1654         draw_arrowline( length, m_arrow_y.m_line, 1 );
1655         draw_arrowline( length, m_arrow_z.m_line, 2 );
1656
1657         draw_quad( 16, m_quad_screen.m_quad );
1658 }
1659
1660 Pivot2World& getPivot(){
1661         return m_pivot;
1662 }
1663
1664 void UpdateColours(){
1665         m_arrow_x.setColour( colourSelected( g_colour_x, m_selectable_x.isSelected() ) );
1666         m_arrow_y.setColour( colourSelected( g_colour_y, m_selectable_y.isSelected() ) );
1667         m_arrow_z.setColour( colourSelected( g_colour_z, m_selectable_z.isSelected() ) );
1668         m_quad_screen.setColour( colourSelected( g_colour_screen, m_selectable_screen.isSelected() ) );
1669 }
1670
1671 void render( Renderer& renderer, const VolumeTest& volume, const Matrix4& pivot2world ){
1672         m_pivot.update( pivot2world, volume.GetModelview(), volume.GetProjection(), volume.GetViewport() );
1673
1674         // temp hack
1675         UpdateColours();
1676
1677         renderer.addRenderable( m_arrow_x, m_pivot.m_worldSpace );
1678         renderer.addRenderable( m_arrow_y, m_pivot.m_worldSpace );
1679         renderer.addRenderable( m_arrow_z, m_pivot.m_worldSpace );
1680
1681         renderer.addRenderable( m_quad_screen, m_pivot.m_viewpointSpace );
1682 }
1683 void testSelect( const View& view, const Matrix4& pivot2world ){
1684         m_pivot.update( pivot2world, view.GetModelview(), view.GetProjection(), view.GetViewport() );
1685
1686         SelectionPool selector;
1687
1688         {
1689                 Matrix4 local2view( matrix4_multiplied_by_matrix4( view.GetViewMatrix(), m_pivot.m_worldSpace ) );
1690
1691 #if defined( DEBUG_SELECTION )
1692                 g_render_clipped.construct( view.GetViewMatrix() );
1693 #endif
1694
1695                 {
1696                         SelectionIntersection best;
1697                         Line_BestPoint( local2view, m_arrow_x.m_line, best );
1698                         selector.addSelectable( best, &m_selectable_x );
1699                 }
1700
1701                 {
1702                         SelectionIntersection best;
1703                         Line_BestPoint( local2view, m_arrow_y.m_line, best );
1704                         selector.addSelectable( best, &m_selectable_y );
1705                 }
1706
1707                 {
1708                         SelectionIntersection best;
1709                         Line_BestPoint( local2view, m_arrow_z.m_line, best );
1710                         selector.addSelectable( best, &m_selectable_z );
1711                 }
1712         }
1713
1714         {
1715                 Matrix4 local2view( matrix4_multiplied_by_matrix4( view.GetViewMatrix(), m_pivot.m_viewpointSpace ) );
1716
1717                 {
1718                         SelectionIntersection best;
1719                         Quad_BestPoint( local2view, eClipCullCW, m_quad_screen.m_quad, best );
1720                         selector.addSelectable( best, &m_selectable_screen );
1721                 }
1722         }
1723
1724         if ( !selector.failed() ) {
1725                 ( *selector.begin() ).second->setSelected( true );
1726         }
1727 }
1728
1729 Manipulatable* GetManipulatable(){
1730         if ( m_selectable_x.isSelected() ) {
1731                 m_axis.SetAxis( g_vector3_axis_x );
1732                 return &m_axis;
1733         }
1734         else if ( m_selectable_y.isSelected() ) {
1735                 m_axis.SetAxis( g_vector3_axis_y );
1736                 return &m_axis;
1737         }
1738         else if ( m_selectable_z.isSelected() ) {
1739                 m_axis.SetAxis( g_vector3_axis_z );
1740                 return &m_axis;
1741         }
1742         else{
1743                 return &m_free;
1744         }
1745 }
1746
1747 void setSelected( bool select ){
1748         m_selectable_x.setSelected( select );
1749         m_selectable_y.setSelected( select );
1750         m_selectable_z.setSelected( select );
1751         m_selectable_screen.setSelected( select );
1752 }
1753 bool isSelected() const {
1754         return m_selectable_x.isSelected()
1755                    | m_selectable_y.isSelected()
1756                    | m_selectable_z.isSelected()
1757                    | m_selectable_screen.isSelected();
1758 }
1759 };
1760
1761
1762 inline PlaneSelectable* Instance_getPlaneSelectable( scene::Instance& instance ){
1763         return InstanceTypeCast<PlaneSelectable>::cast( instance );
1764 }
1765
1766 class PlaneSelectableSelectPlanes : public scene::Graph::Walker
1767 {
1768 Selector& m_selector;
1769 SelectionTest& m_test;
1770 PlaneCallback m_selectedPlaneCallback;
1771 public:
1772 PlaneSelectableSelectPlanes( Selector& selector, SelectionTest& test, const PlaneCallback& selectedPlaneCallback )
1773         : m_selector( selector ), m_test( test ), m_selectedPlaneCallback( selectedPlaneCallback ){
1774 }
1775 bool pre( const scene::Path& path, scene::Instance& instance ) const {
1776         if ( path.top().get().visible() ) {
1777                 Selectable* selectable = Instance_getSelectable( instance );
1778                 if ( selectable != 0 && selectable->isSelected() ) {
1779                         PlaneSelectable* planeSelectable = Instance_getPlaneSelectable( instance );
1780                         if ( planeSelectable != 0 ) {
1781                                 planeSelectable->selectPlanes( m_selector, m_test, m_selectedPlaneCallback );
1782                         }
1783                 }
1784         }
1785         return true;
1786 }
1787 };
1788
1789 class PlaneSelectableSelectReversedPlanes : public scene::Graph::Walker
1790 {
1791 Selector& m_selector;
1792 const SelectedPlanes& m_selectedPlanes;
1793 public:
1794 PlaneSelectableSelectReversedPlanes( Selector& selector, const SelectedPlanes& selectedPlanes )
1795         : m_selector( selector ), m_selectedPlanes( selectedPlanes ){
1796 }
1797 bool pre( const scene::Path& path, scene::Instance& instance ) const {
1798         if ( path.top().get().visible() ) {
1799                 Selectable* selectable = Instance_getSelectable( instance );
1800                 if ( selectable != 0 && selectable->isSelected() ) {
1801                         PlaneSelectable* planeSelectable = Instance_getPlaneSelectable( instance );
1802                         if ( planeSelectable != 0 ) {
1803                                 planeSelectable->selectReversedPlanes( m_selector, m_selectedPlanes );
1804                         }
1805                 }
1806         }
1807         return true;
1808 }
1809 };
1810
1811 void Scene_forEachPlaneSelectable_selectPlanes( scene::Graph& graph, Selector& selector, SelectionTest& test, const PlaneCallback& selectedPlaneCallback ){
1812         graph.traverse( PlaneSelectableSelectPlanes( selector, test, selectedPlaneCallback ) );
1813 }
1814
1815 void Scene_forEachPlaneSelectable_selectReversedPlanes( scene::Graph& graph, Selector& selector, const SelectedPlanes& selectedPlanes ){
1816         graph.traverse( PlaneSelectableSelectReversedPlanes( selector, selectedPlanes ) );
1817 }
1818
1819
1820 class PlaneLess
1821 {
1822 public:
1823 bool operator()( const Plane3& plane, const Plane3& other ) const {
1824         if ( plane.a < other.a ) {
1825                 return true;
1826         }
1827         if ( other.a < plane.a ) {
1828                 return false;
1829         }
1830
1831         if ( plane.b < other.b ) {
1832                 return true;
1833         }
1834         if ( other.b < plane.b ) {
1835                 return false;
1836         }
1837
1838         if ( plane.c < other.c ) {
1839                 return true;
1840         }
1841         if ( other.c < plane.c ) {
1842                 return false;
1843         }
1844
1845         if ( plane.d < other.d ) {
1846                 return true;
1847         }
1848         if ( other.d < plane.d ) {
1849                 return false;
1850         }
1851
1852         return false;
1853 }
1854 };
1855
1856 typedef std::set<Plane3, PlaneLess> PlaneSet;
1857
1858 inline void PlaneSet_insert( PlaneSet& self, const Plane3& plane ){
1859         self.insert( plane );
1860 }
1861
1862 inline bool PlaneSet_contains( const PlaneSet& self, const Plane3& plane ){
1863         return self.find( plane ) != self.end();
1864 }
1865
1866
1867 class SelectedPlaneSet : public SelectedPlanes
1868 {
1869 PlaneSet m_selectedPlanes;
1870 public:
1871 bool empty() const {
1872         return m_selectedPlanes.empty();
1873 }
1874
1875 void insert( const Plane3& plane ){
1876         PlaneSet_insert( m_selectedPlanes, plane );
1877 }
1878 bool contains( const Plane3& plane ) const {
1879         return PlaneSet_contains( m_selectedPlanes, plane );
1880 }
1881 typedef MemberCaller<SelectedPlaneSet, void(const Plane3&), &SelectedPlaneSet::insert> InsertCaller;
1882 };
1883
1884
1885 bool Scene_forEachPlaneSelectable_selectPlanes( scene::Graph& graph, Selector& selector, SelectionTest& test ){
1886         SelectedPlaneSet selectedPlanes;
1887
1888         Scene_forEachPlaneSelectable_selectPlanes( graph, selector, test, SelectedPlaneSet::InsertCaller( selectedPlanes ) );
1889         Scene_forEachPlaneSelectable_selectReversedPlanes( graph, selector, selectedPlanes );
1890
1891         return !selectedPlanes.empty();
1892 }
1893
1894 void Scene_Translate_Component_Selected( scene::Graph& graph, const Vector3& translation );
1895 void Scene_Translate_Selected( scene::Graph& graph, const Vector3& translation );
1896 void Scene_TestSelect_Primitive( Selector& selector, SelectionTest& test, const VolumeTest& volume );
1897 void Scene_TestSelect_Component( Selector& selector, SelectionTest& test, const VolumeTest& volume, SelectionSystem::EComponentMode componentMode );
1898 void Scene_TestSelect_Component_Selected( Selector& selector, SelectionTest& test, const VolumeTest& volume, SelectionSystem::EComponentMode componentMode );
1899 void Scene_SelectAll_Component( bool select, SelectionSystem::EComponentMode componentMode );
1900
1901 class ResizeTranslatable : public Translatable
1902 {
1903 void translate( const Vector3& translation ){
1904         Scene_Translate_Component_Selected( GlobalSceneGraph(), translation );
1905 }
1906 };
1907
1908 class DragTranslatable : public Translatable
1909 {
1910 void translate( const Vector3& translation ){
1911         if ( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent ) {
1912                 Scene_Translate_Component_Selected( GlobalSceneGraph(), translation );
1913         }
1914         else
1915         {
1916                 Scene_Translate_Selected( GlobalSceneGraph(), translation );
1917         }
1918 }
1919 };
1920
1921 class SelectionVolume : public SelectionTest
1922 {
1923 Matrix4 m_local2view;
1924 const View& m_view;
1925 clipcull_t m_cull;
1926 Vector3 m_near;
1927 Vector3 m_far;
1928 public:
1929 SelectionVolume( const View& view )
1930         : m_view( view ){
1931 }
1932
1933 const VolumeTest& getVolume() const {
1934         return m_view;
1935 }
1936
1937 const Vector3& getNear() const {
1938         return m_near;
1939 }
1940 const Vector3& getFar() const {
1941         return m_far;
1942 }
1943
1944 void BeginMesh( const Matrix4& localToWorld, bool twoSided ){
1945         m_local2view = matrix4_multiplied_by_matrix4( m_view.GetViewMatrix(), localToWorld );
1946
1947         // Cull back-facing polygons based on winding being clockwise or counter-clockwise.
1948         // Don't cull if the view is wireframe and the polygons are two-sided.
1949         m_cull = twoSided && !m_view.fill() ? eClipCullNone : ( matrix4_handedness( localToWorld ) == MATRIX4_RIGHTHANDED ) ? eClipCullCW : eClipCullCCW;
1950
1951         {
1952                 Matrix4 screen2world( matrix4_full_inverse( m_local2view ) );
1953
1954                 m_near = vector4_projected(
1955                         matrix4_transformed_vector4(
1956                                 screen2world,
1957                                 Vector4( 0, 0, -1, 1 )
1958                                 )
1959                         );
1960
1961                 m_far = vector4_projected(
1962                         matrix4_transformed_vector4(
1963                                 screen2world,
1964                                 Vector4( 0, 0, 1, 1 )
1965                                 )
1966                         );
1967         }
1968
1969 #if defined( DEBUG_SELECTION )
1970         g_render_clipped.construct( m_view.GetViewMatrix() );
1971 #endif
1972 }
1973 void TestPoint( const Vector3& point, SelectionIntersection& best ){
1974         Vector4 clipped;
1975         if ( matrix4_clip_point( m_local2view, point, clipped ) == c_CLIP_PASS ) {
1976                 best = select_point_from_clipped( clipped );
1977         }
1978 }
1979 void TestPolygon( const VertexPointer& vertices, std::size_t count, SelectionIntersection& best ){
1980         Vector4 clipped[9];
1981         for ( std::size_t i = 0; i + 2 < count; ++i )
1982         {
1983                 BestPoint(
1984                         matrix4_clip_triangle(
1985                                 m_local2view,
1986                                 reinterpret_cast<const Vector3&>( vertices[0] ),
1987                                 reinterpret_cast<const Vector3&>( vertices[i + 1] ),
1988                                 reinterpret_cast<const Vector3&>( vertices[i + 2] ),
1989                                 clipped
1990                                 ),
1991                         clipped,
1992                         best,
1993                         m_cull
1994                         );
1995         }
1996 }
1997 void TestLineLoop( const VertexPointer& vertices, std::size_t count, SelectionIntersection& best ){
1998         if ( count == 0 ) {
1999                 return;
2000         }
2001         Vector4 clipped[9];
2002         for ( VertexPointer::iterator i = vertices.begin(), end = i + count, prev = i + ( count - 1 ); i != end; prev = i, ++i )
2003         {
2004                 BestPoint(
2005                         matrix4_clip_line(
2006                                 m_local2view,
2007                                 reinterpret_cast<const Vector3&>( ( *prev ) ),
2008                                 reinterpret_cast<const Vector3&>( ( *i ) ),
2009                                 clipped
2010                                 ),
2011                         clipped,
2012                         best,
2013                         m_cull
2014                         );
2015         }
2016 }
2017 void TestLineStrip( const VertexPointer& vertices, std::size_t count, SelectionIntersection& best ){
2018         if ( count == 0 ) {
2019                 return;
2020         }
2021         Vector4 clipped[9];
2022         for ( VertexPointer::iterator i = vertices.begin(), end = i + count, next = i + 1; next != end; i = next, ++next )
2023         {
2024                 BestPoint(
2025                         matrix4_clip_line(
2026                                 m_local2view,
2027                                 reinterpret_cast<const Vector3&>( ( *i ) ),
2028                                 reinterpret_cast<const Vector3&>( ( *next ) ),
2029                                 clipped
2030                                 ),
2031                         clipped,
2032                         best,
2033                         m_cull
2034                         );
2035         }
2036 }
2037 void TestLines( const VertexPointer& vertices, std::size_t count, SelectionIntersection& best ){
2038         if ( count == 0 ) {
2039                 return;
2040         }
2041         Vector4 clipped[9];
2042         for ( VertexPointer::iterator i = vertices.begin(), end = i + count; i != end; i += 2 )
2043         {
2044                 BestPoint(
2045                         matrix4_clip_line(
2046                                 m_local2view,
2047                                 reinterpret_cast<const Vector3&>( ( *i ) ),
2048                                 reinterpret_cast<const Vector3&>( ( *( i + 1 ) ) ),
2049                                 clipped
2050                                 ),
2051                         clipped,
2052                         best,
2053                         m_cull
2054                         );
2055         }
2056 }
2057 void TestTriangles( const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best ){
2058         Vector4 clipped[9];
2059         for ( IndexPointer::iterator i( indices.begin() ); i != indices.end(); i += 3 )
2060         {
2061                 BestPoint(
2062                         matrix4_clip_triangle(
2063                                 m_local2view,
2064                                 reinterpret_cast<const Vector3&>( vertices[*i] ),
2065                                 reinterpret_cast<const Vector3&>( vertices[*( i + 1 )] ),
2066                                 reinterpret_cast<const Vector3&>( vertices[*( i + 2 )] ),
2067                                 clipped
2068                                 ),
2069                         clipped,
2070                         best,
2071                         m_cull
2072                         );
2073         }
2074 }
2075 void TestQuads( const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best ){
2076         Vector4 clipped[9];
2077         for ( IndexPointer::iterator i( indices.begin() ); i != indices.end(); i += 4 )
2078         {
2079                 BestPoint(
2080                         matrix4_clip_triangle(
2081                                 m_local2view,
2082                                 reinterpret_cast<const Vector3&>( vertices[*i] ),
2083                                 reinterpret_cast<const Vector3&>( vertices[*( i + 1 )] ),
2084                                 reinterpret_cast<const Vector3&>( vertices[*( i + 3 )] ),
2085                                 clipped
2086                                 ),
2087                         clipped,
2088                         best,
2089                         m_cull
2090                         );
2091                 BestPoint(
2092                         matrix4_clip_triangle(
2093                                 m_local2view,
2094                                 reinterpret_cast<const Vector3&>( vertices[*( i + 1 )] ),
2095                                 reinterpret_cast<const Vector3&>( vertices[*( i + 2 )] ),
2096                                 reinterpret_cast<const Vector3&>( vertices[*( i + 3 )] ),
2097                                 clipped
2098                                 ),
2099                         clipped,
2100                         best,
2101                         m_cull
2102                         );
2103         }
2104 }
2105 void TestQuadStrip( const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best ){
2106         Vector4 clipped[9];
2107         for ( IndexPointer::iterator i( indices.begin() ); i + 2 != indices.end(); i += 2 )
2108         {
2109                 BestPoint(
2110                         matrix4_clip_triangle(
2111                                 m_local2view,
2112                                 reinterpret_cast<const Vector3&>( vertices[*i] ),
2113                                 reinterpret_cast<const Vector3&>( vertices[*( i + 1 )] ),
2114                                 reinterpret_cast<const Vector3&>( vertices[*( i + 2 )] ),
2115                                 clipped
2116                                 ),
2117                         clipped,
2118                         best,
2119                         m_cull
2120                         );
2121                 BestPoint(
2122                         matrix4_clip_triangle(
2123                                 m_local2view,
2124                                 reinterpret_cast<const Vector3&>( vertices[*( i + 2 )] ),
2125                                 reinterpret_cast<const Vector3&>( vertices[*( i + 1 )] ),
2126                                 reinterpret_cast<const Vector3&>( vertices[*( i + 3 )] ),
2127                                 clipped
2128                                 ),
2129                         clipped,
2130                         best,
2131                         m_cull
2132                         );
2133         }
2134 }
2135 };
2136
2137 class SelectionCounter
2138 {
2139 public:
2140 using func = void(const Selectable &);
2141
2142 SelectionCounter( const SelectionChangeCallback& onchanged )
2143         : m_count( 0 ), m_onchanged( onchanged ){
2144 }
2145 void operator()( const Selectable& selectable ){
2146         if ( selectable.isSelected() ) {
2147                 ++m_count;
2148         }
2149         else
2150         {
2151                 ASSERT_MESSAGE( m_count != 0, "selection counter underflow" );
2152                 --m_count;
2153         }
2154
2155         m_onchanged( selectable );
2156 }
2157 bool empty() const {
2158         return m_count == 0;
2159 }
2160 std::size_t size() const {
2161         return m_count;
2162 }
2163 private:
2164 std::size_t m_count;
2165 SelectionChangeCallback m_onchanged;
2166 };
2167
2168 inline void ConstructSelectionTest( View& view, const rect_t selection_box ){
2169         view.EnableScissor( selection_box.min[0], selection_box.max[0], selection_box.min[1], selection_box.max[1] );
2170 }
2171
2172 inline const rect_t SelectionBoxForPoint( const float device_point[2], const float device_epsilon[2] ){
2173         rect_t selection_box;
2174         selection_box.min[0] = device_point[0] - device_epsilon[0];
2175         selection_box.min[1] = device_point[1] - device_epsilon[1];
2176         selection_box.max[0] = device_point[0] + device_epsilon[0];
2177         selection_box.max[1] = device_point[1] + device_epsilon[1];
2178         return selection_box;
2179 }
2180
2181 inline const rect_t SelectionBoxForArea( const float device_point[2], const float device_delta[2] ){
2182         rect_t selection_box;
2183         selection_box.min[0] = ( device_delta[0] < 0 ) ? ( device_point[0] + device_delta[0] ) : ( device_point[0] );
2184         selection_box.min[1] = ( device_delta[1] < 0 ) ? ( device_point[1] + device_delta[1] ) : ( device_point[1] );
2185         selection_box.max[0] = ( device_delta[0] > 0 ) ? ( device_point[0] + device_delta[0] ) : ( device_point[0] );
2186         selection_box.max[1] = ( device_delta[1] > 0 ) ? ( device_point[1] + device_delta[1] ) : ( device_point[1] );
2187         return selection_box;
2188 }
2189
2190 Quaternion construct_local_rotation( const Quaternion& world, const Quaternion& localToWorld ){
2191         return quaternion_normalised( quaternion_multiplied_by_quaternion(
2192                                                                           quaternion_normalised( quaternion_multiplied_by_quaternion(
2193                                                                                                                                  quaternion_inverse( localToWorld ),
2194                                                                                                                                  world
2195                                                                                                                                  ) ),
2196                                                                           localToWorld
2197                                                                           ) );
2198 }
2199
2200 inline void matrix4_assign_rotation( Matrix4& matrix, const Matrix4& other ){
2201         matrix[0] = other[0];
2202         matrix[1] = other[1];
2203         matrix[2] = other[2];
2204         matrix[4] = other[4];
2205         matrix[5] = other[5];
2206         matrix[6] = other[6];
2207         matrix[8] = other[8];
2208         matrix[9] = other[9];
2209         matrix[10] = other[10];
2210 }
2211
2212 void matrix4_assign_rotation_for_pivot( Matrix4& matrix, scene::Instance& instance ){
2213         Editable* editable = Node_getEditable( instance.path().top() );
2214         if ( editable != 0 ) {
2215                 matrix4_assign_rotation( matrix, matrix4_multiplied_by_matrix4( instance.localToWorld(), editable->getLocalPivot() ) );
2216         }
2217         else
2218         {
2219                 matrix4_assign_rotation( matrix, instance.localToWorld() );
2220         }
2221 }
2222
2223 inline bool Instance_isSelectedComponents( scene::Instance& instance ){
2224         ComponentSelectionTestable* componentSelectionTestable = Instance_getComponentSelectionTestable( instance );
2225         return componentSelectionTestable != 0
2226                    && componentSelectionTestable->isSelectedComponents();
2227 }
2228
2229 class TranslateSelected : public SelectionSystem::Visitor
2230 {
2231 const Vector3& m_translate;
2232 public:
2233 TranslateSelected( const Vector3& translate )
2234         : m_translate( translate ){
2235 }
2236 void visit( scene::Instance& instance ) const {
2237         Transformable* transform = Instance_getTransformable( instance );
2238         if ( transform != 0 ) {
2239                 transform->setType( TRANSFORM_PRIMITIVE );
2240                 transform->setTranslation( m_translate );
2241         }
2242 }
2243 };
2244
2245 void Scene_Translate_Selected( scene::Graph& graph, const Vector3& translation ){
2246         if ( GlobalSelectionSystem().countSelected() != 0 ) {
2247                 GlobalSelectionSystem().foreachSelected( TranslateSelected( translation ) );
2248         }
2249 }
2250
2251 Vector3 get_local_pivot( const Vector3& world_pivot, const Matrix4& localToWorld ){
2252         return Vector3(
2253                            matrix4_transformed_point(
2254                                    matrix4_full_inverse( localToWorld ),
2255                                    world_pivot
2256                                    )
2257                            );
2258 }
2259
2260 void translation_for_pivoted_matrix_transform( Vector3& parent_translation, const Matrix4& local_transform, const Vector3& world_pivot, const Matrix4& localToWorld, const Matrix4& localToParent ){
2261         // we need a translation inside the parent system to move the origin of this object to the right place
2262
2263         // mathematically, it must fulfill:
2264         //
2265         //   local_translation local_transform local_pivot = local_pivot
2266         //   local_translation = local_pivot - local_transform local_pivot
2267         //
2268         //   or maybe?
2269         //   local_transform local_translation local_pivot = local_pivot
2270         //                   local_translation local_pivot = local_transform^-1 local_pivot
2271         //                 local_translation + local_pivot = local_transform^-1 local_pivot
2272         //                   local_translation             = local_transform^-1 local_pivot - local_pivot
2273
2274         Vector3 local_pivot( get_local_pivot( world_pivot, localToWorld ) );
2275
2276         Vector3 local_translation(
2277                 vector3_subtracted(
2278                         local_pivot,
2279                         matrix4_transformed_point(
2280                                 local_transform,
2281                                 local_pivot
2282                                 )
2283                 /*
2284                     matrix4_transformed_point(
2285                         matrix4_full_inverse(local_transform),
2286                         local_pivot
2287                     ),
2288                     local_pivot
2289                  */
2290                         )
2291                 );
2292
2293         translation_local2object( parent_translation, local_translation, localToParent );
2294
2295         /*
2296            // verify it!
2297            globalOutputStream() << "World pivot is at " << world_pivot << "\n";
2298            globalOutputStream() << "Local pivot is at " << local_pivot << "\n";
2299            globalOutputStream() << "Transformation " << local_transform << " moves it to: " << matrix4_transformed_point(local_transform, local_pivot) << "\n";
2300            globalOutputStream() << "Must move by " << local_translation << " in the local system" << "\n";
2301            globalOutputStream() << "Must move by " << parent_translation << " in the parent system" << "\n";
2302          */
2303 }
2304
2305 void translation_for_pivoted_rotation( Vector3& parent_translation, const Quaternion& local_rotation, const Vector3& world_pivot, const Matrix4& localToWorld, const Matrix4& localToParent ){
2306         translation_for_pivoted_matrix_transform( parent_translation, matrix4_rotation_for_quaternion_quantised( local_rotation ), world_pivot, localToWorld, localToParent );
2307 }
2308
2309 void translation_for_pivoted_scale( Vector3& parent_translation, const Vector3& world_scale, const Vector3& world_pivot, const Matrix4& localToWorld, const Matrix4& localToParent ){
2310         Matrix4 local_transform(
2311                 matrix4_multiplied_by_matrix4(
2312                         matrix4_full_inverse( localToWorld ),
2313                         matrix4_multiplied_by_matrix4(
2314                                 matrix4_scale_for_vec3( world_scale ),
2315                                 localToWorld
2316                                 )
2317                         )
2318                 );
2319         local_transform.tx() = local_transform.ty() = local_transform.tz() = 0; // cancel translation parts
2320         translation_for_pivoted_matrix_transform( parent_translation, local_transform, world_pivot, localToWorld, localToParent );
2321 }
2322
2323 class rotate_selected : public SelectionSystem::Visitor
2324 {
2325 const Quaternion& m_rotate;
2326 const Vector3& m_world_pivot;
2327 public:
2328 rotate_selected( const Quaternion& rotation, const Vector3& world_pivot )
2329         : m_rotate( rotation ), m_world_pivot( world_pivot ){
2330 }
2331 void visit( scene::Instance& instance ) const {
2332         TransformNode* transformNode = Node_getTransformNode( instance.path().top() );
2333         if ( transformNode != 0 ) {
2334                 Transformable* transform = Instance_getTransformable( instance );
2335                 if ( transform != 0 ) {
2336                         transform->setType( TRANSFORM_PRIMITIVE );
2337                         transform->setScale( c_scale_identity );
2338                         transform->setTranslation( c_translation_identity );
2339
2340                         transform->setType( TRANSFORM_PRIMITIVE );
2341                         transform->setRotation( m_rotate );
2342
2343                         {
2344                                 Editable* editable = Node_getEditable( instance.path().top() );
2345                                 const Matrix4& localPivot = editable != 0 ? editable->getLocalPivot() : g_matrix4_identity;
2346
2347                                 Vector3 parent_translation;
2348                                 translation_for_pivoted_rotation(
2349                                         parent_translation,
2350                                         m_rotate,
2351                                         m_world_pivot,
2352                                         matrix4_multiplied_by_matrix4( instance.localToWorld(), localPivot ),
2353                                         matrix4_multiplied_by_matrix4( transformNode->localToParent(), localPivot )
2354                                         );
2355
2356                                 transform->setTranslation( parent_translation );
2357                         }
2358                 }
2359         }
2360 }
2361 };
2362
2363 void Scene_Rotate_Selected( scene::Graph& graph, const Quaternion& rotation, const Vector3& world_pivot ){
2364         if ( GlobalSelectionSystem().countSelected() != 0 ) {
2365                 GlobalSelectionSystem().foreachSelected( rotate_selected( rotation, world_pivot ) );
2366         }
2367 }
2368
2369 class scale_selected : public SelectionSystem::Visitor
2370 {
2371 const Vector3& m_scale;
2372 const Vector3& m_world_pivot;
2373 public:
2374 scale_selected( const Vector3& scaling, const Vector3& world_pivot )
2375         : m_scale( scaling ), m_world_pivot( world_pivot ){
2376 }
2377 void visit( scene::Instance& instance ) const {
2378         TransformNode* transformNode = Node_getTransformNode( instance.path().top() );
2379         if ( transformNode != 0 ) {
2380                 Transformable* transform = Instance_getTransformable( instance );
2381                 if ( transform != 0 ) {
2382                         transform->setType( TRANSFORM_PRIMITIVE );
2383                         transform->setScale( c_scale_identity );
2384                         transform->setTranslation( c_translation_identity );
2385
2386                         transform->setType( TRANSFORM_PRIMITIVE );
2387                         transform->setScale( m_scale );
2388                         {
2389                                 Editable* editable = Node_getEditable( instance.path().top() );
2390                                 const Matrix4& localPivot = editable != 0 ? editable->getLocalPivot() : g_matrix4_identity;
2391
2392                                 Vector3 parent_translation;
2393                                 translation_for_pivoted_scale(
2394                                         parent_translation,
2395                                         m_scale,
2396                                         m_world_pivot,
2397                                         matrix4_multiplied_by_matrix4( instance.localToWorld(), localPivot ),
2398                                         matrix4_multiplied_by_matrix4( transformNode->localToParent(), localPivot )
2399                                         );
2400
2401                                 transform->setTranslation( parent_translation );
2402                         }
2403                 }
2404         }
2405 }
2406 };
2407
2408 void Scene_Scale_Selected( scene::Graph& graph, const Vector3& scaling, const Vector3& world_pivot ){
2409         if ( GlobalSelectionSystem().countSelected() != 0 ) {
2410                 GlobalSelectionSystem().foreachSelected( scale_selected( scaling, world_pivot ) );
2411         }
2412 }
2413
2414
2415 class translate_component_selected : public SelectionSystem::Visitor
2416 {
2417 const Vector3& m_translate;
2418 public:
2419 translate_component_selected( const Vector3& translate )
2420         : m_translate( translate ){
2421 }
2422 void visit( scene::Instance& instance ) const {
2423         Transformable* transform = Instance_getTransformable( instance );
2424         if ( transform != 0 ) {
2425                 transform->setType( TRANSFORM_COMPONENT );
2426                 transform->setTranslation( m_translate );
2427         }
2428 }
2429 };
2430
2431 void Scene_Translate_Component_Selected( scene::Graph& graph, const Vector3& translation ){
2432         if ( GlobalSelectionSystem().countSelected() != 0 ) {
2433                 GlobalSelectionSystem().foreachSelectedComponent( translate_component_selected( translation ) );
2434         }
2435 }
2436
2437 class rotate_component_selected : public SelectionSystem::Visitor
2438 {
2439 const Quaternion& m_rotate;
2440 const Vector3& m_world_pivot;
2441 public:
2442 rotate_component_selected( const Quaternion& rotation, const Vector3& world_pivot )
2443         : m_rotate( rotation ), m_world_pivot( world_pivot ){
2444 }
2445 void visit( scene::Instance& instance ) const {
2446         Transformable* transform = Instance_getTransformable( instance );
2447         if ( transform != 0 ) {
2448                 Vector3 parent_translation;
2449                 translation_for_pivoted_rotation( parent_translation, m_rotate, m_world_pivot, instance.localToWorld(), Node_getTransformNode( instance.path().top() )->localToParent() );
2450
2451                 transform->setType( TRANSFORM_COMPONENT );
2452                 transform->setRotation( m_rotate );
2453                 transform->setTranslation( parent_translation );
2454         }
2455 }
2456 };
2457
2458 void Scene_Rotate_Component_Selected( scene::Graph& graph, const Quaternion& rotation, const Vector3& world_pivot ){
2459         if ( GlobalSelectionSystem().countSelectedComponents() != 0 ) {
2460                 GlobalSelectionSystem().foreachSelectedComponent( rotate_component_selected( rotation, world_pivot ) );
2461         }
2462 }
2463
2464 class scale_component_selected : public SelectionSystem::Visitor
2465 {
2466 const Vector3& m_scale;
2467 const Vector3& m_world_pivot;
2468 public:
2469 scale_component_selected( const Vector3& scaling, const Vector3& world_pivot )
2470         : m_scale( scaling ), m_world_pivot( world_pivot ){
2471 }
2472 void visit( scene::Instance& instance ) const {
2473         Transformable* transform = Instance_getTransformable( instance );
2474         if ( transform != 0 ) {
2475                 Vector3 parent_translation;
2476                 translation_for_pivoted_scale( parent_translation, m_scale, m_world_pivot, instance.localToWorld(), Node_getTransformNode( instance.path().top() )->localToParent() );
2477
2478                 transform->setType( TRANSFORM_COMPONENT );
2479                 transform->setScale( m_scale );
2480                 transform->setTranslation( parent_translation );
2481         }
2482 }
2483 };
2484
2485 void Scene_Scale_Component_Selected( scene::Graph& graph, const Vector3& scaling, const Vector3& world_pivot ){
2486         if ( GlobalSelectionSystem().countSelectedComponents() != 0 ) {
2487                 GlobalSelectionSystem().foreachSelectedComponent( scale_component_selected( scaling, world_pivot ) );
2488         }
2489 }
2490
2491
2492 class BooleanSelector : public Selector
2493 {
2494 bool m_selected;
2495 SelectionIntersection m_intersection;
2496 Selectable* m_selectable;
2497 public:
2498 BooleanSelector() : m_selected( false ){
2499 }
2500
2501 void pushSelectable( Selectable& selectable ){
2502         m_intersection = SelectionIntersection();
2503         m_selectable = &selectable;
2504 }
2505 void popSelectable(){
2506         if ( m_intersection.valid() ) {
2507                 m_selected = true;
2508         }
2509         m_intersection = SelectionIntersection();
2510 }
2511 void addIntersection( const SelectionIntersection& intersection ){
2512         if ( m_selectable->isSelected() ) {
2513                 assign_if_closer( m_intersection, intersection );
2514         }
2515 }
2516
2517 bool isSelected(){
2518         return m_selected;
2519 }
2520 };
2521
2522 class BestSelector : public Selector
2523 {
2524 SelectionIntersection m_intersection;
2525 Selectable* m_selectable;
2526 SelectionIntersection m_bestIntersection;
2527 std::list<Selectable*> m_bestSelectable;
2528 public:
2529 BestSelector() : m_bestIntersection( SelectionIntersection() ), m_bestSelectable( 0 ){
2530 }
2531
2532 void pushSelectable( Selectable& selectable ){
2533         m_intersection = SelectionIntersection();
2534         m_selectable = &selectable;
2535 }
2536 void popSelectable(){
2537         if ( m_intersection.equalEpsilon( m_bestIntersection, 0.25f, 0.001f ) ) {
2538                 m_bestSelectable.push_back( m_selectable );
2539                 m_bestIntersection = m_intersection;
2540         }
2541         else if ( m_intersection < m_bestIntersection ) {
2542                 m_bestSelectable.clear();
2543                 m_bestSelectable.push_back( m_selectable );
2544                 m_bestIntersection = m_intersection;
2545         }
2546         m_intersection = SelectionIntersection();
2547 }
2548 void addIntersection( const SelectionIntersection& intersection ){
2549         assign_if_closer( m_intersection, intersection );
2550 }
2551
2552 std::list<Selectable*>& best(){
2553         return m_bestSelectable;
2554 }
2555 };
2556
2557 class DragManipulator : public Manipulator
2558 {
2559 TranslateFree m_freeResize;
2560 TranslateFree m_freeDrag;
2561 ResizeTranslatable m_resize;
2562 DragTranslatable m_drag;
2563 SelectableBool m_dragSelectable;
2564 public:
2565
2566 bool m_selected;
2567
2568 DragManipulator() : m_freeResize( m_resize ), m_freeDrag( m_drag ), m_selected( false ){
2569 }
2570
2571 Manipulatable* GetManipulatable(){
2572         //globalOutputStream() << ( m_dragSelectable.isSelected() ? "m_freeDrag\n" : "m_freeResize\n" );
2573         return m_dragSelectable.isSelected() ? &m_freeDrag : &m_freeResize;
2574 }
2575
2576 void testSelect( const View& view, const Matrix4& pivot2world ){
2577         SelectionPool selector;
2578
2579         SelectionVolume test( view );
2580
2581         if ( GlobalSelectionSystem().Mode() == SelectionSystem::ePrimitive ) {
2582                 BooleanSelector booleanSelector;
2583
2584                 Scene_TestSelect_Primitive( booleanSelector, test, view );
2585
2586                 if ( booleanSelector.isSelected() ) {
2587                         selector.addSelectable( SelectionIntersection( 0, 0 ), &m_dragSelectable );
2588                         m_selected = false;
2589                 }
2590                 else
2591                 {
2592                         m_selected = Scene_forEachPlaneSelectable_selectPlanes( GlobalSceneGraph(), selector, test );
2593                 }
2594         }
2595         else
2596         {
2597                 BestSelector bestSelector;
2598                 Scene_TestSelect_Component_Selected( bestSelector, test, view, GlobalSelectionSystem().ComponentMode() );
2599                 for ( std::list<Selectable*>::iterator i = bestSelector.best().begin(); i != bestSelector.best().end(); ++i )
2600                 {
2601                         if ( !( *i )->isSelected() ) {
2602                                 GlobalSelectionSystem().setSelectedAllComponents( false );
2603                         }
2604                         m_selected = false;
2605                         selector.addSelectable( SelectionIntersection( 0, 0 ), ( *i ) );
2606                         m_dragSelectable.setSelected( true );
2607                 }
2608                 if( GlobalSelectionSystem().countSelectedComponents() != 0 ){
2609                         m_dragSelectable.setSelected( true );
2610                 }
2611         }
2612
2613         for ( SelectionPool::iterator i = selector.begin(); i != selector.end(); ++i )
2614         {
2615                 ( *i ).second->setSelected( true );
2616         }
2617 }
2618
2619 void setSelected( bool select ){
2620         m_selected = select;
2621         m_dragSelectable.setSelected( select );
2622 }
2623 bool isSelected() const {
2624         return m_selected || m_dragSelectable.isSelected();
2625 }
2626 };
2627
2628 class ClipManipulator : public Manipulator
2629 {
2630 public:
2631
2632 Manipulatable* GetManipulatable(){
2633         ERROR_MESSAGE( "clipper is not manipulatable" );
2634         return 0;
2635 }
2636
2637 void setSelected( bool select ){
2638 }
2639 bool isSelected() const {
2640         return false;
2641 }
2642 };
2643
2644 class select_all : public scene::Graph::Walker
2645 {
2646 bool m_select;
2647 public:
2648 select_all( bool select )
2649         : m_select( select ){
2650 }
2651 bool pre( const scene::Path& path, scene::Instance& instance ) const {
2652         Selectable* selectable = Instance_getSelectable( instance );
2653         if ( selectable != 0 ) {
2654                 selectable->setSelected( m_select );
2655         }
2656         return true;
2657 }
2658 };
2659
2660 class select_all_component : public scene::Graph::Walker
2661 {
2662 bool m_select;
2663 SelectionSystem::EComponentMode m_mode;
2664 public:
2665 select_all_component( bool select, SelectionSystem::EComponentMode mode )
2666         : m_select( select ), m_mode( mode ){
2667 }
2668 bool pre( const scene::Path& path, scene::Instance& instance ) const {
2669         ComponentSelectionTestable* componentSelectionTestable = Instance_getComponentSelectionTestable( instance );
2670         if ( componentSelectionTestable ) {
2671                 componentSelectionTestable->setSelectedComponents( m_select, m_mode );
2672         }
2673         return true;
2674 }
2675 };
2676
2677 void Scene_SelectAll_Component( bool select, SelectionSystem::EComponentMode componentMode ){
2678         GlobalSceneGraph().traverse( select_all_component( select, componentMode ) );
2679 }
2680
2681
2682 // RadiantSelectionSystem
2683 class RadiantSelectionSystem :
2684         public SelectionSystem,
2685         public Translatable,
2686         public Rotatable,
2687         public Scalable,
2688         public Renderable
2689 {
2690 mutable Matrix4 m_pivot2world;
2691 Matrix4 m_pivot2world_start;
2692 Matrix4 m_manip2pivot_start;
2693 Translation m_translation;
2694 Rotation m_rotation;
2695 Scale m_scale;
2696 public:
2697 static Shader* m_state;
2698 bool m_bPreferPointEntsIn2D;
2699 private:
2700 EManipulatorMode m_manipulator_mode;
2701 Manipulator* m_manipulator;
2702
2703 // state
2704 bool m_undo_begun;
2705 EMode m_mode;
2706 EComponentMode m_componentmode;
2707
2708 SelectionCounter m_count_primitive;
2709 SelectionCounter m_count_component;
2710
2711 TranslateManipulator m_translate_manipulator;
2712 RotateManipulator m_rotate_manipulator;
2713 ScaleManipulator m_scale_manipulator;
2714 DragManipulator m_drag_manipulator;
2715 ClipManipulator m_clip_manipulator;
2716
2717 typedef SelectionList<scene::Instance> selection_t;
2718 selection_t m_selection;
2719 selection_t m_component_selection;
2720
2721 Signal1<const Selectable&> m_selectionChanged_callbacks;
2722
2723 void ConstructPivot() const;
2724 void setCustomPivotOrigin( Vector3& point ) const;
2725 public:
2726 AABB getSelectionAABB() const;
2727 private:
2728 mutable bool m_pivotChanged;
2729 bool m_pivot_moving;
2730 mutable bool m_pivotIsCustom;
2731
2732 void Scene_TestSelect( Selector& selector, SelectionTest& test, const View& view, SelectionSystem::EMode mode, SelectionSystem::EComponentMode componentMode );
2733
2734 bool nothingSelected() const {
2735         return ( Mode() == eComponent && m_count_component.empty() )
2736                    || ( Mode() == ePrimitive && m_count_primitive.empty() );
2737 }
2738
2739
2740 public:
2741 enum EModifier
2742 {
2743         eManipulator,
2744         eToggle,
2745         eReplace,
2746         eCycle,
2747         eSelect,
2748         eDeselect,
2749 };
2750
2751 RadiantSelectionSystem() :
2752         m_bPreferPointEntsIn2D( true ),
2753         m_undo_begun( false ),
2754         m_mode( ePrimitive ),
2755         m_componentmode( eDefault ),
2756         m_count_primitive( SelectionChangedCaller( *this ) ),
2757         m_count_component( SelectionChangedCaller( *this ) ),
2758         m_translate_manipulator( *this, 2, 64 ),
2759         m_rotate_manipulator( *this, 8, 64 ),
2760         m_scale_manipulator( *this, 0, 64 ),
2761         m_pivotChanged( false ),
2762         m_pivot_moving( false ),
2763         m_pivotIsCustom( false ){
2764         SetManipulatorMode( eTranslate );
2765         pivotChanged();
2766         addSelectionChangeCallback( PivotChangedSelectionCaller( *this ) );
2767         AddGridChangeCallback( PivotChangedCaller( *this ) );
2768 }
2769 void pivotChanged() const {
2770         m_pivotChanged = true;
2771         SceneChangeNotify();
2772 }
2773 typedef ConstMemberCaller<RadiantSelectionSystem, void(), &RadiantSelectionSystem::pivotChanged> PivotChangedCaller;
2774 void pivotChangedSelection( const Selectable& selectable ){
2775         pivotChanged();
2776 }
2777 typedef MemberCaller<RadiantSelectionSystem, void(const Selectable&), &RadiantSelectionSystem::pivotChangedSelection> PivotChangedSelectionCaller;
2778
2779 void SetMode( EMode mode ){
2780         if ( m_mode != mode ) {
2781                 m_mode = mode;
2782                 pivotChanged();
2783         }
2784 }
2785 EMode Mode() const {
2786         return m_mode;
2787 }
2788 void SetComponentMode( EComponentMode mode ){
2789         m_componentmode = mode;
2790 }
2791 EComponentMode ComponentMode() const {
2792         return m_componentmode;
2793 }
2794 void SetManipulatorMode( EManipulatorMode mode ){
2795         m_pivotIsCustom = false;
2796         m_manipulator_mode = mode;
2797         switch ( m_manipulator_mode )
2798         {
2799         case eTranslate: m_manipulator = &m_translate_manipulator; break;
2800         case eRotate: m_manipulator = &m_rotate_manipulator; break;
2801         case eScale: m_manipulator = &m_scale_manipulator; break;
2802         case eDrag: m_manipulator = &m_drag_manipulator; break;
2803         case eClip: m_manipulator = &m_clip_manipulator; break;
2804         }
2805         pivotChanged();
2806 }
2807 EManipulatorMode ManipulatorMode() const {
2808         return m_manipulator_mode;
2809 }
2810
2811 SelectionChangeCallback getObserver( EMode mode ){
2812         if ( mode == ePrimitive ) {
2813                 return makeCallback( m_count_primitive );
2814         }
2815         else
2816         {
2817                 return makeCallback( m_count_component );
2818         }
2819 }
2820 std::size_t countSelected() const {
2821         return m_count_primitive.size();
2822 }
2823 std::size_t countSelectedComponents() const {
2824         return m_count_component.size();
2825 }
2826 void onSelectedChanged( scene::Instance& instance, const Selectable& selectable ){
2827         if ( selectable.isSelected() ) {
2828                 m_selection.append( instance );
2829         }
2830         else
2831         {
2832                 m_selection.erase( instance );
2833         }
2834
2835         ASSERT_MESSAGE( m_selection.size() == m_count_primitive.size(), "selection-tracking error" );
2836 }
2837 void onComponentSelection( scene::Instance& instance, const Selectable& selectable ){
2838         if ( selectable.isSelected() ) {
2839                 m_component_selection.append( instance );
2840         }
2841         else
2842         {
2843                 m_component_selection.erase( instance );
2844         }
2845
2846         ASSERT_MESSAGE( m_component_selection.size() == m_count_component.size(), "selection-tracking error" );
2847 }
2848 scene::Instance& ultimateSelected() const {
2849         ASSERT_MESSAGE( m_selection.size() > 0, "no instance selected" );
2850         return m_selection.back();
2851 }
2852 scene::Instance& penultimateSelected() const {
2853         ASSERT_MESSAGE( m_selection.size() > 1, "only one instance selected" );
2854         return *( *( --( --m_selection.end() ) ) );
2855 }
2856 void setSelectedAll( bool selected ){
2857         GlobalSceneGraph().traverse( select_all( selected ) );
2858
2859         m_manipulator->setSelected( selected );
2860 }
2861 void setSelectedAllComponents( bool selected ){
2862         Scene_SelectAll_Component( selected, SelectionSystem::eVertex );
2863         Scene_SelectAll_Component( selected, SelectionSystem::eEdge );
2864         Scene_SelectAll_Component( selected, SelectionSystem::eFace );
2865
2866         m_manipulator->setSelected( selected );
2867 }
2868
2869 void foreachSelected( const Visitor& visitor ) const {
2870         selection_t::const_iterator i = m_selection.begin();
2871         while ( i != m_selection.end() )
2872         {
2873                 visitor.visit( *( *( i++ ) ) );
2874         }
2875 }
2876 void foreachSelectedComponent( const Visitor& visitor ) const {
2877         selection_t::const_iterator i = m_component_selection.begin();
2878         while ( i != m_component_selection.end() )
2879         {
2880                 visitor.visit( *( *( i++ ) ) );
2881         }
2882 }
2883
2884 void addSelectionChangeCallback( const SelectionChangeHandler& handler ){
2885         m_selectionChanged_callbacks.connectLast( handler );
2886 }
2887 void selectionChanged( const Selectable& selectable ){
2888         m_selectionChanged_callbacks( selectable );
2889 }
2890 typedef MemberCaller<RadiantSelectionSystem, void(const Selectable&), &RadiantSelectionSystem::selectionChanged> SelectionChangedCaller;
2891
2892
2893 void startMove(){
2894         m_pivot2world_start = GetPivot2World();
2895 }
2896
2897 bool SelectManipulator( const View& view, const float device_point[2], const float device_epsilon[2] ){
2898         if ( !nothingSelected() || ( ManipulatorMode() == eDrag && Mode() == eComponent ) ) {
2899 #if defined ( DEBUG_SELECTION )
2900                 g_render_clipped.destroy();
2901 #endif
2902
2903                 m_manipulator->setSelected( false );
2904
2905                 if ( !nothingSelected() || ( ManipulatorMode() == eDrag && Mode() == eComponent ) ) {
2906                         View scissored( view );
2907                         ConstructSelectionTest( scissored, SelectionBoxForPoint( device_point, device_epsilon ) );
2908                         m_manipulator->testSelect( scissored, GetPivot2World() );
2909                 }
2910
2911                 startMove();
2912
2913                 m_pivot_moving = m_manipulator->isSelected();
2914
2915                 if ( m_pivot_moving ) {
2916                         Pivot2World pivot;
2917                         pivot.update( GetPivot2World(), view.GetModelview(), view.GetProjection(), view.GetViewport() );
2918
2919                         m_manip2pivot_start = matrix4_multiplied_by_matrix4( matrix4_full_inverse( m_pivot2world_start ), pivot.m_worldSpace );
2920
2921                         Matrix4 device2manip;
2922                         ConstructDevice2Manip( device2manip, m_pivot2world_start, view.GetModelview(), view.GetProjection(), view.GetViewport() );
2923                         m_manipulator->GetManipulatable()->Construct( device2manip, device_point[0], device_point[1], getSelectionAABB(), vector4_to_vector3( GetPivot2World().t() ) );
2924
2925                         m_undo_begun = false;
2926                 }
2927
2928                 SceneChangeNotify();
2929         }
2930
2931         return m_pivot_moving;
2932 }
2933
2934 void deselectAll(){
2935         if ( Mode() == eComponent ) {
2936                 setSelectedAllComponents( false );
2937         }
2938         else
2939         {
2940                 setSelectedAll( false );
2941         }
2942 }
2943
2944 void deselectComponentsOrAll( bool components ){
2945         if ( components ) {
2946                 setSelectedAllComponents( false );
2947         }
2948         else
2949         {
2950                 deselectAll();
2951         }
2952 }
2953
2954 void SelectPoint( const View& view, const float device_point[2], const float device_epsilon[2], RadiantSelectionSystem::EModifier modifier, bool face ){
2955         //globalOutputStream() << device_point[0] << "   " << device_point[1] << "\n";
2956         ASSERT_MESSAGE( fabs( device_point[0] ) <= 1.0f && fabs( device_point[1] ) <= 1.0f, "point-selection error" );
2957
2958         if ( modifier == eReplace ) {
2959                 deselectComponentsOrAll( face );
2960         }
2961 /*
2962 //nothingSelected() doesn't consider faces, selected in non-component mode, m
2963         if ( modifier == eCycle && nothingSelected() ){
2964                 modifier = eReplace;
2965         }
2966 */
2967   #if defined ( DEBUG_SELECTION )
2968         g_render_clipped.destroy();
2969   #endif
2970
2971         {
2972                 View scissored( view );
2973                 ConstructSelectionTest( scissored, SelectionBoxForPoint( device_point, device_epsilon ) );
2974
2975                 SelectionVolume volume( scissored );
2976                 SelectionPool selector;
2977                 SelectionPool selector_point_ents;
2978                 const bool prefer_point_ents = m_bPreferPointEntsIn2D && Mode() == ePrimitive && !view.fill() && !face
2979                         && ( modifier == RadiantSelectionSystem::eReplace || modifier == RadiantSelectionSystem::eSelect || modifier == RadiantSelectionSystem::eDeselect );
2980
2981                 if( prefer_point_ents ){
2982                         Scene_TestSelect( selector_point_ents, volume, scissored, eEntity, ComponentMode() );
2983                 }
2984                 if( prefer_point_ents && !selector_point_ents.failed() ){
2985                         switch ( modifier )
2986                         {
2987                         // if cycle mode not enabled, enable it
2988                         case RadiantSelectionSystem::eReplace:
2989                         {
2990                                 // select closest
2991                                 ( *selector_point_ents.begin() ).second->setSelected( true );
2992                         }
2993                         break;
2994                         case RadiantSelectionSystem::eSelect:
2995                         {
2996                                 SelectionPool::iterator best = selector_point_ents.begin();
2997                                 if( !( *best ).second->isSelected() ){
2998                                         ( *best ).second->setSelected( true );
2999                                 }
3000                                 SelectionPool::iterator i = best;
3001                                 ++i;
3002                                 while ( i != selector_point_ents.end() )
3003                                 {
3004                                         if( ( *i ).first.equalEpsilon( ( *best ).first, 0.25f, 0.000001f ) ){
3005                                                 if( !( *i ).second->isSelected() ){
3006                                                         ( *i ).second->setSelected( true );
3007                                                 }
3008                                         }
3009                                         else{
3010                                                 break;
3011                                         }
3012                                         ++i;
3013                                 }
3014                         }
3015                         break;
3016                         case RadiantSelectionSystem::eDeselect:
3017                         {
3018                                 SelectionPool::iterator best = selector_point_ents.begin();
3019                                 if( ( *best ).second->isSelected() ){
3020                                         ( *best ).second->setSelected( false );
3021                                 }
3022                                 SelectionPool::iterator i = best;
3023                                 ++i;
3024                                 while ( i != selector_point_ents.end() )
3025                                 {
3026                                         if( ( *i ).first.equalEpsilon( ( *best ).first, 0.25f, 0.000001f ) ){
3027                                                 if( ( *i ).second->isSelected() ){
3028                                                         ( *i ).second->setSelected( false );
3029                                                 }
3030                                         }
3031                                         else{
3032                                                 break;
3033                                         }
3034                                         ++i;
3035                                 }
3036                         }
3037                         break;
3038                         default:
3039                                 break;
3040                         }
3041                 }
3042                 else{
3043                         if ( face ){
3044                                 Scene_TestSelect_Component( selector, volume, scissored, eFace );
3045                         }
3046                         else{
3047                                 Scene_TestSelect( selector, volume, scissored, Mode(), ComponentMode() );
3048                         }
3049
3050                         if ( !selector.failed() ) {
3051                                 switch ( modifier )
3052                                 {
3053                                 case RadiantSelectionSystem::eToggle:
3054                                 {
3055                                         SelectableSortedSet::iterator best = selector.begin();
3056                                         // toggle selection of the object with least depth
3057                                         if ( ( *best ).second->isSelected() ) {
3058                                                 ( *best ).second->setSelected( false );
3059                                         }
3060                                         else{
3061                                                 ( *best ).second->setSelected( true );
3062                                         }
3063                                 }
3064                                 break;
3065                                 // if cycle mode not enabled, enable it
3066                                 case RadiantSelectionSystem::eReplace:
3067                                 {
3068                                         // select closest
3069                                         ( *selector.begin() ).second->setSelected( true );
3070                                 }
3071                                 break;
3072                                 // select the next object in the list from the one already selected
3073                                 case RadiantSelectionSystem::eCycle:
3074                                 {
3075                                         bool CycleSelectionOccured = false;
3076                                         SelectionPool::iterator i = selector.begin();
3077                                         while ( i != selector.end() )
3078                                         {
3079                                                 if ( ( *i ).second->isSelected() ) {
3080                                                         deselectComponentsOrAll( face );
3081                                                         ++i;
3082                                                         if ( i != selector.end() ) {
3083                                                                 i->second->setSelected( true );
3084                                                         }
3085                                                         else
3086                                                         {
3087                                                                 selector.begin()->second->setSelected( true );
3088                                                         }
3089                                                         CycleSelectionOccured = true;
3090                                                         break;
3091                                                 }
3092                                                 ++i;
3093                                         }
3094                                         if( !CycleSelectionOccured ){
3095                                                 deselectComponentsOrAll( face );
3096                                                 ( *selector.begin() ).second->setSelected( true );
3097                                         }
3098                                 }
3099                                 break;
3100                                 case RadiantSelectionSystem::eSelect:
3101                                 {
3102                                         SelectionPool::iterator best = selector.begin();
3103                                         if( !( *best ).second->isSelected() ){
3104                                                 ( *best ).second->setSelected( true );
3105                                         }
3106                                         SelectionPool::iterator i = best;
3107                                         ++i;
3108                                         while ( i != selector.end() )
3109                                         {
3110                                                 if( ( *i ).first.equalEpsilon( ( *best ).first, 0.25f, 0.000001f ) ){
3111                                                         if( !( *i ).second->isSelected() ){
3112                                                                 ( *i ).second->setSelected( true );
3113                                                         }
3114                                                 }
3115                                                 else{
3116                                                         break;
3117                                                 }
3118                                                 ++i;
3119                                         }
3120                                 }
3121                                 break;
3122                                 case RadiantSelectionSystem::eDeselect:
3123                                 {
3124                                         SelectionPool::iterator best = selector.begin();
3125                                         if( ( *best ).second->isSelected() ){
3126                                                 ( *best ).second->setSelected( false );
3127                                         }
3128                                         SelectionPool::iterator i = best;
3129                                         ++i;
3130                                         while ( i != selector.end() )
3131                                         {
3132                                                 if( ( *i ).first.equalEpsilon( ( *best ).first, 0.25f, 0.000001f ) ){
3133                                                         if( ( *i ).second->isSelected() ){
3134                                                                 ( *i ).second->setSelected( false );
3135                                                         }
3136                                                 }
3137                                                 else{
3138                                                         break;
3139                                                 }
3140                                                 ++i;
3141                                         }
3142                                 }
3143                                 break;
3144                                 default:
3145                                         break;
3146                                 }
3147                         }
3148                         else if( modifier == eCycle ){
3149                                 deselectComponentsOrAll( face );
3150                         }
3151                 }
3152         }
3153 }
3154
3155 bool SelectPoint_InitPaint( const View& view, const float device_point[2], const float device_epsilon[2], bool face ){
3156         ASSERT_MESSAGE( fabs( device_point[0] ) <= 1.0f && fabs( device_point[1] ) <= 1.0f, "point-selection error" );
3157   #if defined ( DEBUG_SELECTION )
3158         g_render_clipped.destroy();
3159   #endif
3160
3161         {
3162                 View scissored( view );
3163                 ConstructSelectionTest( scissored, SelectionBoxForPoint( device_point, device_epsilon ) );
3164
3165                 SelectionVolume volume( scissored );
3166                 SelectionPool selector;
3167                 SelectionPool selector_point_ents;
3168                 const bool prefer_point_ents = m_bPreferPointEntsIn2D && Mode() == ePrimitive && !view.fill() && !face;
3169
3170                 if( prefer_point_ents ){
3171                         Scene_TestSelect( selector_point_ents, volume, scissored, eEntity, ComponentMode() );
3172                 }
3173                 if( prefer_point_ents && !selector_point_ents.failed() ){
3174                         SelectableSortedSet::iterator best = selector_point_ents.begin();
3175                         const bool wasSelected = ( *best ).second->isSelected();
3176                         ( *best ).second->setSelected( !wasSelected );
3177                         SelectableSortedSet::iterator i = best;
3178                         ++i;
3179                         while ( i != selector_point_ents.end() )
3180                         {
3181                                 if( ( *i ).first.equalEpsilon( ( *best ).first, 0.25f, 0.000001f ) ){
3182                                         ( *i ).second->setSelected( !wasSelected );
3183                                 }
3184                                 else{
3185                                         break;
3186                                 }
3187                                 ++i;
3188                         }
3189                         return !wasSelected;
3190                 }
3191                 else{//do primitives, if ents failed
3192                         if ( face ){
3193                                 Scene_TestSelect_Component( selector, volume, scissored, eFace );
3194                         }
3195                         else{
3196                                 Scene_TestSelect( selector, volume, scissored, Mode(), ComponentMode() );
3197                         }
3198                         if ( !selector.failed() ){
3199                                 SelectableSortedSet::iterator best = selector.begin();
3200                                 const bool wasSelected = ( *best ).second->isSelected();
3201                                 ( *best ).second->setSelected( !wasSelected );
3202                                 SelectableSortedSet::iterator i = best;
3203                                 ++i;
3204                                 while ( i != selector.end() )
3205                                 {
3206                                         if( ( *i ).first.equalEpsilon( ( *best ).first, 0.25f, 0.000001f ) ){
3207                                                 ( *i ).second->setSelected( !wasSelected );
3208                                         }
3209                                         else{
3210                                                 break;
3211                                         }
3212                                         ++i;
3213                                 }
3214                                 return !wasSelected;
3215                         }
3216                         else{
3217                                 return true;
3218                         }
3219                 }
3220         }
3221 }
3222
3223 void SelectArea( const View& view, const float device_point[2], const float device_delta[2], RadiantSelectionSystem::EModifier modifier, bool face ){
3224         if ( modifier == eReplace ) {
3225                 deselectComponentsOrAll( face );
3226         }
3227
3228   #if defined ( DEBUG_SELECTION )
3229         g_render_clipped.destroy();
3230   #endif
3231
3232         {
3233                 View scissored( view );
3234                 ConstructSelectionTest( scissored, SelectionBoxForArea( device_point, device_delta ) );
3235
3236                 SelectionVolume volume( scissored );
3237                 SelectionPool pool;
3238                 if ( face ) {
3239                         Scene_TestSelect_Component( pool, volume, scissored, eFace );
3240                 }
3241                 else
3242                 {
3243                         Scene_TestSelect( pool, volume, scissored, Mode(), ComponentMode() );
3244                 }
3245
3246                 for ( SelectionPool::iterator i = pool.begin(); i != pool.end(); ++i )
3247                 {
3248                         ( *i ).second->setSelected( !( modifier == RadiantSelectionSystem::eToggle && ( *i ).second->isSelected() ) );
3249                 }
3250         }
3251 }
3252
3253
3254 void translate( const Vector3& translation ){
3255         if ( !nothingSelected() ) {
3256                 //ASSERT_MESSAGE(!m_pivotChanged, "pivot is invalid");
3257
3258                 m_translation = translation;
3259
3260                 m_pivot2world = m_pivot2world_start;
3261                 matrix4_translate_by_vec3( m_pivot2world, translation );
3262
3263                 if ( Mode() == eComponent ) {
3264                         Scene_Translate_Component_Selected( GlobalSceneGraph(), m_translation );
3265                 }
3266                 else
3267                 {
3268                         Scene_Translate_Selected( GlobalSceneGraph(), m_translation );
3269                 }
3270
3271                 SceneChangeNotify();
3272         }
3273 }
3274 void outputTranslation( TextOutputStream& ostream ){
3275         ostream << " -xyz " << m_translation.x() << " " << m_translation.y() << " " << m_translation.z();
3276 }
3277 void rotate( const Quaternion& rotation ){
3278         if ( !nothingSelected() ) {
3279                 //ASSERT_MESSAGE(!m_pivotChanged, "pivot is invalid");
3280
3281                 m_rotation = rotation;
3282
3283                 if ( Mode() == eComponent ) {
3284                         Scene_Rotate_Component_Selected( GlobalSceneGraph(), m_rotation, vector4_to_vector3( m_pivot2world.t() ) );
3285
3286                         matrix4_assign_rotation_for_pivot( m_pivot2world, m_component_selection.back() );
3287                 }
3288                 else
3289                 {
3290                         Scene_Rotate_Selected( GlobalSceneGraph(), m_rotation, vector4_to_vector3( m_pivot2world.t() ) );
3291
3292                         matrix4_assign_rotation_for_pivot( m_pivot2world, m_selection.back() );
3293                 }
3294
3295                 SceneChangeNotify();
3296         }
3297 }
3298 void outputRotation( TextOutputStream& ostream ){
3299         ostream << " -eulerXYZ " << m_rotation.x() << " " << m_rotation.y() << " " << m_rotation.z();
3300 }
3301 void scale( const Vector3& scaling ){
3302         if ( !nothingSelected() ) {
3303                 m_scale = scaling;
3304
3305                 if ( Mode() == eComponent ) {
3306                         Scene_Scale_Component_Selected( GlobalSceneGraph(), m_scale, vector4_to_vector3( m_pivot2world.t() ) );
3307                 }
3308                 else
3309                 {
3310                         Scene_Scale_Selected( GlobalSceneGraph(), m_scale, vector4_to_vector3( m_pivot2world.t() ) );
3311                 }
3312
3313                 SceneChangeNotify();
3314         }
3315 }
3316 void outputScale( TextOutputStream& ostream ){
3317         ostream << " -scale " << m_scale.x() << " " << m_scale.y() << " " << m_scale.z();
3318 }
3319
3320 void rotateSelected( const Quaternion& rotation, bool snapOrigin ){
3321         if( snapOrigin && !m_pivotIsCustom ){
3322                 m_pivot2world.tx() = float_snapped( m_pivot2world.tx(), GetSnapGridSize() );
3323                 m_pivot2world.ty() = float_snapped( m_pivot2world.ty(), GetSnapGridSize() );
3324                 m_pivot2world.tz() = float_snapped( m_pivot2world.tz(), GetSnapGridSize() );
3325         }
3326         startMove();
3327         rotate( rotation );
3328         freezeTransforms();
3329 }
3330 void translateSelected( const Vector3& translation ){
3331         startMove();
3332         translate( translation );
3333         freezeTransforms();
3334 }
3335 void scaleSelected( const Vector3& scaling ){
3336         startMove();
3337         scale( scaling );
3338         freezeTransforms();
3339 }
3340
3341 void MoveSelected( const View& view, const float device_point[2], bool snap, bool snapbbox ){
3342         if ( m_manipulator->isSelected() ) {
3343                 if ( !m_undo_begun ) {
3344                         m_undo_begun = true;
3345                         GlobalUndoSystem().start();
3346                 }
3347
3348                 Matrix4 device2manip;
3349                 ConstructDevice2Manip( device2manip, m_pivot2world_start, view.GetModelview(), view.GetProjection(), view.GetViewport() );
3350                 m_manipulator->GetManipulatable()->Transform( m_manip2pivot_start, device2manip, device_point[0], device_point[1], snap, snapbbox );
3351         }
3352 }
3353
3354 /// \todo Support view-dependent nudge.
3355 void NudgeManipulator( const Vector3& nudge, const Vector3& view ){
3356         if ( ManipulatorMode() == eTranslate || ManipulatorMode() == eDrag ) {
3357                 translateSelected( nudge );
3358         }
3359 }
3360
3361 void endMove();
3362 void freezeTransforms();
3363
3364 void renderSolid( Renderer& renderer, const VolumeTest& volume ) const;
3365 void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const {
3366         renderSolid( renderer, volume );
3367 }
3368
3369 const Matrix4& GetPivot2World() const {
3370         ConstructPivot();
3371         return m_pivot2world;
3372 }
3373
3374 static void constructStatic(){
3375         m_state = GlobalShaderCache().capture( "$POINT" );
3376   #if defined( DEBUG_SELECTION )
3377         g_state_clipped = GlobalShaderCache().capture( "$DEBUG_CLIPPED" );
3378   #endif
3379         TranslateManipulator::m_state_wire = GlobalShaderCache().capture( "$WIRE_OVERLAY" );
3380         TranslateManipulator::m_state_fill = GlobalShaderCache().capture( "$FLATSHADE_OVERLAY" );
3381         RotateManipulator::m_state_outer = GlobalShaderCache().capture( "$WIRE_OVERLAY" );
3382 }
3383
3384 static void destroyStatic(){
3385   #if defined( DEBUG_SELECTION )
3386         GlobalShaderCache().release( "$DEBUG_CLIPPED" );
3387   #endif
3388         GlobalShaderCache().release( "$WIRE_OVERLAY" );
3389         GlobalShaderCache().release( "$FLATSHADE_OVERLAY" );
3390         GlobalShaderCache().release( "$WIRE_OVERLAY" );
3391         GlobalShaderCache().release( "$POINT" );
3392 }
3393 };
3394
3395 Shader* RadiantSelectionSystem::m_state = 0;
3396
3397
3398 namespace
3399 {
3400 RadiantSelectionSystem* g_RadiantSelectionSystem;
3401
3402 inline RadiantSelectionSystem& getSelectionSystem(){
3403         return *g_RadiantSelectionSystem;
3404 }
3405 }
3406
3407 #include "map.h"
3408
3409 class testselect_entity_visible : public scene::Graph::Walker
3410 {
3411 Selector& m_selector;
3412 SelectionTest& m_test;
3413 public:
3414 testselect_entity_visible( Selector& selector, SelectionTest& test )
3415         : m_selector( selector ), m_test( test ){
3416 }
3417 bool pre( const scene::Path& path, scene::Instance& instance ) const {
3418         if( path.top().get_pointer() == Map_GetWorldspawn( g_map ) ||
3419                 node_is_group( path.top().get() ) ){
3420                 return false;
3421         }
3422         Selectable* selectable = Instance_getSelectable( instance );
3423         if ( selectable != 0
3424                  && Node_isEntity( path.top() ) ) {
3425                 m_selector.pushSelectable( *selectable );
3426         }
3427
3428         SelectionTestable* selectionTestable = Instance_getSelectionTestable( instance );
3429         if ( selectionTestable ) {
3430                 selectionTestable->testSelect( m_selector, m_test );
3431         }
3432
3433         return true;
3434 }
3435 void post( const scene::Path& path, scene::Instance& instance ) const {
3436         Selectable* selectable = Instance_getSelectable( instance );
3437         if ( selectable != 0
3438                  && Node_isEntity( path.top() ) ) {
3439                 m_selector.popSelectable();
3440         }
3441 }
3442 };
3443
3444 class testselect_primitive_visible : public scene::Graph::Walker
3445 {
3446 Selector& m_selector;
3447 SelectionTest& m_test;
3448 public:
3449 testselect_primitive_visible( Selector& selector, SelectionTest& test )
3450         : m_selector( selector ), m_test( test ){
3451 }
3452 bool pre( const scene::Path& path, scene::Instance& instance ) const {
3453         Selectable* selectable = Instance_getSelectable( instance );
3454         if ( selectable != 0 ) {
3455                 m_selector.pushSelectable( *selectable );
3456         }
3457
3458         SelectionTestable* selectionTestable = Instance_getSelectionTestable( instance );
3459         if ( selectionTestable ) {
3460                 selectionTestable->testSelect( m_selector, m_test );
3461         }
3462
3463         return true;
3464 }
3465 void post( const scene::Path& path, scene::Instance& instance ) const {
3466         Selectable* selectable = Instance_getSelectable( instance );
3467         if ( selectable != 0 ) {
3468                 m_selector.popSelectable();
3469         }
3470 }
3471 };
3472
3473 class testselect_component_visible : public scene::Graph::Walker
3474 {
3475 Selector& m_selector;
3476 SelectionTest& m_test;
3477 SelectionSystem::EComponentMode m_mode;
3478 public:
3479 testselect_component_visible( Selector& selector, SelectionTest& test, SelectionSystem::EComponentMode mode )
3480         : m_selector( selector ), m_test( test ), m_mode( mode ){
3481 }
3482 bool pre( const scene::Path& path, scene::Instance& instance ) const {
3483         ComponentSelectionTestable* componentSelectionTestable = Instance_getComponentSelectionTestable( instance );
3484         if ( componentSelectionTestable ) {
3485                 componentSelectionTestable->testSelectComponents( m_selector, m_test, m_mode );
3486         }
3487
3488         return true;
3489 }
3490 };
3491
3492
3493 class testselect_component_visible_selected : public scene::Graph::Walker
3494 {
3495 Selector& m_selector;
3496 SelectionTest& m_test;
3497 SelectionSystem::EComponentMode m_mode;
3498 public:
3499 testselect_component_visible_selected( Selector& selector, SelectionTest& test, SelectionSystem::EComponentMode mode )
3500         : m_selector( selector ), m_test( test ), m_mode( mode ){
3501 }
3502 bool pre( const scene::Path& path, scene::Instance& instance ) const {
3503         Selectable* selectable = Instance_getSelectable( instance );
3504         if ( selectable != 0 && selectable->isSelected() ) {
3505                 ComponentSelectionTestable* componentSelectionTestable = Instance_getComponentSelectionTestable( instance );
3506                 if ( componentSelectionTestable ) {
3507                         componentSelectionTestable->testSelectComponents( m_selector, m_test, m_mode );
3508                 }
3509         }
3510
3511         return true;
3512 }
3513 };
3514
3515 void Scene_TestSelect_Primitive( Selector& selector, SelectionTest& test, const VolumeTest& volume ){
3516         Scene_forEachVisible( GlobalSceneGraph(), volume, testselect_primitive_visible( selector, test ) );
3517 }
3518
3519 void Scene_TestSelect_Component_Selected( Selector& selector, SelectionTest& test, const VolumeTest& volume, SelectionSystem::EComponentMode componentMode ){
3520         Scene_forEachVisible( GlobalSceneGraph(), volume, testselect_component_visible_selected( selector, test, componentMode ) );
3521 }
3522
3523 void Scene_TestSelect_Component( Selector& selector, SelectionTest& test, const VolumeTest& volume, SelectionSystem::EComponentMode componentMode ){
3524         Scene_forEachVisible( GlobalSceneGraph(), volume, testselect_component_visible( selector, test, componentMode ) );
3525 }
3526
3527 void RadiantSelectionSystem::Scene_TestSelect( Selector& selector, SelectionTest& test, const View& view, SelectionSystem::EMode mode, SelectionSystem::EComponentMode componentMode ){
3528         switch ( mode )
3529         {
3530         case eEntity:
3531         {
3532                 Scene_forEachVisible( GlobalSceneGraph(), view, testselect_entity_visible( selector, test ) );
3533         }
3534         break;
3535         case ePrimitive:
3536                 Scene_TestSelect_Primitive( selector, test, view );
3537                 break;
3538         case eComponent:
3539                 Scene_TestSelect_Component_Selected( selector, test, view, componentMode );
3540                 break;
3541         }
3542 }
3543
3544 class FreezeTransforms : public scene::Graph::Walker
3545 {
3546 public:
3547 bool pre( const scene::Path& path, scene::Instance& instance ) const {
3548         TransformNode* transformNode = Node_getTransformNode( path.top() );
3549         if ( transformNode != 0 ) {
3550                 Transformable* transform = Instance_getTransformable( instance );
3551                 if ( transform != 0 ) {
3552                         transform->freezeTransform();
3553                 }
3554         }
3555         return true;
3556 }
3557 };
3558
3559 void RadiantSelectionSystem::freezeTransforms(){
3560         GlobalSceneGraph().traverse( FreezeTransforms() );
3561 }
3562
3563
3564 void RadiantSelectionSystem::endMove(){
3565         freezeTransforms();
3566
3567         if ( Mode() == ePrimitive ) {
3568                 if ( ManipulatorMode() == eDrag ) {
3569                         Scene_SelectAll_Component( false, SelectionSystem::eFace );
3570                 }
3571         }
3572
3573         m_pivot_moving = false;
3574         pivotChanged();
3575
3576         SceneChangeNotify();
3577
3578         if ( m_undo_begun ) {
3579                 StringOutputStream command;
3580
3581                 if ( ManipulatorMode() == eTranslate ) {
3582                         command << "translateTool";
3583                         outputTranslation( command );
3584                 }
3585                 else if ( ManipulatorMode() == eRotate ) {
3586                         command << "rotateTool";
3587                         outputRotation( command );
3588                 }
3589                 else if ( ManipulatorMode() == eScale ) {
3590                         command << "scaleTool";
3591                         outputScale( command );
3592                 }
3593                 else if ( ManipulatorMode() == eDrag ) {
3594                         command << "dragTool";
3595                 }
3596
3597                 GlobalUndoSystem().finish( command.c_str() );
3598         }
3599
3600 }
3601
3602 inline AABB Instance_getPivotBounds( scene::Instance& instance ){
3603         Entity* entity = Node_getEntity( instance.path().top() );
3604         if ( entity != 0
3605                  && ( entity->getEntityClass().fixedsize
3606                           || !node_is_group( instance.path().top() ) ) ) {
3607                 Editable* editable = Node_getEditable( instance.path().top() );
3608                 if ( editable != 0 ) {
3609                         return AABB( vector4_to_vector3( matrix4_multiplied_by_matrix4( instance.localToWorld(), editable->getLocalPivot() ).t() ), Vector3( 0, 0, 0 ) );
3610                 }
3611                 else
3612                 {
3613                         return AABB( vector4_to_vector3( instance.localToWorld().t() ), Vector3( 0, 0, 0 ) );
3614                 }
3615         }
3616
3617         return instance.worldAABB();
3618 }
3619
3620 class bounds_selected : public scene::Graph::Walker
3621 {
3622 AABB& m_bounds;
3623 public:
3624 bounds_selected( AABB& bounds )
3625         : m_bounds( bounds ){
3626         m_bounds = AABB();
3627 }
3628 bool pre( const scene::Path& path, scene::Instance& instance ) const {
3629         Selectable* selectable = Instance_getSelectable( instance );
3630         if ( selectable != 0
3631                  && selectable->isSelected() ) {
3632                 aabb_extend_by_aabb_safe( m_bounds, Instance_getPivotBounds( instance ) );
3633         }
3634         return true;
3635 }
3636 };
3637
3638 class bounds_selected_component : public scene::Graph::Walker
3639 {
3640 AABB& m_bounds;
3641 public:
3642 bounds_selected_component( AABB& bounds )
3643         : m_bounds( bounds ){
3644         m_bounds = AABB();
3645 }
3646 bool pre( const scene::Path& path, scene::Instance& instance ) const {
3647         Selectable* selectable = Instance_getSelectable( instance );
3648         if ( selectable != 0
3649                  && selectable->isSelected() ) {
3650                 ComponentEditable* componentEditable = Instance_getComponentEditable( instance );
3651                 if ( componentEditable ) {
3652                         aabb_extend_by_aabb_safe( m_bounds, aabb_for_oriented_aabb_safe( componentEditable->getSelectedComponentsBounds(), instance.localToWorld() ) );
3653                 }
3654         }
3655         return true;
3656 }
3657 };
3658
3659 void Scene_BoundsSelected( scene::Graph& graph, AABB& bounds ){
3660         graph.traverse( bounds_selected( bounds ) );
3661 }
3662
3663 void Scene_BoundsSelectedComponent( scene::Graph& graph, AABB& bounds ){
3664         graph.traverse( bounds_selected_component( bounds ) );
3665 }
3666
3667 #if 0
3668 inline void pivot_for_node( Matrix4& pivot, scene::Node& node, scene::Instance& instance ){
3669         ComponentEditable* componentEditable = Instance_getComponentEditable( instance );
3670         if ( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent
3671                  && componentEditable != 0 ) {
3672                 pivot = matrix4_translation_for_vec3( componentEditable->getSelectedComponentsBounds().origin );
3673         }
3674         else
3675         {
3676                 Bounded* bounded = Instance_getBounded( instance );
3677                 if ( bounded != 0 ) {
3678                         pivot = matrix4_translation_for_vec3( bounded->localAABB().origin );
3679                 }
3680                 else
3681                 {
3682                         pivot = g_matrix4_identity;
3683                 }
3684         }
3685 }
3686 #endif
3687
3688 void RadiantSelectionSystem::ConstructPivot() const {
3689         if ( !m_pivotChanged || m_pivot_moving || m_pivotIsCustom ) {
3690                 return;
3691         }
3692         m_pivotChanged = false;
3693
3694         Vector3 m_object_pivot;
3695
3696         if ( !nothingSelected() ) {
3697                 {
3698                         AABB bounds;
3699                         if ( Mode() == eComponent ) {
3700                                 Scene_BoundsSelectedComponent( GlobalSceneGraph(), bounds );
3701                         }
3702                         else
3703                         {
3704                                 Scene_BoundsSelected( GlobalSceneGraph(), bounds );
3705                         }
3706                         m_object_pivot = bounds.origin;
3707                 }
3708
3709                 //vector3_snap( m_object_pivot, GetSnapGridSize() );
3710                 //globalOutputStream() << m_object_pivot << "\n";
3711                 m_pivot2world = matrix4_translation_for_vec3( m_object_pivot );
3712
3713                 switch ( m_manipulator_mode )
3714                 {
3715                 case eTranslate:
3716                         break;
3717                 case eRotate:
3718                         if ( Mode() == eComponent ) {
3719                                 matrix4_assign_rotation_for_pivot( m_pivot2world, m_component_selection.back() );
3720                         }
3721                         else
3722                         {
3723                                 matrix4_assign_rotation_for_pivot( m_pivot2world, m_selection.back() );
3724                         }
3725                         break;
3726                 case eScale:
3727                         if ( Mode() == eComponent ) {
3728                                 matrix4_assign_rotation_for_pivot( m_pivot2world, m_component_selection.back() );
3729                         }
3730                         else
3731                         {
3732                                 matrix4_assign_rotation_for_pivot( m_pivot2world, m_selection.back() );
3733                         }
3734                         break;
3735                 default:
3736                         break;
3737                 }
3738         }
3739 }
3740
3741 void RadiantSelectionSystem::setCustomPivotOrigin( Vector3& point ) const {
3742         if ( !nothingSelected() && ( m_manipulator_mode == eTranslate || m_manipulator_mode == eRotate || m_manipulator_mode == eScale ) ) {
3743                 AABB bounds;
3744                 if ( Mode() == eComponent ) {
3745                         Scene_BoundsSelectedComponent( GlobalSceneGraph(), bounds );
3746                 }
3747                 else
3748                 {
3749                         Scene_BoundsSelected( GlobalSceneGraph(), bounds );
3750                 }
3751                 //globalOutputStream() << point << "\n";
3752                 for( std::size_t i = 0; i < 3; i++ ){
3753                         if( point[i] < 900000.0f ){
3754                                 float bestsnapDist = fabs( bounds.origin[i] - point[i] );
3755                                 float bestsnapTo = bounds.origin[i];
3756                                 float othersnapDist = fabs( bounds.origin[i] + bounds.extents[i] - point[i] );
3757                                 if( othersnapDist < bestsnapDist ){
3758                                         bestsnapDist = othersnapDist;
3759                                         bestsnapTo = bounds.origin[i] + bounds.extents[i];
3760                                 }
3761                                 othersnapDist = fabs( bounds.origin[i] - bounds.extents[i] - point[i] );
3762                                 if( othersnapDist < bestsnapDist ){
3763                                         bestsnapDist = othersnapDist;
3764                                         bestsnapTo = bounds.origin[i] - bounds.extents[i];
3765                                 }
3766                                 othersnapDist = fabs( float_snapped( point[i], GetSnapGridSize() ) - point[i] );
3767                                 if( othersnapDist < bestsnapDist ){
3768                                         bestsnapDist = othersnapDist;
3769                                         bestsnapTo = float_snapped( point[i], GetSnapGridSize() );
3770                                 }
3771                                 point[i] = bestsnapTo;
3772
3773                                 m_pivot2world[i + 12] = point[i]; //m_pivot2world.tx() .ty() .tz()
3774                         }
3775                 }
3776
3777                 switch ( m_manipulator_mode )
3778                 {
3779                 case eTranslate:
3780                         break;
3781                 case eRotate:
3782                         if ( Mode() == eComponent ) {
3783                                 matrix4_assign_rotation_for_pivot( m_pivot2world, m_component_selection.back() );
3784                         }
3785                         else
3786                         {
3787                                 matrix4_assign_rotation_for_pivot( m_pivot2world, m_selection.back() );
3788                         }
3789                         break;
3790                 case eScale:
3791                         if ( Mode() == eComponent ) {
3792                                 matrix4_assign_rotation_for_pivot( m_pivot2world, m_component_selection.back() );
3793                         }
3794                         else
3795                         {
3796                                 matrix4_assign_rotation_for_pivot( m_pivot2world, m_selection.back() );
3797                         }
3798                         break;
3799                 default:
3800                         break;
3801                 }
3802
3803                 m_pivotIsCustom = true;
3804         }
3805 }
3806
3807 AABB RadiantSelectionSystem::getSelectionAABB() const {
3808         AABB bounds;
3809         if ( !nothingSelected() ) {
3810                 if ( Mode() == eComponent ) {
3811                         Scene_BoundsSelectedComponent( GlobalSceneGraph(), bounds );
3812                 }
3813                 else
3814                 {
3815                         Scene_BoundsSelected( GlobalSceneGraph(), bounds );
3816                 }
3817         }
3818         return bounds;
3819 }
3820
3821 void RadiantSelectionSystem::renderSolid( Renderer& renderer, const VolumeTest& volume ) const {
3822         //if(view->TestPoint(m_object_pivot))
3823         if ( !nothingSelected() ) {
3824                 renderer.Highlight( Renderer::ePrimitive, false );
3825                 renderer.Highlight( Renderer::eFace, false );
3826
3827                 renderer.SetState( m_state, Renderer::eWireframeOnly );
3828                 renderer.SetState( m_state, Renderer::eFullMaterials );
3829
3830                 m_manipulator->render( renderer, volume, GetPivot2World() );
3831         }
3832
3833 #if defined( DEBUG_SELECTION )
3834         renderer.SetState( g_state_clipped, Renderer::eWireframeOnly );
3835         renderer.SetState( g_state_clipped, Renderer::eFullMaterials );
3836         renderer.addRenderable( g_render_clipped, g_render_clipped.m_world );
3837 #endif
3838 }
3839
3840 #include "preferencesystem.h"
3841 #include "preferences.h"
3842
3843 void SelectionSystem_constructPreferences( PreferencesPage& page ){
3844         page.appendCheckBox( "", "Prefer point entities in 2D", getSelectionSystem().m_bPreferPointEntsIn2D );
3845 }
3846 void SelectionSystem_constructPage( PreferenceGroup& group ){
3847         PreferencesPage page( group.createPage( "Selection", "Selection System Settings" ) );
3848         SelectionSystem_constructPreferences( page );
3849 }
3850 void SelectionSystem_registerPreferencesPage(){
3851         PreferencesDialog_addSettingsPage( FreeCaller<void(PreferenceGroup&), SelectionSystem_constructPage>() );
3852 }
3853
3854
3855
3856 void SelectionSystem_OnBoundsChanged(){
3857         getSelectionSystem().pivotChanged();
3858 }
3859
3860 SignalHandlerId SelectionSystem_boundsChanged;
3861
3862 void SelectionSystem_Construct(){
3863         RadiantSelectionSystem::constructStatic();
3864
3865         g_RadiantSelectionSystem = new RadiantSelectionSystem;
3866
3867         SelectionSystem_boundsChanged = GlobalSceneGraph().addBoundsChangedCallback( FreeCaller<void(), SelectionSystem_OnBoundsChanged>() );
3868
3869         GlobalShaderCache().attachRenderable( getSelectionSystem() );
3870
3871         GlobalPreferenceSystem().registerPreference( "PreferPointEntsIn2D", make_property_string( getSelectionSystem().m_bPreferPointEntsIn2D ) );
3872         SelectionSystem_registerPreferencesPage();
3873 }
3874
3875 void SelectionSystem_Destroy(){
3876         GlobalShaderCache().detachRenderable( getSelectionSystem() );
3877
3878         GlobalSceneGraph().removeBoundsChangedCallback( SelectionSystem_boundsChanged );
3879
3880         delete g_RadiantSelectionSystem;
3881
3882         RadiantSelectionSystem::destroyStatic();
3883 }
3884
3885
3886
3887
3888 inline float screen_normalised( float pos, std::size_t size ){
3889         return ( ( 2.0f * pos ) / size ) - 1.0f;
3890 }
3891
3892 typedef Vector2 DeviceVector;
3893
3894 inline DeviceVector window_to_normalised_device( WindowVector window, std::size_t width, std::size_t height ){
3895         return DeviceVector( screen_normalised( window.x(), width ), screen_normalised( height - 1 - window.y(), height ) );
3896 }
3897
3898 inline float device_constrained( float pos ){
3899         return std::min( 1.0f, std::max( -1.0f, pos ) );
3900 }
3901
3902 inline DeviceVector device_constrained( DeviceVector device ){
3903         return DeviceVector( device_constrained( device.x() ), device_constrained( device.y() ) );
3904 }
3905
3906 inline float window_constrained( float pos, std::size_t origin, std::size_t size ){
3907         return std::min( static_cast<float>( origin + size ), std::max( static_cast<float>( origin ), pos ) );
3908 }
3909
3910 inline WindowVector window_constrained( WindowVector window, std::size_t x, std::size_t y, std::size_t width, std::size_t height ){
3911         return WindowVector( window_constrained( window.x(), x, width ), window_constrained( window.y(), y, height ) );
3912 }
3913
3914 typedef Callback<void(DeviceVector)> MouseEventCallback;
3915
3916 Single<MouseEventCallback> g_mouseMovedCallback;
3917 Single<MouseEventCallback> g_mouseUpCallback;
3918
3919 #if 1
3920 const ButtonIdentifier c_button_select = c_buttonLeft;
3921 const ButtonIdentifier c_button_select2 = c_buttonRight;
3922 const ModifierFlags c_modifier_manipulator = c_modifierNone;
3923 const ModifierFlags c_modifier_toggle = c_modifierShift;
3924 const ModifierFlags c_modifier_replace = c_modifierShift | c_modifierAlt;
3925 const ModifierFlags c_modifier_face = c_modifierControl;
3926 #else
3927 const ButtonIdentifier c_button_select = c_buttonLeft;
3928 const ModifierFlags c_modifier_manipulator = c_modifierNone;
3929 const ModifierFlags c_modifier_toggle = c_modifierControl;
3930 const ModifierFlags c_modifier_replace = c_modifierNone;
3931 const ModifierFlags c_modifier_face = c_modifierShift;
3932 #endif
3933 const ModifierFlags c_modifier_toggle_face = c_modifier_toggle | c_modifier_face;
3934 const ModifierFlags c_modifier_replace_face = c_modifier_replace | c_modifier_face;
3935
3936 const ButtonIdentifier c_button_texture = c_buttonMiddle;
3937 const ModifierFlags c_modifier_apply_texture1 = c_modifierControl | c_modifierShift;
3938 const ModifierFlags c_modifier_apply_texture2 = c_modifierControl;
3939 const ModifierFlags c_modifier_apply_texture3 =                     c_modifierShift;
3940 const ModifierFlags c_modifier_copy_texture = c_modifierNone;
3941
3942 class Selector_
3943 {
3944 RadiantSelectionSystem::EModifier modifier_for_state( ModifierFlags state ){
3945         if ( ( state == c_modifier_toggle || state == c_modifier_toggle_face || state == c_modifier_face ) ) {
3946                 if( m_mouse2 ){
3947                         return RadiantSelectionSystem::eReplace;
3948                 }
3949                 else{
3950                         return RadiantSelectionSystem::eToggle;
3951                 }
3952         }
3953         return RadiantSelectionSystem::eManipulator;
3954 }
3955
3956 rect_t getDeviceArea() const {
3957         DeviceVector delta( m_current - m_start );
3958         if ( selecting() && fabs( delta.x() ) > m_epsilon.x() && fabs( delta.y() ) > m_epsilon.y() ) {
3959                 return SelectionBoxForArea( &m_start[0], &delta[0] );
3960         }
3961         else
3962         {
3963                 rect_t default_area = { { 0, 0, }, { 0, 0, }, };
3964                 return default_area;
3965         }
3966 }
3967
3968 public:
3969 DeviceVector m_start;
3970 DeviceVector m_current;
3971 DeviceVector m_epsilon;
3972 ModifierFlags m_state;
3973 bool m_mouse2;
3974 bool m_mouseMoved;
3975 bool m_mouseMovedWhilePressed;
3976 bool m_paintSelect;
3977 const View* m_view;
3978 RectangleCallback m_window_update;
3979
3980 Selector_() : m_start( 0.0f, 0.0f ), m_current( 0.0f, 0.0f ), m_state( c_modifierNone ), m_mouse2( false ), m_mouseMoved( false ), m_mouseMovedWhilePressed( false ){
3981 }
3982
3983 void draw_area(){
3984         m_window_update( getDeviceArea() );
3985 }
3986
3987 void testSelect( DeviceVector position ){
3988         RadiantSelectionSystem::EModifier modifier = modifier_for_state( m_state );
3989         if ( modifier != RadiantSelectionSystem::eManipulator ) {
3990                 DeviceVector delta( position - m_start );
3991                 if ( fabs( delta.x() ) > m_epsilon.x() && fabs( delta.y() ) > m_epsilon.y() ) {
3992                         DeviceVector delta( position - m_start );
3993                         //getSelectionSystem().SelectArea( *m_view, &m_start[0], &delta[0], modifier, ( m_state & c_modifier_face ) != c_modifierNone );
3994                         getSelectionSystem().SelectArea( *m_view, &m_start[0], &delta[0], RadiantSelectionSystem::eToggle, ( m_state & c_modifier_face ) != c_modifierNone );
3995                 }
3996                 else if( !m_mouseMovedWhilePressed ){
3997                         if ( modifier == RadiantSelectionSystem::eReplace && !m_mouseMoved ) {
3998                                 modifier = RadiantSelectionSystem::eCycle;
3999                         }
4000                         getSelectionSystem().SelectPoint( *m_view, &position[0], &m_epsilon[0], modifier, ( m_state & c_modifier_face ) != c_modifierNone );
4001                 }
4002         }
4003
4004         m_start = m_current = DeviceVector( 0.0f, 0.0f );
4005         draw_area();
4006 }
4007
4008 void testSelect_simpleM1( DeviceVector position ){
4009         /*RadiantSelectionSystem::EModifier modifier = RadiantSelectionSystem::eReplace;
4010         DeviceVector delta( position - m_start );
4011         if ( fabs( delta.x() ) < m_epsilon.x() && fabs( delta.y() ) < m_epsilon.y() ) {
4012                 modifier = RadiantSelectionSystem::eCycle;
4013         }
4014         getSelectionSystem().SelectPoint( *m_view, &position[0], &m_epsilon[0], modifier, false );*/
4015         getSelectionSystem().SelectPoint( *m_view, &position[0], &m_epsilon[0], m_mouseMoved ? RadiantSelectionSystem::eReplace : RadiantSelectionSystem::eCycle, false );
4016         m_start = m_current = device_constrained( position );
4017 }
4018
4019
4020 bool selecting() const {
4021         return m_state != c_modifier_manipulator && m_mouse2;
4022 }
4023
4024 void setState( ModifierFlags state ){
4025         bool was_selecting = selecting();
4026         m_state = state;
4027         if ( was_selecting ^ selecting() ) {
4028                 draw_area();
4029         }
4030 }
4031
4032 ModifierFlags getState() const {
4033         return m_state;
4034 }
4035
4036 void modifierEnable( ModifierFlags type ){
4037         setState( bitfield_enable( getState(), type ) );
4038 }
4039 void modifierDisable( ModifierFlags type ){
4040         setState( bitfield_disable( getState(), type ) );
4041 }
4042
4043 void mouseDown( DeviceVector position ){
4044         m_start = m_current = device_constrained( position );
4045         if( !m_mouse2 && m_state != c_modifierNone ){
4046                 m_paintSelect = getSelectionSystem().SelectPoint_InitPaint( *m_view, &position[0], &m_epsilon[0], ( m_state & c_modifier_face ) != c_modifierNone );
4047         }
4048 }
4049
4050 void mouseMoved( DeviceVector position ){
4051         m_current = device_constrained( position );
4052         m_mouseMovedWhilePressed = true;
4053         if( m_mouse2 ){
4054                 draw_area();
4055         }
4056         else if( m_state != c_modifier_manipulator ){
4057                 getSelectionSystem().SelectPoint( *m_view, &m_current[0], &m_epsilon[0],
4058                                                                                 m_paintSelect ? RadiantSelectionSystem::eSelect : RadiantSelectionSystem::eDeselect,
4059                                                                                 ( m_state & c_modifier_face ) != c_modifierNone );
4060         }
4061 }
4062 typedef MemberCaller<Selector_, void(DeviceVector), &Selector_::mouseMoved> MouseMovedCaller;
4063
4064 void mouseUp( DeviceVector position ){
4065         if( m_mouse2 ){
4066                 testSelect( device_constrained( position ) );
4067         }
4068         else{
4069                 m_start = m_current = DeviceVector( 0.0f, 0.0f );
4070         }
4071
4072         g_mouseMovedCallback.clear();
4073         g_mouseUpCallback.clear();
4074 }
4075 typedef MemberCaller<Selector_, void(DeviceVector), &Selector_::mouseUp> MouseUpCaller;
4076 };
4077
4078
4079 class Manipulator_
4080 {
4081 public:
4082 DeviceVector m_epsilon;
4083 const View* m_view;
4084 ModifierFlags m_state;
4085
4086 Manipulator_() : m_state( c_modifierNone ){
4087 }
4088
4089 bool mouseDown( DeviceVector position ){
4090         return getSelectionSystem().SelectManipulator( *m_view, &position[0], &m_epsilon[0] );
4091 }
4092
4093 void mouseMoved( DeviceVector position ){
4094         getSelectionSystem().MoveSelected( *m_view, &position[0], ( m_state & c_modifierShift ) == c_modifierShift, ( m_state & c_modifierControl ) == c_modifierControl );
4095 }
4096 typedef MemberCaller<Manipulator_, void(DeviceVector), &Manipulator_::mouseMoved> MouseMovedCaller;
4097
4098 void mouseUp( DeviceVector position ){
4099         getSelectionSystem().endMove();
4100         g_mouseMovedCallback.clear();
4101         g_mouseUpCallback.clear();
4102 }
4103 typedef MemberCaller<Manipulator_, void(DeviceVector), &Manipulator_::mouseUp> MouseUpCaller;
4104
4105 void setState( ModifierFlags state ){
4106         m_state = state;
4107 }
4108
4109 ModifierFlags getState() const {
4110         return m_state;
4111 }
4112
4113 void modifierEnable( ModifierFlags type ){
4114         setState( bitfield_enable( getState(), type ) );
4115 }
4116 void modifierDisable( ModifierFlags type ){
4117         setState( bitfield_disable( getState(), type ) );
4118 }
4119 };
4120
4121 void Scene_copyClosestTexture( SelectionTest& test );
4122 void Scene_applyClosestTexture( SelectionTest& test );
4123
4124 class RadiantWindowObserver : public SelectionSystemWindowObserver
4125 {
4126 enum
4127 {
4128         SELECT_EPSILON = 8,
4129 };
4130
4131 int m_width;
4132 int m_height;
4133
4134 bool m_mouse_down;
4135
4136 public:
4137 Selector_ m_selector;
4138 Manipulator_ m_manipulator;
4139
4140 RadiantWindowObserver() : m_mouse_down( false ){
4141 }
4142 void release(){
4143         delete this;
4144 }
4145 void setView( const View& view ){
4146         m_selector.m_view = &view;
4147         m_manipulator.m_view = &view;
4148 }
4149 void setRectangleDrawCallback( const RectangleCallback& callback ){
4150         m_selector.m_window_update = callback;
4151 }
4152 void onSizeChanged( int width, int height ){
4153         m_width = width;
4154         m_height = height;
4155         DeviceVector epsilon( SELECT_EPSILON / static_cast<float>( m_width ), SELECT_EPSILON / static_cast<float>( m_height ) );
4156         m_selector.m_epsilon = m_manipulator.m_epsilon = epsilon;
4157 }
4158 void onMouseDown( const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers ){
4159         if ( button == c_button_select || ( button == c_button_select2 && modifiers != c_modifierNone ) ) {
4160                 m_mouse_down = true;
4161                 //m_selector.m_mouseMoved = false;
4162
4163                 DeviceVector devicePosition( window_to_normalised_device( position, m_width, m_height ) );
4164                 if ( modifiers == c_modifier_manipulator && m_manipulator.mouseDown( devicePosition ) ) {
4165                         g_mouseMovedCallback.insert( MouseEventCallback( Manipulator_::MouseMovedCaller( m_manipulator ) ) );
4166                         g_mouseUpCallback.insert( MouseEventCallback( Manipulator_::MouseUpCaller( m_manipulator ) ) );
4167                 }
4168                 else
4169                 {
4170                         if ( button == c_button_select ) {
4171                                 m_selector.m_mouse2 = false;
4172                         }
4173                         else{
4174                                 m_selector.m_mouse2 = true;
4175                         }
4176                         m_selector.mouseDown( devicePosition );
4177                         g_mouseMovedCallback.insert( MouseEventCallback( Selector_::MouseMovedCaller( m_selector ) ) );
4178                         g_mouseUpCallback.insert( MouseEventCallback( Selector_::MouseUpCaller( m_selector ) ) );
4179                 }
4180         }
4181         else if ( button == c_button_texture ) {
4182                 DeviceVector devicePosition( device_constrained( window_to_normalised_device( position, m_width, m_height ) ) );
4183
4184                 View scissored( *m_selector.m_view );
4185                 ConstructSelectionTest( scissored, SelectionBoxForPoint( &devicePosition[0], &m_selector.m_epsilon[0] ) );
4186                 SelectionVolume volume( scissored );
4187
4188                 if ( modifiers == c_modifier_apply_texture1 || modifiers == c_modifier_apply_texture2 || modifiers == c_modifier_apply_texture3 ) {
4189                         Scene_applyClosestTexture( volume );
4190                 }
4191                 else if ( modifiers == c_modifier_copy_texture ) {
4192                         Scene_copyClosestTexture( volume );
4193                 }
4194         }
4195 }
4196 void onMouseMotion( const WindowVector& position, ModifierFlags modifiers ){
4197         m_selector.m_mouseMoved = true;
4198         if ( m_mouse_down && !g_mouseMovedCallback.empty() ) {
4199                 m_selector.m_mouseMovedWhilePressed = true;
4200                 g_mouseMovedCallback.get() ( window_to_normalised_device( position, m_width, m_height ) );
4201         }
4202 }
4203 void onMouseUp( const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers ){
4204         if ( ( button == c_button_select || button == c_button_select2 ) && !g_mouseUpCallback.empty() ) {
4205                 m_mouse_down = false;
4206
4207                 g_mouseUpCallback.get() ( window_to_normalised_device( position, m_width, m_height ) );
4208         }
4209         //L button w/o scene changed = tunnel selection
4210         if( // !getSelectionSystem().m_undo_begun &&
4211                 modifiers == c_modifierNone && button == c_button_select &&
4212                 //( !m_selector.m_mouseMoved || !m_mouse_down ) &&
4213                 !m_selector.m_mouseMovedWhilePressed &&
4214                 ( getSelectionSystem().Mode() != SelectionSystem::eComponent || getSelectionSystem().ManipulatorMode() != SelectionSystem::eDrag ) ){
4215                 m_selector.testSelect_simpleM1( device_constrained( window_to_normalised_device( position, m_width, m_height ) ) );
4216         }
4217         //getSelectionSystem().m_undo_begun = false;
4218         m_selector.m_mouseMoved = false;
4219         m_selector.m_mouseMovedWhilePressed = false;
4220 }
4221 void onModifierDown( ModifierFlags type ){
4222         m_selector.modifierEnable( type );
4223         m_manipulator.modifierEnable( type );
4224 }
4225 void onModifierUp( ModifierFlags type ){
4226         m_selector.modifierDisable( type );
4227         m_manipulator.modifierDisable( type );
4228 }
4229 };
4230
4231
4232
4233 SelectionSystemWindowObserver* NewWindowObserver(){
4234         return new RadiantWindowObserver;
4235 }
4236
4237
4238
4239 #include "modulesystem/singletonmodule.h"
4240 #include "modulesystem/moduleregistry.h"
4241
4242 class SelectionDependencies :
4243         public GlobalSceneGraphModuleRef,
4244         public GlobalShaderCacheModuleRef,
4245         public GlobalOpenGLModuleRef
4246 {
4247 };
4248
4249 class SelectionAPI : public TypeSystemRef
4250 {
4251 SelectionSystem* m_selection;
4252 public:
4253 typedef SelectionSystem Type;
4254 STRING_CONSTANT( Name, "*" );
4255
4256 SelectionAPI(){
4257         SelectionSystem_Construct();
4258
4259         m_selection = &getSelectionSystem();
4260 }
4261 ~SelectionAPI(){
4262         SelectionSystem_Destroy();
4263 }
4264 SelectionSystem* getTable(){
4265         return m_selection;
4266 }
4267 };
4268
4269 typedef SingletonModule<SelectionAPI, SelectionDependencies> SelectionModule;
4270 typedef Static<SelectionModule> StaticSelectionModule;
4271 StaticRegisterModule staticRegisterSelection( StaticSelectionModule::instance() );