shaders – Need help getting an objects orientation / all my OpenGL rotations are reversed

I’m using OpenGL on Ubuntu Linux with the Eclipse IDE and the GCC compiler. I am bringing blender models into a homemade renderer/game engine.
I parse a text file containing object descriptions to load models.

Example object:

begin_object generic_object
generic_object_name lampost
generic_object_parent_name world
generic_object_position -10.0000 -10.0000 2.000000
generic_object_rotation 90.000000 0.000000 0.000000
generic_object_scale 1.000000 1.000000 1.000000
end_object

begin_object ...

The generic_object_rotation 90.000000 0.000000 0.000000 line describes 3 values:

  • Rotation around Z (XY).
  • Rotation around X (YZ).
  • Rotation around Y (XZ).

After going through all the headaches of Euler angles and their gimbal lock and singularities, I switched all my code to quaternions (highly recommended).

I am told that a counter-clockwise rotation around the Z-axis, looking down the Z-axis toward the origin uses a rotation matrix like:

cos(theta)  -sin(theta)  0  0
sin(theta)  cos(theta)   0  0
0           0            1  0
0           0            0  1

I got this from a document (rotgen.pdf) off the Song-Ho website.

If I replace theta with +90.0 (just like in my input file above), the result is:

  0.0 ,  -1.0 ,  0.0 ,  0.0  
  1.0 ,   0.0 ,  0.0 ,  0.0 
  0.0 ,   0.0 ,  1.0 ,  0.0 
-10.0 , -10.0 ,  2.0 ,  1.0

So, I make a quaternion for +90.0 degrees, turn it into a matrix and then print out the matrix to see if it is the same, and I actually get the same matrix.

  0.0 ,  -1.0 ,  0.0 ,  0.0  
  1.0 ,   0.0 ,  0.0 ,  0.0 
  0.0 ,   0.0 ,  1.0 ,  0.0 
-10.0 , -10.0 ,  2.0 ,  1.0

All is well… Then, I send this matrix to the shader to draw this object and it rotates my object CW instead.

In the shader there’s:

gl_Position = projection_matrix * view_matrix * model_matrix * vec4( aPos , 1.0 );

which seems correct.

So, I made a cube in Blender, attached different colour textures to each side of the cube so I could verify that my input data was good and, as long as the model_matrix is the identity matrix, the object is oriented correctly in space. Any time I add rotations, the models rotate in the
opposite direction. This happens on all 3 axes.

My current goal/project is the parenting system. I want to be able to extract orientation and position from the model matrix of any object (that data is stored with the object).

Specifically, right now, I want to extract the forward vector from the model_matrix so I can attach a light source to this rotating object. Set its light direction for the fragment shader. That is when I found this error.

What I am seeing:
The rotation of the object is opposite to what I command. When I rotate 0-360 over and over again, the forward vector I am reading from the objects model_matrix diverges from the direction of the object until it gets to 180 degrees, where the face of the object and the forward vector are coincident again; then they diverge again until we reach 360 and they are again coincident.

What I expect (and this may be part of my issue):
I want the rotation part of the model_matrix that rotates the object to be the current orientation of the object. And it looks like it is but the object does not render that way. The object rotates in the opposite direction (which is preventing me from getting the correct light direction vector, i.e. the forward vector).

Is this an OpenGL thing? Is the orientation of an object the transpose of the 3×3 rotation section of the model_matrix?

A c++ program to take the size and components of an Array from user and return the reversed Array

I have written this code that should take the size and components of the array from the user and then return the reverse of the Array but not able to identify and fix the error.
My best guess is that the while loop is causing trouble, but I am not sure.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


// function to reverse given array
void reverseArray(int arr(), int start, int end){

while (start<=end){
    int temp = arr(start);
    arr(start) = arr(end);
    arr(end) = temp;
    start++;
    end--;
       
}

}


// function to print given array
void printArray(int arr(), int size){
   for (int i = 0; i < size; i++)
   cout << arr(i) << " ";
}


int main() {
    int n;
    cin >> n;
    int mainarray() = {n} ; 
    n = sizeof(mainarray);

    for (int i=0; i<n; i++) {
        cin >> mainarray(i);
    }

reverseArray(mainarray , 0, n-1);
printArray(mainarray ,n);

    return 0;
}

inequalities – “Reversed” Bernstein Inequality

I’m studying harmonic analysis by myself, and I read some online notes that introduce the Bernstein inequality. One of them mention a reversed form of the Bernstein inequality, which is stated below:

Let $mathbb{T} = mathbb{R} / mathbb{Z} = (0,1)$ be the one-dimensional torus. Assume that a function $f in L^{1}(mathbb{T})$ satisfies $hat{f}(j) = 0$ for all $|j| < n$ (vanishing Fourier coefficients). Then for all $1 leq p leq infty$, there exists some constant $C$ independent of $n,p$ and $f$, such that
$$||f’||_{p} geq Cn||f||_{p}$$

It seems that an easier problem can be obtained by replacing $f’$ with $f”$ in the above inequality. The easier problem is addressed in the MO post below:

