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