commit 903041cd020dea348f1e870a2528a1555728d33c
Author: Leszek Koltunski <leszek@koltunski.pl>
Date:   Wed Mar 23 01:34:54 2022 +0100

    Progress with BandagedCreator: marking a cubit by touching it.

diff --git a/src/main/java/org/distorted/bandaged/BandagedCreatorRenderer.java b/src/main/java/org/distorted/bandaged/BandagedCreatorRenderer.java
index d1f31b1c..9f4d8312 100644
--- a/src/main/java/org/distorted/bandaged/BandagedCreatorRenderer.java
+++ b/src/main/java/org/distorted/bandaged/BandagedCreatorRenderer.java
@@ -35,7 +35,7 @@ import org.distorted.library.type.Static4D;
 
 public class BandagedCreatorRenderer implements GLSurfaceView.Renderer, DistortedLibrary.ExceptionListener
 {
-   private final GLSurfaceView mView;
+   private final BandagedCreatorView mView;
    private final DistortedScreen mScreen;
    private final Static3D mScale;
    private final Static3D mMoveWhole;
@@ -43,7 +43,11 @@ public class BandagedCreatorRenderer implements GLSurfaceView.Renderer, Distorte
    private final Static3D[] mMoveUnscaled;
    private final BandagedCubit[] mCubits;
 
-   private final int COLOR_DEFAULT = 0xffffff55;
+   static final int COLOR_DEFAULT = 0xffffff55;
+   static final int COLOR_MARKED  = 0xffff0000;
+
+   static final float SCREEN_RATIO = 0.5f;
+   static final float OBJECT_SIZE  = 3.0f;
 
    private final float[][] POSITIONS = new float[][]
         {
@@ -144,6 +148,20 @@ public class BandagedCreatorRenderer implements GLSurfaceView.Renderer, Distorte
       move.set(totalX,totalY,totalZ);
       }
 
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+   public BandagedCubit[] getCubits()
+     {
+     return mCubits;
+     }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+   public DistortedScreen getScreen()
+     {
+     return mScreen;
+     }
+
 ///////////////////////////////////////////////////////////////////////////////////////////////////
 
    @Override
@@ -158,7 +176,7 @@ public class BandagedCreatorRenderer implements GLSurfaceView.Renderer, Distorte
    @Override
    public void onSurfaceChanged(GL10 glUnused, int width, int height)
       {
-      final float Q = 0.15f;
+      final float Q = SCREEN_RATIO/OBJECT_SIZE;
       float scale = width<height ? Q*width : Q*height;
 
       mScreen.detachAll();
@@ -184,6 +202,7 @@ public class BandagedCreatorRenderer implements GLSurfaceView.Renderer, Distorte
 
       mScale.set( scale,scale,scale );
       mScreenMin = Math.min(width, height);
+      mView.setScreenSize(width,height, (int)yOffset);
       mScreen.resize(width,height);
       }
 
diff --git a/src/main/java/org/distorted/bandaged/BandagedCreatorView.java b/src/main/java/org/distorted/bandaged/BandagedCreatorView.java
index eacfd767..81b9a87e 100644
--- a/src/main/java/org/distorted/bandaged/BandagedCreatorView.java
+++ b/src/main/java/org/distorted/bandaged/BandagedCreatorView.java
@@ -29,13 +29,19 @@ import android.view.MotionEvent;
 
 import com.google.firebase.crashlytics.FirebaseCrashlytics;
 
+import org.distorted.library.main.DistortedScreen;
+
 ///////////////////////////////////////////////////////////////////////////////////////////////////
 
 public class BandagedCreatorView extends GLSurfaceView
 {
     private final static int DIRECTION_SENSITIVITY=  12;
     private int mX, mY;
+    private int mTouchedIndex;
     private BandagedCreatorRenderer mRenderer;
+    private BandagedTouchControl mTouchControl;
+    private int mScreenWidth, mScreenHeight;
+    private int mYoffset;
 
 ///////////////////////////////////////////////////////////////////////////////////////////////////
 // PUBLIC API
@@ -52,6 +58,9 @@ public class BandagedCreatorView extends GLSurfaceView
         {
         BandagedCreatorActivity act = (BandagedCreatorActivity)context;
         mRenderer = new BandagedCreatorRenderer(this);
+        BandagedCubit[] cubits = mRenderer.getCubits();
+        DistortedScreen screen = mRenderer.getScreen();
+        mTouchControl = new BandagedTouchControl(cubits, BandagedCreatorRenderer.SCREEN_RATIO, screen.getFOV() );
 
         final ActivityManager activityManager= (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
 
@@ -106,16 +115,42 @@ public class BandagedCreatorView extends GLSurfaceView
 
 ///////////////////////////////////////////////////////////////////////////////////////////////////
 
-    @Override public boolean onTouchEvent(MotionEvent event)
+    public void setScreenSize(int width, int height, int yOffset)
+      {
+      mScreenWidth = width;
+      mScreenHeight= height;
+      mYoffset     = yOffset;
+      }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+    @Override
+    public boolean onTouchEvent(MotionEvent event)
       {
       int action = event.getAction();
       int x = (int)event.getX();
-      int y = (int)event.getY();
+      int y = (int)event.getY() + mYoffset;
 
       switch(action)
          {
-         case MotionEvent.ACTION_DOWN: mX = x;
-                                       mY = y;
+         case MotionEvent.ACTION_DOWN: float x1 = (x -  mScreenWidth*0.5f)/mRenderer.mScreenMin;
+                                       float y1 = (mScreenHeight*0.5f - y)/mRenderer.mScreenMin;
+
+                                       mTouchedIndex = mTouchControl.cubitTouched(x1,y1,mRenderer.mQuat2);
+
+                                       if( mTouchedIndex<0 )
+                                         {
+                                         mX = x;
+                                         mY = y;
+                                         }
+                                       else
+                                         {
+                                         mX = -1;
+                                         mY = -1;
+
+                                         mTouchControl.markCubit(mTouchedIndex, BandagedCreatorRenderer.COLOR_MARKED);
+                                         }
+
                                        break;
 
          case MotionEvent.ACTION_MOVE: if( mX>=0 && mY>= 0 )
@@ -147,6 +182,13 @@ public class BandagedCreatorView extends GLSurfaceView
 
          case MotionEvent.ACTION_UP  : mX = -1;
                                        mY = -1;
+
+                                       if( mTouchedIndex>=0 )
+                                         {
+                                         mTouchControl.markCubit(mTouchedIndex, BandagedCreatorRenderer.COLOR_DEFAULT);
+                                         mTouchedIndex = -1;
+                                         }
+
         	                             resetQuats();
                                        break;
          }
diff --git a/src/main/java/org/distorted/bandaged/BandagedCubit.java b/src/main/java/org/distorted/bandaged/BandagedCubit.java
index 2911ef61..ff1c64c3 100644
--- a/src/main/java/org/distorted/bandaged/BandagedCubit.java
+++ b/src/main/java/org/distorted/bandaged/BandagedCubit.java
@@ -41,6 +41,7 @@ public class BandagedCubit
     private final DistortedEffects mEffects;
     private final MeshBase mMesh;
     private final float[] mPosition;
+    private boolean mIsAttached;
 
 ///////////////////////////////////////////////////////////////////////////////////////////////////
 // PUBLIC API
@@ -49,6 +50,7 @@ public class BandagedCubit
     public BandagedCubit(float[] position, Static4D quat1, Static4D quat2, Static3D move1, Static3D move2, Static3D scale, int color)
       {
       mPosition = position;
+      mIsAttached = true;
 
       FactoryBandaged3x3Cubit factory = FactoryBandaged3x3Cubit.getInstance();
       mMesh = factory.createMesh(position);
@@ -79,6 +81,27 @@ public class BandagedCubit
       mTexture.setColorARGB(color);
       }
 
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+    public void detach()
+      {
+      mIsAttached = false;
+      }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+    public boolean isAttached()
+      {
+      return mIsAttached;
+      }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+    public float[] getPosition()
+      {
+      return mPosition;
+      }
+
 ///////////////////////////////////////////////////////////////////////////////////////////////////
 
     public DistortedNode getNode()
diff --git a/src/main/java/org/distorted/bandaged/BandagedTouchControl.java b/src/main/java/org/distorted/bandaged/BandagedTouchControl.java
new file mode 100644
index 00000000..f0e2ee90
--- /dev/null
+++ b/src/main/java/org/distorted/bandaged/BandagedTouchControl.java
@@ -0,0 +1,259 @@
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// Copyright 2022 Leszek Koltunski                                                               //
+//                                                                                               //
+// This file is part of Magic Cube.                                                              //
+//                                                                                               //
+// Magic Cube is free software: you can redistribute it and/or modify                            //
+// it under the terms of the GNU General Public License as published by                          //
+// the Free Software Foundation, either version 2 of the License, or                             //
+// (at your option) any later version.                                                           //
+//                                                                                               //
+// Magic Cube is distributed in the hope that it will be useful,                                 //
+// but WITHOUT ANY WARRANTY; without even the implied warranty of                                //
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                                 //
+// GNU General Public License for more details.                                                  //
+//                                                                                               //
+// You should have received a copy of the GNU General Public License                             //
+// along with Magic Cube.  If not, see <http://www.gnu.org/licenses/>.                           //
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+package org.distorted.bandaged;
+
+import org.distorted.library.main.QuatHelper;
+import org.distorted.library.type.Static3D;
+import org.distorted.library.type.Static4D;
+import org.distorted.objectlib.touchcontrol.TouchControlHexahedron;
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+public class BandagedTouchControl
+{
+  private static final float DIST3D = 0.5f;
+  private static final float DIST2D = 0.5f;
+
+  private final Static4D CAMERA_POINT;
+  private final BandagedCubit[] mCubits;
+  private final int mNumCubits;
+  private final float[] mPoint, mCamera, mTouch, mPos;
+  private final float[] mPoint2D;
+  private float mObjectRatio;
+  private int mLastTouchedFace;
+  private final Static3D[] mFaceAxis;
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+  private boolean isInsideFace(float[] p)
+    {
+    return ( p[0]<=DIST2D && p[0]>=-DIST2D && p[1]<=DIST2D && p[1]>=-DIST2D );
+    }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// Convert the 3D point3D into a 2D point on the same face surface, but in a different
+// coordinate system: a in-plane 2D coord where the origin is in the point where the axis intersects
+// the surface, and whose Y axis points 'north' i.e. is in the plane given by the 3D origin, the
+// original 3D Y axis and our 2D in-plane origin.
+// If those 3 points constitute a degenerate triangle which does not define a plane - which can only
+// happen if axis is vertical (or in theory when 2D origin and 3D origin meet, but that would have to
+// mean that the distance between the center of the Object and its faces is 0) - then we arbitrarily
+// decide that 2D Y = (0,0,-1) in the North Pole and (0,0,1) in the South Pole)
+// (ax,ay,az) - vector normal to the face surface.
+
+  void convertTo2Dcoords(float[] point3D, float ax, float ay, float az , float[] output)
+    {
+    float y0,y1,y2; // base Y vector of the 2D coord system
+
+    if( ax==0.0f && az==0.0f )
+      {
+      y0=0; y1=0; y2=-ay;
+      }
+    else if( ay==0.0f )
+      {
+      y0=0; y1=1; y2=0;
+      }
+    else
+      {
+      float norm = (float)(-ay/Math.sqrt(1-ay*ay));
+      y0 = norm*ax; y1= norm*(ay-1/ay); y2=norm*az;
+      }
+
+    float x0 = y1*az - y2*ay;  //
+    float x1 = y2*ax - y0*az;  // (2D coord baseY) x (axis) = 2D coord baseX
+    float x2 = y0*ay - y1*ax;  //
+
+    float originAlpha = point3D[0]*ax + point3D[1]*ay + point3D[2]*az;
+
+    float origin0 = originAlpha*ax; // coords of the point where axis
+    float origin1 = originAlpha*ay; // intersects surface plane i.e.
+    float origin2 = originAlpha*az; // the origin of our 2D coord system
+
+    float v0 = point3D[0] - origin0;
+    float v1 = point3D[1] - origin1;
+    float v2 = point3D[2] - origin2;
+
+    output[0] = v0*x0 + v1*x1 + v2*x2;
+    output[1] = v0*y0 + v1*y1 + v2*y2;
+    }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// given precomputed mCamera and mPoint, respectively camera and touch point positions in ScreenSpace,
+// compute point 'output[]' which:
+// 1) lies on a face of the Object, i.e. surface defined by (axis, distance from (0,0,0))
+// 2) is co-linear with mCamera and mPoint
+//
+// output = camera + alpha*(point-camera), where alpha = [dist-axis*camera] / [axis*(point-camera)]
+
+  private void castTouchPointOntoFace(int index, float[] output)
+    {
+    Static3D faceAxis = mFaceAxis[index];
+
+    float d0 = mPoint[0]-mCamera[0];
+    float d1 = mPoint[1]-mCamera[1];
+    float d2 = mPoint[2]-mCamera[2];
+    float a0 = faceAxis.get0();
+    float a1 = faceAxis.get1();
+    float a2 = faceAxis.get2();
+
+    float denom = a0*d0 + a1*d1 + a2*d2;
+
+    if( denom != 0.0f )
+      {
+      float axisCam = a0*mCamera[0] + a1*mCamera[1] + a2*mCamera[2];
+      float alpha = (DIST3D-axisCam)/denom;
+
+      output[0] = mCamera[0] + d0*alpha;
+      output[1] = mCamera[1] + d1*alpha;
+      output[2] = mCamera[2] + d2*alpha;
+      }
+    }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+  private boolean faceIsVisible(int index)
+    {
+    Static3D faceAxis = mFaceAxis[index];
+    float castCameraOnAxis = mCamera[0]*faceAxis.get0() + mCamera[1]*faceAxis.get1() + mCamera[2]*faceAxis.get2();
+    return castCameraOnAxis > DIST3D;
+    }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+  private boolean objectTouched(Static4D rotatedTouchPoint, Static4D rotatedCamera)
+    {
+    mPoint[0]  = rotatedTouchPoint.get0()/mObjectRatio;
+    mPoint[1]  = rotatedTouchPoint.get1()/mObjectRatio;
+    mPoint[2]  = rotatedTouchPoint.get2()/mObjectRatio;
+
+    mCamera[0] = rotatedCamera.get0()/mObjectRatio;
+    mCamera[1] = rotatedCamera.get1()/mObjectRatio;
+    mCamera[2] = rotatedCamera.get2()/mObjectRatio;
+
+    for( mLastTouchedFace=0; mLastTouchedFace<6; mLastTouchedFace++)
+      {
+      if( faceIsVisible(mLastTouchedFace) )
+        {
+        castTouchPointOntoFace(mLastTouchedFace, mTouch);
+
+        float ax = mFaceAxis[mLastTouchedFace].get0();
+        float ay = mFaceAxis[mLastTouchedFace].get1();
+        float az = mFaceAxis[mLastTouchedFace].get2();
+
+        convertTo2Dcoords(mTouch, ax,ay,az, mPoint2D);
+        if( isInsideFace(mPoint2D) ) return true;
+        }
+      }
+
+    return false;
+    }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+  private void computePosition(int face, float pointX, float pointY)
+    {
+    int x = (int)(3*pointX+1.5f) -1;
+    int y = (int)(3*pointY+1.5f) -1;
+
+    switch(face)
+      {
+      case 0: mPos[0] = 1.0f; mPos[1] =    y; mPos[2] =   -x; break;
+      case 1: mPos[0] =-1.0f; mPos[1] =    y; mPos[2] =    x; break;
+      case 2: mPos[0] =    x; mPos[1] = 1.0f; mPos[2] =   -y; break;
+      case 3: mPos[0] =    x; mPos[1] =-1.0f; mPos[2] =    y; break;
+      case 4: mPos[0] =    x; mPos[1] =    y; mPos[2] = 1.0f; break;
+      case 5: mPos[0] =   -x; mPos[1] =    y; mPos[2] =-1.0f; break;
+      }
+    }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+  private int whichCubitTouched(int face, float pointX, float pointY)
+    {
+    computePosition(face,pointX,pointY);
+
+    for(int c=0; c<mNumCubits; c++)
+      if( mCubits[c].isAttached() )
+        {
+        float[] pos = mCubits[c].getPosition();
+        int len = pos.length/3;
+
+        for(int p=0; p<len; p++)
+          if( pos[3*p]==mPos[0] && pos[3*p+1]==mPos[1] && pos[3*p+2]==mPos[2] ) return c;
+        }
+
+    android.util.Log.e("D", "whichCubitTouched: IMPOSSIBLE!!");
+    return -1;
+    }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// PUBLIC API
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+  public BandagedTouchControl(BandagedCubit[] cubits, float ratio, float fov)
+    {
+    mCubits = cubits;
+    mNumCubits = cubits.length;
+    mPoint = new float[3];
+    mCamera= new float[3];
+    mTouch = new float[3];
+    mPos   = new float[3];
+    mPoint2D = new float[2];
+    mFaceAxis = TouchControlHexahedron.FACE_AXIS;
+    mObjectRatio = ratio;
+
+    double halfFOV = fov * (Math.PI/360);
+    float tanHalf = (float)Math.tan(halfFOV);
+    float dist = 0.5f/tanHalf;
+
+    CAMERA_POINT = new Static4D(0,0,dist,0);
+    }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+  public void setObjectRatio(float ratio)
+    {
+    mObjectRatio = ratio;
+    }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// return the index of the cubit touched; if none, return -1.
+
+  public int cubitTouched(float x, float y, Static4D quat)
+    {
+    Static4D touchPoint = new Static4D(x, y, 0, 0);
+    Static4D rotatedTouchPoint= QuatHelper.rotateVectorByInvertedQuat(touchPoint, quat);
+    Static4D rotatedCamera= QuatHelper.rotateVectorByInvertedQuat(CAMERA_POINT, quat);
+
+    boolean touched = objectTouched(rotatedTouchPoint,rotatedCamera);
+
+    if( !touched ) return -1;
+
+    return whichCubitTouched(mLastTouchedFace,mPoint2D[0],mPoint2D[1]);
+    }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+  public void markCubit(int index, int color)
+    {
+    mCubits[index].setTexture(color);
+    }
+}
+