Does there exist some $C$ independent of $n$ and $f$ such that $ |f”|_p geq Cn^2 | f |_p$, where $1 leq pleq infty$?

However, it seems that the trick of convex Fourier coefficients used in the post above no longer applies to the harder problem (lower bounding the norm of the first derivative). Any suggestions/ideas?

linear algebra – GSL gsl_linalg_SV_decomp returning U and V reversed

I have the following C code:

void calculate_svd_example() {
  int m = 4;
  int n = 5;
  double M(4)(5) = {{1.0, 0.0, 0.0, 0.0, 2.0},
                     {0.0, 0.0, 3.0, 0.0, 0.0},
                     {0.0, 0.0, 0.0, 0.0, 0.0},
                     {0.0, 2.0, 0.0, 0.0, 0.0}};

  gsl_matrix *mat = gsl_matrix_alloc(m, n);
  for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) {
          double x = M(i)(j);
          gsl_matrix_set(mat, i, j, x);
      }
  }
  printf("M = n");
  pretty_print(mat);
  run_svd(mat);
}

#include <stdio.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
#include <time.h>

#include "../include/run_svd.h"

/*
  gsl_matrix_printf prints a matrix as a column vector.  This function
  prints a matrix in block form.
*/
void pretty_print(const gsl_matrix * M)
{
  // Get the dimension of the matrix.
  int rows = M->size1;
  int cols = M->size2;
  // Now print out the data in a square format.
  for(int i = 0; i < rows; i++){
    for(int j = 0; j < cols; j++){
      printf("%f ", gsl_matrix_get(M, i, j));
    }
    printf("n");
  }
  printf("n");
}

void pretty_print_vector(const gsl_vector * M)
{
  int cols = M->size;
    for(int j = 0; j < cols; j++){
      printf("%f ", gsl_vector_get(M, j));
    }
  printf("n");
}

int run_svd(const gsl_matrix * a) {
  gsl_matrix *aa;
  int m = a->size1;
  int n = a->size2;
  if (m >= n) {
    aa = gsl_matrix_alloc(m, n);
    gsl_matrix_memcpy(aa, a);
  } else {
    aa = gsl_matrix_alloc(n, m);
    // Need to transpose the input
    gsl_matrix_transpose_memcpy(aa, a);
  }

  m = aa->size2;
  gsl_matrix * V = gsl_matrix_alloc(m, m);
  gsl_vector * S = gsl_vector_alloc(m);
  gsl_vector * work = gsl_vector_alloc(m);

  /**
   * On output the matrix A is replaced by U. The diagonal elements of 
   * the singular value matrix S are stored in the vector S. The 
   * singular values are non-negative and form a non-increasing sequence 
   * from S_1 to S_N. The matrix V contains the elements of V in 
   * untransposed form. To form the product U S V^T it is necessary to 
   * take the transpose of V. A workspace of length N is required in 
   * work.
   */
  gsl_linalg_SV_decomp(aa, V, S, work);
  printf("U:n");
  pretty_print(aa);
  printf("S:n");
  pretty_print_vector(S);
  printf("V:n");
  pretty_print(V);

  gsl_matrix_free(V);
  gsl_vector_free(S);
  gsl_vector_free(work);

  return 0;
}

It is giving me the following results:

U:
-0.000000 -0.447214  0.000000 -0.000000 
 0.000000 -0.000000 -1.000000 -0.000000 
-1.000000 -0.000000  0.000000  0.000000 
-0.000000 -0.000000  0.000000  1.000000 
-0.000000 -0.894427  0.000000  0.000000 

S:
3.000000 2.236068 2.000000 0.000000 

V:
-0.000000 -1.000000 -0.000000 0.000000 
-1.000000 -0.000000 -0.000000 0.000000 
-0.000000 -0.000000 -0.000000 1.000000 
-0.000000 -0.000000 -1.000000 0.000000 

Aren’t U and V reversed here? Is this a problem with the GSL code, the GSL documentation, or something I’m doing wrong?

ordinary differential equations – Formula for the derivative of finite power series in reversed order of terms.

I wanted to solve the polar part in Schrödinger’s wave equation for the H-atom by direct substitution of functions of form:-
$$
Theta_{lm}(theta) = a_{lm} sin^{|m|}theta sum_{r≥0}^{r≤(l-|m|)/2}(-1)^rb_r cos^{l-|m|-2r}theta
$$

The $a$‘s are normalisation constants, no problem there. However, the problem of determining the $b$‘s ultimately drops down to finding the first and second derivatives of the polynomial in $z=cos theta$:
$$
P(z)=sum_{r≥0}^{r≤(l-|m|)/2} (-1)^rb_r z^{l-|m|-2r}
$$

Which is a finite power series written in decreasing order of powers. I couldn’t find a formula for so (well sometimes I get that dumb), but I think it does exist, maybe some reference book or website. I emphasize that what I’m doing is right the reverse of Frobenius-method. Thanks.

python – Finding reversed word pairs

I wrote this code to find opposites of words (i.e., words backwards). Input is a list of words. If this list contains a word + its opposite, then it should form a pair. The output should be a list of tuples (pairs).

The output should:

  • contain every pair of words only once – it should contain either (‘reed’, ‘deer’) or (‘deer’, ‘reed’), but not both.
  • not contain palindromes (words which are opposite to themselves) – e.g. ‘refer’

”’

def find_opposites(lst):
    if lst == () or len(lst) == 1:
        return ()
    else:
        opposites = () # contains all words backwards (except palindromes)
        result = ()
        for word in lst: 
            if word != word(::-1): # avoid palindromes
                opposites.append(word(::-1))

        for word in opposites:
            if word in lst: 
            # if word in both opposites list and original list,
            # then it should form a pair with its opposite

                tup = (word(::-1), word) # create tuple
                if tup(::-1) not in result: # append tuple only if its opposite in not already in result
                    result.append(tup)

        return result

”’

I have tried to substitute the list opposites with a dictionary as I know lists are slower to process, but it still takes a very long time.

Please let me know if you have any ideas on how to make it run faster, as it takes ages when I run on my corpora which contains over 11.000 words. Thanks a lot 🙂

Is disk encryption (e. g. LUKS) reversed when having an encrypted disk image inside an encrypted partition with the same encryption password?

Let’s assume one has created an encrypted partition, e. g. with the LUKS standard. Then one creates a (virtual) disk image, e. g. for use by a virtual machine, containing an encrypted partition created by the same method and using the same encryption password. The disk image is stored inside the outer encrypted partition. I assume that a symmetric encryption is used.

Is it possible that the parts of the real disk which are occupied by the encrypted partion of the inside disk image are visible in plain text (or something close to that) as if no encryption was used (due to applying the same symmetric encryption method twice)?
If yes, in which particular configuration?

java – Prime numbers that are also a prime numbers when reversed

This is a challenge on Codewars I took years ago. Task is to find all prime numbers that are also a prime number when reversed, i.e. 13 -> 31 is such a number.
This is still the answer with the most upvotes in the categories ‘Best practice’ as well as in ‘Clever’. Know looking at this answer years later I found in the comments that I probably should have used Long.parseLong() instead of Integer.parseInt(), with which I agree. Any other improvements or thoughts about this piece of code? Please keep in mind in code challenges like this I always try to code as concise as possible.

public class BackWardsPrime {

    public static String backwardsPrime(long start, long end) {
        StringBuilder sb = new StringBuilder();
        while(start <= end){
            int rev = Integer.parseInt(new StringBuilder(
            String.valueOf(start)).reverse().toString());
            if(start > 12 && isPrime(rev) && isPrime(start) && start != rev) 
                sb.append(start + " ");  
            start++;
        }
        return sb.toString().trim();
    }
    
    static boolean isPrime(long n) {
        if(n % 2 == 0) return false;
        for(int i = 3; i * i  <= n  ; i += 2) {
            if(n % i == 0)
                return false;
        }
        return true;
    }
}

c – Transformed and stored reversed order digits of an integer to a complete integer number

The indentation of your post is very bad, mainly because it is very inconsistent. Run your code through a program that indents the code for you, like indent or ClangFormat.

There is a simpler solution that is also more efficient, by avoiding the first pass over all the digits to find the length of the number. The solution could be a single loop that does this:

while (number != 0) {
    // Step 1: pop last digit from number
    ...

    // Step 2: push the digit to the back of complete_integer
    ...
}

Doing this will result in the order of the digits to be reversed. You already implemented popping the last digit from a number, now try to implement the reverse operation of pushing something to the back of a number, without having to know the exact length of that number.

I wonder why you don’t allow the number 0 to be reversed. It seems that this has a clear answer. You should be able to handle that case without having to write any additional code.

For negative numbers, you could indeed disallow them, or instead define how a negative number will be reversed. For example, you could say that the reverse of the number -123 will be -321, and then ensure your code implements this case. If the requirements for this project don’t say anything about negative numbers, it is up to you.

It is good to have descriptive names for functions and variables. One-letter names are usually bad, unless it’s for very commonly used things such as i for a loop iterator, or x and y for coordinates. But too long names can be bad as well; they require more typing, and they are distracting. Not only try to be clear, also be concise. For example:

int find_out_the_reverse_order_and_transform_digits_as_a_complete_integer(int number,int value){
    ...
}

That’s a lot of text! Now compare the following:

int reverse_digits(int number) {
    ...
}

The name of this function, along with the type of the input parameters and return value, are still very descriptive; it tells you that if you give it a number as a parameter, the function will reverse the digits, and returns the result as an interger. The name is much more concise though.

Similarly, even though you shouldn’t need this function, find_out_the_number_of_digit() could be shortened to count_digits().

On the other hand, also be aware of using too similar names. For example:

int number=get_input_validation();
int value=find_out_the_number_of_digit(number);

Now you have two variables, number and value. Now I have to look at what function was called to find out that value is actually the number of digits in number. Here is a suggestion for renaming it:

int input = get_input();
int digits_in_input = count_digits(input);