<commit_before>//                       MFEM Example 1 - Parallel Version
//
// Compile with: make ex1p
//
// Sample runs:  mpirun -np 4 ex1p -m ../data/square-disc.mesh
//               mpirun -np 4 ex1p -m ../data/star.mesh
//               mpirun -np 4 ex1p -m ../data/star-mixed.mesh
//               mpirun -np 4 ex1p -m ../data/escher.mesh
//               mpirun -np 4 ex1p -m ../data/fichera.mesh
//               mpirun -np 4 ex1p -m ../data/fichera-mixed.mesh
//               mpirun -np 4 ex1p -m ../data/toroid-wedge.mesh
//               mpirun -np 4 ex1p -m ../data/periodic-annulus-sector.msh
//               mpirun -np 4 ex1p -m ../data/periodic-torus-sector.msh
//               mpirun -np 4 ex1p -m ../data/square-disc-p2.vtk -o 2
//               mpirun -np 4 ex1p -m ../data/square-disc-p3.mesh -o 3
//               mpirun -np 4 ex1p -m ../data/square-disc-nurbs.mesh -o -1
//               mpirun -np 4 ex1p -m ../data/star-mixed-p2.mesh -o 2
//               mpirun -np 4 ex1p -m ../data/disc-nurbs.mesh -o -1
//               mpirun -np 4 ex1p -m ../data/pipe-nurbs.mesh -o -1
//               mpirun -np 4 ex1p -m ../data/ball-nurbs.mesh -o 2
//               mpirun -np 4 ex1p -m ../data/fichera-mixed-p2.mesh -o 2
//               mpirun -np 4 ex1p -m ../data/star-surf.mesh
//               mpirun -np 4 ex1p -m ../data/square-disc-surf.mesh
//               mpirun -np 4 ex1p -m ../data/inline-segment.mesh
//               mpirun -np 4 ex1p -m ../data/amr-quad.mesh
//               mpirun -np 4 ex1p -m ../data/amr-hex.mesh
//               mpirun -np 4 ex1p -m ../data/mobius-strip.mesh
//               mpirun -np 4 ex1p -m ../data/mobius-strip.mesh -o -1 -sc
//
// Device sample runs:
//               mpirun -np 4 ex1p -pa -d cuda
//               mpirun -np 4 ex1p -pa -d occa-cuda
//               mpirun -np 4 ex1p -pa -d raja-omp
//               mpirun -np 4 ex1p -pa -d ceed-cpu
//             * mpirun -np 4 ex1p -pa -d ceed-cuda
//               mpirun -np 4 ex1p -pa -d ceed-cuda:/gpu/cuda/shared
//               mpirun -np 4 ex1p -m ../data/beam-tet.mesh -pa -d ceed-cpu
//
// Description: This example is a copy of ex1 instrumented with Caliper.
// Any option supported by the Caliper ConfigManager can be passed to the
// code using a configuration string after -p or --caliper flag. For more
// information, the users are referred to the Caliper documentation.
// Examples:
//              mpirun -np 4 ex1p --caliper runtime-report
//              mpirun -np 4 ex1p --caliper runtime-report,mem.highwatermark,mpi-report
//
//The first run will return the default report and the second run will
//return in addition to the default output the memory high-water mark and time
//spent in MPI routines.

#include "mfem.hpp"
#include <fstream>
#include <iostream>

using namespace std;
using namespace mfem;

int main(int argc, char *argv[])
{
   // 1. Initialize MPI.
   int num_procs, myid;
   MPI_Init(&argc, &argv);
   MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
   MPI_Comm_rank(MPI_COMM_WORLD, &myid);
   // Define Caliper ConfigManager
   cali::ConfigManager mgr;
   // Caliper instrumentation
   MFEM_PERF_FUNCTION;

   // 2. Parse command-line options.
   const char *mesh_file = "../../data/star.mesh";
   int order = 1;
   bool static_cond = false;
   bool pa = false;
   const char *device_config = "cpu";
   bool visualization = true;
   const char* cali_config = "runtime-report";

   OptionsParser args(argc, argv);
   args.AddOption(&mesh_file, "-m", "--mesh",
                  "Mesh file to use.");
   args.AddOption(&order, "-o", "--order",
                  "Finite element order (polynomial degree) or -1 for"
                  " isoparametric space.");
   args.AddOption(&static_cond, "-sc", "--static-condensation", "-no-sc",
                  "--no-static-condensation", "Enable static condensation.");
   args.AddOption(&pa, "-pa", "--partial-assembly", "-no-pa",
                  "--no-partial-assembly", "Enable Partial Assembly.");
   args.AddOption(&device_config, "-d", "--device",
                  "Device configuration string, see Device::Configure().");
   args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
                  "--no-visualization",
                  "Enable or disable GLVis visualization.");
   args.AddOption(&cali_config, "-p", "--caliper",
                  "Caliper configuration string.");
   args.Parse();
   if (!args.Good())
   {
      if (myid == 0)
      {
         args.PrintUsage(cout);
      }
      MPI_Finalize();
      return 1;
   }
   if (myid == 0)
   {
      args.PrintOptions(cout);
   }

   // 3. Enable hardware devices such as GPUs, and programming models such as
   //    CUDA, OCCA, RAJA and OpenMP based on command line options.
   Device device(device_config);
   if (myid == 0) { device.Print(); }

   //Caliper configuration
   mgr.add(cali_config);
   mgr.start();

   // 4. Read the (serial) mesh from the given mesh file on all processors.  We
   //    can handle triangular, quadrilateral, tetrahedral, hexahedral, surface
   //    and volume meshes with the same code.
   Mesh mesh(mesh_file, 1, 1);
   int dim = mesh.Dimension();

   // 5. Refine the serial mesh on all processors to increase the resolution. In
   //    this example we do 'ref_levels' of uniform refinement. We choose
   //    'ref_levels' to be the largest number that gives a final mesh with no
   //    more than 10,000 elements.
   {
      int ref_levels =
         (int)floor(log(10000./mesh.GetNE())/log(2.)/dim);
      for (int l = 0; l < ref_levels; l++)
      {
         mesh.UniformRefinement();
      }
   }

   // 6. Define a parallel mesh by a partitioning of the serial mesh. Refine
   //    this mesh further in parallel to increase the resolution. Once the
   //    parallel mesh is defined, the serial mesh can be deleted.
   ParMesh pmesh(MPI_COMM_WORLD, mesh);
   mesh.Clear();
   {
      int par_ref_levels = 2;
      for (int l = 0; l < par_ref_levels; l++)
      {
         pmesh.UniformRefinement();
      }
   }

   // 7. Define a parallel finite element space on the parallel mesh. Here we
   //    use continuous Lagrange finite elements of the specified order. If
   //    order < 1, we instead use an isoparametric/isogeometric space.
   FiniteElementCollection *fec;
   bool delete_fec;
   if (order > 0)
   {
      fec = new H1_FECollection(order, dim);
      delete_fec = true;
   }
   else if (pmesh.GetNodes())
   {
      fec = pmesh.GetNodes()->OwnFEC();
      delete_fec = false;
      if (myid == 0)
      {
         cout << "Using isoparametric FEs: " << fec->Name() << endl;
      }
   }
   else
   {
      fec = new H1_FECollection(order = 1, dim);
      delete_fec = true;
   }
   ParFiniteElementSpace fespace(&pmesh, fec);
   HYPRE_Int size = fespace.GlobalTrueVSize();
   if (myid == 0)
   {
      cout << "Number of finite element unknowns: " << size << endl;
   }

   // 8. Determine the list of true (i.e. parallel conforming) essential
   //    boundary dofs. In this example, the boundary conditions are defined
   //    by marking all the boundary attributes from the mesh as essential
   //    (Dirichlet) and converting them to a list of true dofs.
   Array<int> ess_tdof_list;
   if (pmesh.bdr_attributes.Size())
   {
      Array<int> ess_bdr(pmesh.bdr_attributes.Max());
      ess_bdr = 1;
      fespace.GetEssentialTrueDofs(ess_bdr, ess_tdof_list);
   }

   // 9. Set up the parallel linear form b(.) which corresponds to the
   //    right-hand side of the FEM linear system, which in this case is
   //    (1,phi_i) where phi_i are the basis functions in fespace.
   MFEM_PERF_BEGIN("Set up the linear form");
   ParLinearForm b(&fespace);
   ConstantCoefficient one(1.0);
   b.AddDomainIntegrator(new DomainLFIntegrator(one));
   b.Assemble();
   MFEM_PERF_END("Set up the linear form");

   // 10. Define the solution vector x as a parallel finite element grid function
   //     corresponding to fespace. Initialize x with initial guess of zero,
   //     which satisfies the boundary conditions.
   ParGridFunction x(&fespace);
   x = 0.0;

   // 11. Set up the parallel bilinear form a(.,.) on the finite element space
   //     corresponding to the Laplacian operator -Delta, by adding the Diffusion
   //     domain integrator.
   MFEM_PERF_BEGIN("Set up the bilinear form");
   ParBilinearForm a(&fespace);
   if (pa) { a.SetAssemblyLevel(AssemblyLevel::PARTIAL); }
   a.AddDomainIntegrator(new DiffusionIntegrator(one));

   // 12. Assemble the parallel bilinear form and the corresponding linear
   //     system, applying any necessary transformations such as: parallel
   //     assembly, eliminating boundary conditions, applying conforming
   //     constraints for non-conforming AMR, static condensation, etc.
   if (static_cond) { a.EnableStaticCondensation(); }
   a.Assemble();

   OperatorPtr A;
   Vector B, X;
   a.FormLinearSystem(ess_tdof_list, x, b, A, X, B);
   MFEM_PERF_END("Set up the bilinear form");
   // 13. Solve the linear system A X = B.
   //     * With full assembly, use the BoomerAMG preconditioner from hypre.
   //     * With partial assembly, use Jacobi smoothing, for now.
   MFEM_PERF_BEGIN("Solve A X = B");
   Solver *prec = NULL;
   if (pa)
   {
      if (UsesTensorBasis(fespace))
      {
         prec = new OperatorJacobiSmoother(a, ess_tdof_list);
      }
   }
   else
   {
      prec = new HypreBoomerAMG;
   }
   CGSolver cg(MPI_COMM_WORLD);
   cg.SetRelTol(1e-12);
   cg.SetMaxIter(2000);
   cg.SetPrintLevel(1);
   if (prec) { cg.SetPreconditioner(*prec); }
   cg.SetOperator(*A);
   cg.Mult(B, X);
   delete prec;
   MFEM_PERF_END("Solve A X = B");
   // 14. Recover the parallel grid function corresponding to X. This is the
   //     local finite element solution on each processor.
   a.RecoverFEMSolution(X, b, x);

   // 15. Save the refined mesh and the solution in parallel. This output can
   //     be viewed later using GLVis: "glvis -np <np> -m mesh -g sol".
   MFEM_PERF_BEGIN("Save the results");
   {
      ostringstream mesh_name, sol_name;
      mesh_name << "mesh." << setfill('0') << setw(6) << myid;
      sol_name << "sol." << setfill('0') << setw(6) << myid;

      ofstream mesh_ofs(mesh_name.str().c_str());
      mesh_ofs.precision(8);
      pmesh.Print(mesh_ofs);

      ofstream sol_ofs(sol_name.str().c_str());
      sol_ofs.precision(8);
      x.Save(sol_ofs);
   }
   MFEM_PERF_END("Save the results");
   // 16. Send the solution by socket to a GLVis server.
   if (visualization)
   {
      char vishost[] = "localhost";
      int  visport   = 19916;
      socketstream sol_sock(vishost, visport);
      sol_sock << "parallel " << num_procs << " " << myid << "\n";
      sol_sock.precision(8);
      sol_sock << "solution\n" << pmesh << x << flush;
   }

   // 17. Free the used memory.
   if (delete_fec)
   {
      delete fec;
   }
   // Flush output before MPI_finalize
   mgr.flush();
   MPI_Finalize();

   return 0;
}
<commit_msg>Update examples/caliper/ex1p.cpp<commit_after>//                       MFEM Example 1 - Parallel Version
//
// Compile with: make ex1p
//
// Sample runs:  mpirun -np 4 ex1p -m ../data/square-disc.mesh
//               mpirun -np 4 ex1p -m ../data/star.mesh
//               mpirun -np 4 ex1p -m ../data/star-mixed.mesh
//               mpirun -np 4 ex1p -m ../data/escher.mesh
//               mpirun -np 4 ex1p -m ../data/fichera.mesh
//               mpirun -np 4 ex1p -m ../data/fichera-mixed.mesh
//               mpirun -np 4 ex1p -m ../data/toroid-wedge.mesh
//               mpirun -np 4 ex1p -m ../data/periodic-annulus-sector.msh
//               mpirun -np 4 ex1p -m ../data/periodic-torus-sector.msh
//               mpirun -np 4 ex1p -m ../data/square-disc-p2.vtk -o 2
//               mpirun -np 4 ex1p -m ../data/square-disc-p3.mesh -o 3
//               mpirun -np 4 ex1p -m ../data/square-disc-nurbs.mesh -o -1
//               mpirun -np 4 ex1p -m ../data/star-mixed-p2.mesh -o 2
//               mpirun -np 4 ex1p -m ../data/disc-nurbs.mesh -o -1
//               mpirun -np 4 ex1p -m ../data/pipe-nurbs.mesh -o -1
//               mpirun -np 4 ex1p -m ../data/ball-nurbs.mesh -o 2
//               mpirun -np 4 ex1p -m ../data/fichera-mixed-p2.mesh -o 2
//               mpirun -np 4 ex1p -m ../data/star-surf.mesh
//               mpirun -np 4 ex1p -m ../data/square-disc-surf.mesh
//               mpirun -np 4 ex1p -m ../data/inline-segment.mesh
//               mpirun -np 4 ex1p -m ../data/amr-quad.mesh
//               mpirun -np 4 ex1p -m ../data/amr-hex.mesh
//               mpirun -np 4 ex1p -m ../data/mobius-strip.mesh
//               mpirun -np 4 ex1p -m ../data/mobius-strip.mesh -o -1 -sc
//
// Device sample runs:
//               mpirun -np 4 ex1p -pa -d cuda
//               mpirun -np 4 ex1p -pa -d occa-cuda
//               mpirun -np 4 ex1p -pa -d raja-omp
//               mpirun -np 4 ex1p -pa -d ceed-cpu
//             * mpirun -np 4 ex1p -pa -d ceed-cuda
//               mpirun -np 4 ex1p -pa -d ceed-cuda:/gpu/cuda/shared
//               mpirun -np 4 ex1p -m ../data/beam-tet.mesh -pa -d ceed-cpu
//
// Description: This example is a copy of ex1 instrumented with Caliper.
// Any option supported by the Caliper ConfigManager can be passed to the
// code using a configuration string after -p or --caliper flag. For more
// information, the users are referred to the Caliper documentation.
// Examples:
//              mpirun -np 4 ex1p --caliper runtime-report
//              mpirun -np 4 ex1p --caliper runtime-report,mem.highwatermark,mpi-report
//
//The first run will return the default report and the second run will
//return in addition to the default output the memory high-water mark and time
//spent in MPI routines.

#include "mfem.hpp"
#include <fstream>
#include <iostream>

using namespace std;
using namespace mfem;

int main(int argc, char *argv[])
{
   // 1. Initialize MPI.
   int num_procs, myid;
   MPI_Init(&argc, &argv);
   MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
   MPI_Comm_rank(MPI_COMM_WORLD, &myid);
   // Define Caliper ConfigManager
   cali::ConfigManager mgr;
   // Caliper instrumentation
   MFEM_PERF_FUNCTION;

   // 2. Parse command-line options.
   const char *mesh_file = "../../data/star.mesh";
   int order = 1;
   bool static_cond = false;
   bool pa = false;
   const char *device_config = "cpu";
   bool visualization = true;
   const char* cali_config = "runtime-report";

   OptionsParser args(argc, argv);
   args.AddOption(&mesh_file, "-m", "--mesh",
                  "Mesh file to use.");
   args.AddOption(&order, "-o", "--order",
                  "Finite element order (polynomial degree) or -1 for"
                  " isoparametric space.");
   args.AddOption(&static_cond, "-sc", "--static-condensation", "-no-sc",
                  "--no-static-condensation", "Enable static condensation.");
   args.AddOption(&pa, "-pa", "--partial-assembly", "-no-pa",
                  "--no-partial-assembly", "Enable Partial Assembly.");
   args.AddOption(&device_config, "-d", "--device",
                  "Device configuration string, see Device::Configure().");
   args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
                  "--no-visualization",
                  "Enable or disable GLVis visualization.");
   args.AddOption(&cali_config, "-p", "--caliper",
                  "Caliper configuration string.");
   args.Parse();
   if (!args.Good())
   {
      if (myid == 0)
      {
         args.PrintUsage(cout);
      }
      MPI_Finalize();
      return 1;
   }
   if (myid == 0)
   {
      args.PrintOptions(cout);
   }

   // 3. Enable hardware devices such as GPUs, and programming models such as
   //    CUDA, OCCA, RAJA and OpenMP based on command line options.
   Device device(device_config);
   if (myid == 0) { device.Print(); }

   // Caliper configuration
   mgr.add(cali_config);
   mgr.start();

   // 4. Read the (serial) mesh from the given mesh file on all processors.  We
   //    can handle triangular, quadrilateral, tetrahedral, hexahedral, surface
   //    and volume meshes with the same code.
   Mesh mesh(mesh_file, 1, 1);
   int dim = mesh.Dimension();

   // 5. Refine the serial mesh on all processors to increase the resolution. In
   //    this example we do 'ref_levels' of uniform refinement. We choose
   //    'ref_levels' to be the largest number that gives a final mesh with no
   //    more than 10,000 elements.
   {
      int ref_levels =
         (int)floor(log(10000./mesh.GetNE())/log(2.)/dim);
      for (int l = 0; l < ref_levels; l++)
      {
         mesh.UniformRefinement();
      }
   }

   // 6. Define a parallel mesh by a partitioning of the serial mesh. Refine
   //    this mesh further in parallel to increase the resolution. Once the
   //    parallel mesh is defined, the serial mesh can be deleted.
   ParMesh pmesh(MPI_COMM_WORLD, mesh);
   mesh.Clear();
   {
      int par_ref_levels = 2;
      for (int l = 0; l < par_ref_levels; l++)
      {
         pmesh.UniformRefinement();
      }
   }

   // 7. Define a parallel finite element space on the parallel mesh. Here we
   //    use continuous Lagrange finite elements of the specified order. If
   //    order < 1, we instead use an isoparametric/isogeometric space.
   FiniteElementCollection *fec;
   bool delete_fec;
   if (order > 0)
   {
      fec = new H1_FECollection(order, dim);
      delete_fec = true;
   }
   else if (pmesh.GetNodes())
   {
      fec = pmesh.GetNodes()->OwnFEC();
      delete_fec = false;
      if (myid == 0)
      {
         cout << "Using isoparametric FEs: " << fec->Name() << endl;
      }
   }
   else
   {
      fec = new H1_FECollection(order = 1, dim);
      delete_fec = true;
   }
   ParFiniteElementSpace fespace(&pmesh, fec);
   HYPRE_Int size = fespace.GlobalTrueVSize();
   if (myid == 0)
   {
      cout << "Number of finite element unknowns: " << size << endl;
   }

   // 8. Determine the list of true (i.e. parallel conforming) essential
   //    boundary dofs. In this example, the boundary conditions are defined
   //    by marking all the boundary attributes from the mesh as essential
   //    (Dirichlet) and converting them to a list of true dofs.
   Array<int> ess_tdof_list;
   if (pmesh.bdr_attributes.Size())
   {
      Array<int> ess_bdr(pmesh.bdr_attributes.Max());
      ess_bdr = 1;
      fespace.GetEssentialTrueDofs(ess_bdr, ess_tdof_list);
   }

   // 9. Set up the parallel linear form b(.) which corresponds to the
   //    right-hand side of the FEM linear system, which in this case is
   //    (1,phi_i) where phi_i are the basis functions in fespace.
   MFEM_PERF_BEGIN("Set up the linear form");
   ParLinearForm b(&fespace);
   ConstantCoefficient one(1.0);
   b.AddDomainIntegrator(new DomainLFIntegrator(one));
   b.Assemble();
   MFEM_PERF_END("Set up the linear form");

   // 10. Define the solution vector x as a parallel finite element grid function
   //     corresponding to fespace. Initialize x with initial guess of zero,
   //     which satisfies the boundary conditions.
   ParGridFunction x(&fespace);
   x = 0.0;

   // 11. Set up the parallel bilinear form a(.,.) on the finite element space
   //     corresponding to the Laplacian operator -Delta, by adding the Diffusion
   //     domain integrator.
   MFEM_PERF_BEGIN("Set up the bilinear form");
   ParBilinearForm a(&fespace);
   if (pa) { a.SetAssemblyLevel(AssemblyLevel::PARTIAL); }
   a.AddDomainIntegrator(new DiffusionIntegrator(one));

   // 12. Assemble the parallel bilinear form and the corresponding linear
   //     system, applying any necessary transformations such as: parallel
   //     assembly, eliminating boundary conditions, applying conforming
   //     constraints for non-conforming AMR, static condensation, etc.
   if (static_cond) { a.EnableStaticCondensation(); }
   a.Assemble();

   OperatorPtr A;
   Vector B, X;
   a.FormLinearSystem(ess_tdof_list, x, b, A, X, B);
   MFEM_PERF_END("Set up the bilinear form");
   // 13. Solve the linear system A X = B.
   //     * With full assembly, use the BoomerAMG preconditioner from hypre.
   //     * With partial assembly, use Jacobi smoothing, for now.
   MFEM_PERF_BEGIN("Solve A X = B");
   Solver *prec = NULL;
   if (pa)
   {
      if (UsesTensorBasis(fespace))
      {
         prec = new OperatorJacobiSmoother(a, ess_tdof_list);
      }
   }
   else
   {
      prec = new HypreBoomerAMG;
   }
   CGSolver cg(MPI_COMM_WORLD);
   cg.SetRelTol(1e-12);
   cg.SetMaxIter(2000);
   cg.SetPrintLevel(1);
   if (prec) { cg.SetPreconditioner(*prec); }
   cg.SetOperator(*A);
   cg.Mult(B, X);
   delete prec;
   MFEM_PERF_END("Solve A X = B");
   // 14. Recover the parallel grid function corresponding to X. This is the
   //     local finite element solution on each processor.
   a.RecoverFEMSolution(X, b, x);

   // 15. Save the refined mesh and the solution in parallel. This output can
   //     be viewed later using GLVis: "glvis -np <np> -m mesh -g sol".
   MFEM_PERF_BEGIN("Save the results");
   {
      ostringstream mesh_name, sol_name;
      mesh_name << "mesh." << setfill('0') << setw(6) << myid;
      sol_name << "sol." << setfill('0') << setw(6) << myid;

      ofstream mesh_ofs(mesh_name.str().c_str());
      mesh_ofs.precision(8);
      pmesh.Print(mesh_ofs);

      ofstream sol_ofs(sol_name.str().c_str());
      sol_ofs.precision(8);
      x.Save(sol_ofs);
   }
   MFEM_PERF_END("Save the results");
   // 16. Send the solution by socket to a GLVis server.
   if (visualization)
   {
      char vishost[] = "localhost";
      int  visport   = 19916;
      socketstream sol_sock(vishost, visport);
      sol_sock << "parallel " << num_procs << " " << myid << "\n";
      sol_sock.precision(8);
      sol_sock << "solution\n" << pmesh << x << flush;
   }

   // 17. Free the used memory.
   if (delete_fec)
   {
      delete fec;
   }
   // Flush output before MPI_finalize
   mgr.flush();
   MPI_Finalize();

   return 0;
}
<|endoftext|>


<commit_before>/** @file
    @brief Implementation

    @date 2015

    @author
    Sensics, Inc.
    <http://sensics.com/osvr>
*/

// Copyright 2015 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 	http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Internal Includes
#include "TrackerRemoteFactory.h"
#include "VRPNConnectionCollection.h"
#include <osvr/Client/ClientInterface.h>
#include <osvr/Util/QuatlibInteropC.h>
#include <osvr/Util/EigenInterop.h>
#include <osvr/Common/PathTreeFull.h>
#include <osvr/Util/ChannelCountC.h>
#include <osvr/Util/UniquePtr.h>
#include <osvr/Common/Transform.h>
#include <osvr/Common/DecomposeOriginalSource.h>
#include <osvr/Common/JSONTransformVisitor.h>
#include "PureClientContext.h"
#include "InterfaceTree.h"
#include <osvr/Util/Verbosity.h>

// Library/third-party includes
#include <vrpn_Tracker.h>
#include <boost/lexical_cast.hpp>
#include <boost/any.hpp>
#include <boost/variant/get.hpp>
#include <json/value.h>
#include <json/reader.h>

// Standard includes
// - none

namespace osvr {
namespace client {
    class VRPNTrackerHandler : public RemoteHandler {
      public:
        struct Options {
            Options()
                : reportPose(false), reportPosition(false),
                  reportOrientation(false) {}
            bool reportPose;
            bool reportPosition;
            bool reportOrientation;
        };
        VRPNTrackerHandler(vrpn_ConnectionPtr const &conn, const char *src,
                           Options const &options, common::Transform const &t,
                           boost::optional<int> sensor, InterfaceList &ifaces)
            : m_remote(new vrpn_Tracker_Remote(src, conn.get())),
              m_transform(t), m_interfaces(ifaces), m_opts(options) {
            m_remote->register_change_handler(this, &VRPNTrackerHandler::handle,
                                              sensor.get_value_or(-1));
            OSVR_DEV_VERBOSE("Constructed a TrackerHandler for "
                             << src << " sensor " << sensor.get_value_or(-1));
        }
        virtual ~VRPNTrackerHandler() {}

        EIGEN_MAKE_ALIGNED_OPERATOR_NEW

        static void VRPN_CALLBACK handle(void *userdata, vrpn_TRACKERCB info) {
            auto self = static_cast<VRPNTrackerHandler *>(userdata);
            self->m_handle(info);
        }
        virtual void update() { m_remote->mainloop(); }

      private:
        void m_handle(vrpn_TRACKERCB const &info) {
            OSVR_PoseReport report;
            report.sensor = info.sensor;
            OSVR_TimeValue timestamp;
            osvrStructTimevalToTimeValue(&timestamp, &(info.msg_time));
            osvrQuatFromQuatlib(&(report.pose.rotation), info.quat);
            osvrVec3FromQuatlib(&(report.pose.translation), info.pos);
            Eigen::Matrix4d pose =
                m_transform.transform(util::fromPose(report.pose).matrix());
            util::toPose(pose, report.pose);

            if (m_opts.reportPose) {
                for (auto &iface : m_interfaces) {
                    iface->triggerCallbacks(timestamp, report);
                }
            }

            if (m_opts.reportPosition) {
                OSVR_PositionReport positionReport;
                positionReport.sensor = info.sensor;
                positionReport.xyz = report.pose.translation;
                for (auto &iface : m_interfaces) {
                    iface->triggerCallbacks(timestamp, positionReport);
                }
            }

            if (m_opts.reportOrientation) {
                OSVR_OrientationReport oriReport;
                oriReport.sensor = info.sensor;
                oriReport.rotation = report.pose.rotation;

                for (auto &iface : m_interfaces) {
                    iface->triggerCallbacks(timestamp, oriReport);
                }
            }
        }
        unique_ptr<vrpn_Tracker_Remote> m_remote;
        common::Transform m_transform;
        InterfaceList &m_interfaces;
        Options m_opts;
    };

    TrackerRemoteFactory::TrackerRemoteFactory(
        VRPNConnectionCollection const &conns)
        : m_conns(conns) {}

    shared_ptr<RemoteHandler> TrackerRemoteFactory::
    operator()(common::OriginalSource const &source, InterfaceList &ifaces) {

        shared_ptr<RemoteHandler> ret;

        /// @todo set this struct correctly from the descriptor, or perhaps
        /// the path?
        VRPNTrackerHandler::Options opts;

        auto interfaceType = source.getInterfaceName();
        if ("position" == interfaceType) {
            opts.reportPosition = true;
        } else if ("orientation" == interfaceType) {
            opts.reportOrientation = true;
        } else {
            /// pose and tracker both imply full reports (?)
            opts.reportOrientation = true;
            opts.reportPosition = true;
            opts.reportPose = true;
        }

        auto const &devElt = source.getDeviceElement();

        common::Transform xform{};
        if (source.hasTransform()) {
            Json::Value val;
            Json::Reader reader;
            if (reader.parse(source.getTransform(), val)) {
                common::JSONTransformVisitor xformParse(val);
                xform = xformParse.getTransform();
            }
        }

        /// @todo find out why make_shared causes a crash here
        ret.reset(new VRPNTrackerHandler(
            m_conns.getConnection(devElt), devElt.getFullDeviceName().c_str(),
            opts, xform, source.getSensorNumber(), ifaces));
        return ret;
    }

} // namespace client
} // namespace osvr<commit_msg>Unregister callback in Tracker remote<commit_after>/** @file
    @brief Implementation

    @date 2015

    @author
    Sensics, Inc.
    <http://sensics.com/osvr>
*/

// Copyright 2015 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 	http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Internal Includes
#include "TrackerRemoteFactory.h"
#include "VRPNConnectionCollection.h"
#include <osvr/Client/ClientInterface.h>
#include <osvr/Util/QuatlibInteropC.h>
#include <osvr/Util/EigenInterop.h>
#include <osvr/Common/PathTreeFull.h>
#include <osvr/Util/ChannelCountC.h>
#include <osvr/Util/UniquePtr.h>
#include <osvr/Common/Transform.h>
#include <osvr/Common/DecomposeOriginalSource.h>
#include <osvr/Common/JSONTransformVisitor.h>
#include "PureClientContext.h"
#include "InterfaceTree.h"
#include <osvr/Util/Verbosity.h>

// Library/third-party includes
#include <vrpn_Tracker.h>
#include <boost/lexical_cast.hpp>
#include <boost/any.hpp>
#include <boost/variant/get.hpp>
#include <json/value.h>
#include <json/reader.h>

// Standard includes
// - none

namespace osvr {
namespace client {
    class VRPNTrackerHandler : public RemoteHandler {
      public:
        struct Options {
            Options()
                : reportPose(false), reportPosition(false),
                  reportOrientation(false) {}
            bool reportPose;
            bool reportPosition;
            bool reportOrientation;
        };
        VRPNTrackerHandler(vrpn_ConnectionPtr const &conn, const char *src,
                           Options const &options, common::Transform const &t,
                           boost::optional<int> sensor, InterfaceList &ifaces)
            : m_remote(new vrpn_Tracker_Remote(src, conn.get())),
              m_transform(t), m_interfaces(ifaces), m_opts(options),
              m_sensor(sensor) {
            m_remote->register_change_handler(this, &VRPNTrackerHandler::handle,
                                              sensor.get_value_or(-1));
            OSVR_DEV_VERBOSE("Constructed a TrackerHandler for "
                             << src << " sensor " << sensor.get_value_or(-1));
        }
        virtual ~VRPNTrackerHandler() {
            m_remote->unregister_change_handler(
                this, &VRPNTrackerHandler::handle, m_sensor.get_value_or(-1));
        }

        EIGEN_MAKE_ALIGNED_OPERATOR_NEW

        static void VRPN_CALLBACK handle(void *userdata, vrpn_TRACKERCB info) {
            auto self = static_cast<VRPNTrackerHandler *>(userdata);
            self->m_handle(info);
        }
        virtual void update() { m_remote->mainloop(); }

      private:
        void m_handle(vrpn_TRACKERCB const &info) {
            OSVR_PoseReport report;
            report.sensor = info.sensor;
            OSVR_TimeValue timestamp;
            osvrStructTimevalToTimeValue(&timestamp, &(info.msg_time));
            osvrQuatFromQuatlib(&(report.pose.rotation), info.quat);
            osvrVec3FromQuatlib(&(report.pose.translation), info.pos);
            Eigen::Matrix4d pose =
                m_transform.transform(util::fromPose(report.pose).matrix());
            util::toPose(pose, report.pose);

            if (m_opts.reportPose) {
                for (auto &iface : m_interfaces) {
                    iface->triggerCallbacks(timestamp, report);
                }
            }

            if (m_opts.reportPosition) {
                OSVR_PositionReport positionReport;
                positionReport.sensor = info.sensor;
                positionReport.xyz = report.pose.translation;
                for (auto &iface : m_interfaces) {
                    iface->triggerCallbacks(timestamp, positionReport);
                }
            }

            if (m_opts.reportOrientation) {
                OSVR_OrientationReport oriReport;
                oriReport.sensor = info.sensor;
                oriReport.rotation = report.pose.rotation;

                for (auto &iface : m_interfaces) {
                    iface->triggerCallbacks(timestamp, oriReport);
                }
            }
        }
        unique_ptr<vrpn_Tracker_Remote> m_remote;
        common::Transform m_transform;
        InterfaceList &m_interfaces;
        Options m_opts;
        boost::optional<int> m_sensor;
    };

    TrackerRemoteFactory::TrackerRemoteFactory(
        VRPNConnectionCollection const &conns)
        : m_conns(conns) {}

    shared_ptr<RemoteHandler> TrackerRemoteFactory::
    operator()(common::OriginalSource const &source, InterfaceList &ifaces) {

        shared_ptr<RemoteHandler> ret;

        /// @todo set this struct correctly from the descriptor, or perhaps
        /// the path?
        VRPNTrackerHandler::Options opts;

        auto interfaceType = source.getInterfaceName();
        if ("position" == interfaceType) {
            opts.reportPosition = true;
        } else if ("orientation" == interfaceType) {
            opts.reportOrientation = true;
        } else {
            /// pose and tracker both imply full reports (?)
            opts.reportOrientation = true;
            opts.reportPosition = true;
            opts.reportPose = true;
        }

        auto const &devElt = source.getDeviceElement();

        common::Transform xform{};
        if (source.hasTransform()) {
            Json::Value val;
            Json::Reader reader;
            if (reader.parse(source.getTransform(), val)) {
                common::JSONTransformVisitor xformParse(val);
                xform = xformParse.getTransform();
            }
        }

        /// @todo find out why make_shared causes a crash here
        ret.reset(new VRPNTrackerHandler(
            m_conns.getConnection(devElt), devElt.getFullDeviceName().c_str(),
            opts, xform, source.getSensorNumber(), ifaces));
        return ret;
    }

} // namespace client
} // namespace osvr<|endoftext|>


<commit_before>/*

Copyright (c) 2003, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include <iostream>
#include <fstream>
#include <iterator>
#include <iomanip>

#include "libtorrent/entry.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/lazy_entry.hpp"
#include "libtorrent/magnet_uri.hpp"

int main(int argc, char* argv[])
{
	using namespace libtorrent;

	if (argc != 2)
	{
		std::cerr << "usage: dump_torrent torrent-file\n";
		return 1;
	}

	int size = file_size(argv[1]);
	if (size > 10 * 1000000)
	{
		std::cerr << "file too big (" << size << "), aborting\n";
		return 1;
	}
	std::vector<char> buf(size);
	std::ifstream(argv[1], std::ios_base::binary).read(&buf[0], size);
	lazy_entry e;
	int ret = lazy_bdecode(&buf[0], &buf[0] + buf.size(), e);

	if (ret != 0)
	{
		std::cerr << "invalid bencoding: " << ret << std::endl;
		return 1;
	}

	std::cout << "\n\n----- raw info -----\n\n";
	std::cout << print_entry(e) << std::endl;

	error_code ec;
	torrent_info t(e, ec);
	if (ec)
	{
		std::cout << ec.message() << std::endl;
		return 1;
	}

	// print info about torrent
	std::cout << "\n\n----- torrent file info -----\n\n";
	std::cout << "nodes:\n";
	typedef std::vector<std::pair<std::string, int> > node_vec;
	node_vec const& nodes = t.nodes();
	for (node_vec::const_iterator i = nodes.begin(), end(nodes.end());
		i != end; ++i)
	{
		std::cout << i->first << ":" << i->second << "\n";
	}
	std::cout << "trackers:\n";
	for (std::vector<announce_entry>::const_iterator i = t.trackers().begin();
		i != t.trackers().end(); ++i)
	{
		std::cout << i->tier << ": " << i->url << "\n";
	}

	std::cout << "number of pieces: " << t.num_pieces() << "\n";
	std::cout << "piece length: " << t.piece_length() << "\n";
	char ih[41];
	to_hex((char const*)&t.info_hash()[0], 20, ih);
	std::cout << "info hash: " << ih << "\n";
	std::cout << "comment: " << t.comment() << "\n";
	std::cout << "created by: " << t.creator() << "\n";
	std::cout << "magnet link: " << make_magnet_uri(t) << "\n";
	std::cout << "name: " << t.name() << "\n";
	std::cout << "files:\n";
	int index = 0;
	for (torrent_info::file_iterator i = t.begin_files();
		i != t.end_files(); ++i, ++index)
	{
		int first = t.map_file(index, 0, 0).piece;
		int last = t.map_file(index, (std::max)(i->size-1, size_type(0)), 0).piece;
		std::cout << "  " << std::setw(11) << i->size
			<< " "
			<< (i->pad_file?'p':'-')
			<< (i->executable_attribute?'x':'-')
			<< (i->hidden_attribute?'h':'-')
			<< (i->symlink_attribute?'l':'-')
			<< " "
			<< "[ " << std::setw(4) << first << ", " << std::setw(4) << last << " ]\t"
			<< i->path;
		if (i->symlink_attribute)
			std::cout << " -> " << i->symlink_path;
		std::cout << std::endl;
	}

	return 0;
}

<commit_msg>replaced iostream in dump_torrent example<commit_after>/*

Copyright (c) 2003, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/entry.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/lazy_entry.hpp"
#include "libtorrent/magnet_uri.hpp"

int main(int argc, char* argv[])
{
	using namespace libtorrent;

	if (argc != 2)
	{
		fputs("usage: dump_torrent torrent-file\n", stderr);
		return 1;
	}

	int size = file_size(argv[1]);
	if (size > 10 * 1000000)
	{
		fprintf(stderr, "file too big (%d), aborting\n", size);
		return 1;
	}
	std::vector<char> buf(size);
	int ret = load_file(argv[1], buf);
	if (ret != 0)
	{
		fprintf(stderr, "failed to load file: %d\n", ret);
		return 1;
	}
	lazy_entry e;
	ret = lazy_bdecode(&buf[0], &buf[0] + buf.size(), e);

	if (ret != 0)
	{
		fprintf(stderr, "invalid bencoding: %d\n", ret);
		return 1;
	}

	printf("\n\n----- raw info -----\n\n%s\n", print_entry(e).c_str());

	error_code ec;
	torrent_info t(e, ec);
	if (ec)
	{
		fprintf(stderr, "%s\n", ec.message().c_str());
		return 1;
	}

	// print info about torrent
	printf("\n\n----- torrent file info -----\n\n"
		"nodes:\n");

	typedef std::vector<std::pair<std::string, int> > node_vec;
	node_vec const& nodes = t.nodes();
	for (node_vec::const_iterator i = nodes.begin(), end(nodes.end());
		i != end; ++i)
	{
		printf("%s: %d\n", i->first.c_str(), i->second);
	}
	puts("trackers:\n");
	for (std::vector<announce_entry>::const_iterator i = t.trackers().begin();
		i != t.trackers().end(); ++i)
	{
		printf("%2d: %s\n", i->tier, i->url.c_str());
	}

	char ih[41];
	to_hex((char const*)&t.info_hash()[0], 20, ih);
	printf("number of pieces: %d\n"
		"piece length: %d\n"
		"info hash: %s\n"
		"comment: %s\n"
		"created by: %s\n"
		"magnet link: %s\n"
		"name: %s\n"
		"files:\n"
		, t.num_pieces()
		, t.piece_length()
		, ih
		, t.comment().c_str()
		, t.creator().c_str()
		, make_magnet_uri(t).c_str()
		, t.name().c_str());
	int index = 0;
	for (torrent_info::file_iterator i = t.begin_files();
		i != t.end_files(); ++i, ++index)
	{
		int first = t.map_file(index, 0, 0).piece;
		int last = t.map_file(index, (std::max)(i->size-1, size_type(0)), 0).piece;
		printf("  %11"PRId64" %c%c%c%c [ %4d, %4d ] %s %s%s\n"
			, i->size
			, (i->pad_file?'p':'-')
			, (i->executable_attribute?'x':'-')
			, (i->hidden_attribute?'h':'-')
			, (i->symlink_attribute?'l':'-')
			, first, last, i->path.c_str()
			, i->symlink_attribute ? "-> ": ""
			, i->symlink_attribute ? i->symlink_path.c_str() : "");
	}

	return 0;
}

<|endoftext|>


<commit_before>#include "logxx/logxx.h"
#include "dicom/dicom.h"
#include "dirent.h"
#include <fstream>

static logxx::Log cLog("extractor");

std::ostream& operator<<(std::ostream& s, const Dicom & d){
        s << d.GetId() << "," << d.GetDate() << "," << d.GetName() << "," << d.GetPet();
        return s;
}

int main(int argc, char **argv){
	S_LOG("main");
        logxx::GlobalLogLevel(logxx::warning);
        if (argc < 2){
                log(logxx::error) << "A path with dicom files should be specified" << logxx::endl;
                return 1;
        } else {
                std::string path(argv[1]);
                if (path[path.length()-1] != '/')
                        path += '/';

                std::string csvFile = path + "out.csv";
                std::ofstream out(csvFile);
                if (out.good()){
                        DIR *dir;
                        if ((dir = opendir (path.c_str())) != nullptr) {
                                dirent *ent;
                                while ((ent = readdir (dir)) != nullptr) {
                                        if (ent->d_type == DT_REG){
                                                std::string fName = ent->d_name;
                                                log(logxx::debug) << "{" << fName << "}" << logxx::endl;
                                                Dicom dicom(path + fName);
                                                if (dicom.Parse()){
                                                        // cppcheck-suppress constStatement
                                                        log(logxx::notice) << "{" << fName << "} Parsed" << logxx::endl;
                                                        out << fName << "," << dicom << std::endl;

                                                } else {
                                                        // cppcheck-suppress constStatement
                                                        log(logxx::notice) << "{" << fName << "} Not parsed" << logxx::endl;
                                                }
                                        }
                                }
                                closedir (dir);
                        } else {
                                log(logxx::error) << "Can't open path {" << path << "}" << logxx::endl;
                                return 1;
                        }
                        return 0;
                } else {
                        log(logxx::error) << "Can't open file {" << csvFile <<  "} for writing"  << logxx::endl;
                        return 1;
                }
        }
}
<commit_msg>Tiny refactoring<commit_after>#include "logxx/logxx.h"
#include "dicom/dicom.h"
#include "dirent.h"
#include <fstream>

static logxx::Log cLog("extractor");

std::ostream& operator<<(std::ostream& s, const Dicom & d){
        s << d.GetId() << "," << d.GetDate() << "," << d.GetName() << "," << d.GetPet();
        return s;
}

int main(int argc, char **argv){
	S_LOG("main");
        logxx::GlobalLogLevel(logxx::warning);
        if (argc < 2){
                log(logxx::error) << "A path with dicom files should be specified" << logxx::endl;
                return 1;
        } else {
                std::string path(argv[1]);
                if (path[path.length()-1] != '/')
                        path += '/';

                std::string csvFile = path + "out.csv";
                std::ofstream out(csvFile);
                if (out.good()){
                        DIR *dir;
                        if ((dir = opendir (path.c_str())) != nullptr) {
                                dirent *ent;
                                while ((ent = readdir (dir)) != nullptr) {
                                        if (ent->d_type == DT_REG){
                                                std::string fName = ent->d_name;
                                                log(logxx::debug) << "{" << fName << "}" << logxx::endl;
                                                Dicom dicom(path + fName);
                                                if (dicom.Parse()){
                                                        // cppcheck-suppress constStatement
                                                        log(logxx::notice) << "{" << fName << "} Parsed" << logxx::endl;
                                                        out << fName << "," << dicom << std::endl;

                                                } else {
                                                        // cppcheck-suppress constStatement
                                                        log(logxx::notice) << "{" << fName << "} Not parsed" << logxx::endl;
                                                }
                                        }
                                }
                                closedir (dir);
                                return 0;
                        } else {
                                log(logxx::error) << "Can't open path {" << path << "}" << logxx::endl;
                                return 1;
                        }
                } else {
                        log(logxx::error) << "Can't open file {" << csvFile <<  "} for writing"  << logxx::endl;
                        return 1;
                }
        }
}
<|endoftext|>


<commit_before>#include <ctrcommon/common.hpp>

#include <sstream>
#include <iomanip>

typedef enum {
    INSTALL,
    DELETE
} Mode;

int main(int argc, char **argv) {
    if(!platform_init()) {
        return 0;
    }

    std::vector<std::string> extensions;
    extensions.push_back("cia");

    MediaType destination = SD;
    Mode mode = INSTALL;
    bool netInstall = false;
    u64 freeSpace = fs_get_free_space(destination);
    auto onLoop = [&]() {
        bool breakLoop = false;
        if(input_is_pressed(BUTTON_L)) {
            if(destination == SD) {
                destination = NAND;
            } else {
                destination = SD;
            }

            freeSpace = fs_get_free_space(destination);
            if(mode == DELETE) {
                breakLoop = true;
            }
        }

        if(input_is_pressed(BUTTON_R)) {
            if(mode == INSTALL) {
                mode = DELETE;
            } else {
                mode = INSTALL;
            }

            breakLoop = true;
        }

        if(input_is_pressed(BUTTON_Y)) {
            netInstall = true;
            breakLoop = true;
        }

        std::stringstream stream;
        stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
        stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL ? "Install" : "Delete") << "\n";
        stream << "L - Switch Destination, R - Switch Mode" << "\n";
        stream << "Y - Receive an app over the network" << "\n";

        std::string str = stream.str();
        screen_draw_string(str, (screen_get_width() - screen_get_str_width(str)) / 2, screen_get_height() - 4 - screen_get_str_height(str), 255, 255, 255);

        return breakLoop;
    };

    auto onProgress = [&](int progress) {
        ui_display_progress("Installing", "Press B to cancel.", true, progress);
        input_poll();
        return !input_is_pressed(BUTTON_B);
    };

    while(platform_is_running()) {
        std::string targetInstall;
        App targetDelete;
        bool obtained = false;
        if(mode == INSTALL) {
            obtained = ui_select_file(&targetInstall, "sdmc:", extensions, onLoop);
        } else if(mode == DELETE) {
            obtained = ui_select_app(&targetDelete, destination, onLoop);
        }

        if(netInstall) {
            netInstall = false;

            // Clear bottom screen on both buffers.
            screen_begin_draw(BOTTOM_SCREEN);
            screen_clear(0, 0, 0);
            screen_end_draw();
            screen_swap_buffers();

            screen_begin_draw(BOTTOM_SCREEN);
            screen_clear(0, 0, 0);
            screen_end_draw();
            screen_swap_buffers();

            RemoteFile file = ui_accept_remote_file();
            if(file.socket == -1) {
                continue;
            }

            std::stringstream confirmStream;
            confirmStream << "Install the received application?" << "\n";
            confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n";
            if(ui_prompt(confirmStream.str(), true)) {
                int ret = app_install_socket(destination, file.socket, file.fileSize, onProgress);
                std::stringstream resultMsg;
                resultMsg << "Install ";
                if(ret == 0) {
                    resultMsg << "succeeded!";
                } else if(ret == -2) {
                    resultMsg << "cancelled!";
                } else {
                    resultMsg << "failed! Error: 0x" << std::hex << ret;
                }

                ui_prompt(resultMsg.str(), false);
            }

            socket_close(file.socket);
            continue;
        }

        if(obtained) {
            std::stringstream prompt;
            if(mode == INSTALL) {
                prompt << "Install ";
            } else if(mode == DELETE) {
                prompt << "Delete ";
            }

            prompt << "the selected title?";
            if(ui_prompt(prompt.str(), true)) {
                int ret = 0;
                if(mode == INSTALL) {
                    ret = app_install_file(destination, targetInstall, onProgress);
                } else if(mode == DELETE) {
                    ui_display_message("Deleting title...");
                    ret = app_delete(targetDelete);
                }

                std::stringstream resultMsg;
                if(mode == INSTALL) {
                    resultMsg << "Install ";
                } else if(mode == DELETE) {
                    resultMsg << "Delete ";
                }

                if(ret == 0) {
                    resultMsg << "succeeded!";
                } else if(ret == -2) {
                    resultMsg << "cancelled!";
                } else {
                    resultMsg << "failed! Error: 0x" << std::hex << ret;
                }

                ui_prompt(resultMsg.str(), false);

                freeSpace = fs_get_free_space(destination);
            }
        }
    }

    platform_cleanup();
    return 0;
}
<commit_msg>Update for ctrcommon changes.<commit_after>#include <ctrcommon/common.hpp>

#include <sstream>
#include <iomanip>
#include <stdio.h>

typedef enum {
    INSTALL,
    DELETE
} Mode;

int main(int argc, char **argv) {
    if(!platform_init()) {
        return 0;
    }

    std::vector<std::string> extensions;
    extensions.push_back("cia");

    MediaType destination = SD;
    Mode mode = INSTALL;
    bool netInstall = false;
    u64 freeSpace = fs_get_free_space(destination);
    auto onLoop = [&]() {
        bool breakLoop = false;
        if(input_is_pressed(BUTTON_L)) {
            if(destination == SD) {
                destination = NAND;
            } else {
                destination = SD;
            }

            freeSpace = fs_get_free_space(destination);
            if(mode == DELETE) {
                breakLoop = true;
            }
        }

        if(input_is_pressed(BUTTON_R)) {
            if(mode == INSTALL) {
                mode = DELETE;
            } else {
                mode = INSTALL;
            }

            breakLoop = true;
        }

        if(input_is_pressed(BUTTON_Y)) {
            netInstall = true;
            breakLoop = true;
        }

        std::stringstream stream;
        stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
        stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL ? "Install" : "Delete") << "\n";
        stream << "L - Switch Destination, R - Switch Mode" << "\n";
        stream << "Y - Receive an app over the network" << "\n";

        std::string str = stream.str();
        screen_draw_string(str, (screen_get_width() - screen_get_str_width(str)) / 2, screen_get_height() - 4 - screen_get_str_height(str), 255, 255, 255);

        return breakLoop;
    };

    auto onProgress = [&](int progress) {
        ui_display_progress("Installing", "Press B to cancel.", true, progress);
        input_poll();
        return !input_is_pressed(BUTTON_B);
    };

    while(platform_is_running()) {
        std::string targetInstall;
        App targetDelete;
        bool obtained = false;
        if(mode == INSTALL) {
            obtained = ui_select_file(&targetInstall, "sdmc:", extensions, onLoop);
        } else if(mode == DELETE) {
            obtained = ui_select_app(&targetDelete, destination, onLoop);
        }

        if(netInstall) {
            netInstall = false;

            // Clear bottom screen on both buffers.
            screen_begin_draw(BOTTOM_SCREEN);
            screen_clear(0, 0, 0);
            screen_end_draw();
            screen_swap_buffers();

            screen_begin_draw(BOTTOM_SCREEN);
            screen_clear(0, 0, 0);
            screen_end_draw();
            screen_swap_buffers();

            RemoteFile file = ui_accept_remote_file();
            if(file.fd == NULL) {
                continue;
            }

            std::stringstream confirmStream;
            confirmStream << "Install the received application?" << "\n";
            confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n";
            if(ui_prompt(confirmStream.str(), true)) {
                int ret = app_install(destination, file.fd, file.fileSize, onProgress);
                std::stringstream resultMsg;
                resultMsg << "Install ";
                if(ret == 0) {
                    resultMsg << "succeeded!";
                } else if(ret == -2) {
                    resultMsg << "cancelled!";
                } else {
                    resultMsg << "failed! Error: 0x" << std::hex << ret;
                }

                ui_prompt(resultMsg.str(), false);
            }

            fclose(file.fd);
            continue;
        }

        if(obtained) {
            std::stringstream prompt;
            if(mode == INSTALL) {
                prompt << "Install ";
            } else if(mode == DELETE) {
                prompt << "Delete ";
            }

            prompt << "the selected title?";
            if(ui_prompt(prompt.str(), true)) {
                int ret = 0;
                if(mode == INSTALL) {
                    ret = app_install_file(destination, targetInstall, onProgress);
                } else if(mode == DELETE) {
                    ui_display_message("Deleting title...");
                    ret = app_delete(targetDelete);
                }

                std::stringstream resultMsg;
                if(mode == INSTALL) {
                    resultMsg << "Install ";
                } else if(mode == DELETE) {
                    resultMsg << "Delete ";
                }

                if(ret == 0) {
                    resultMsg << "succeeded!";
                } else if(ret == -2) {
                    resultMsg << "cancelled!";
                } else {
                    resultMsg << "failed! Error: 0x" << std::hex << ret;
                }

                ui_prompt(resultMsg.str(), false);

                freeSpace = fs_get_free_space(destination);
            }
        }
    }

    platform_cleanup();
    return 0;
}
<|endoftext|>


<commit_before>/*************** <auto-copyright.pl BEGIN do not edit this line> **************
 *
 * VR Juggler is (C) Copyright 1998-2003 by Iowa State University
 *
 * Original Authors:
 *   Allen Bierbaum, Christopher Just,
 *   Patrick Hartling, Kevin Meinert,
 *   Carolina Cruz-Neira, Albert Baker
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 * -----------------------------------------------------------------
 * File:          $RCSfile$
 * Date modified: $Date$
 * Version:       $Revision$
 * -----------------------------------------------------------------
 *
 *************** <auto-copyright.pl END do not edit this line> ***************/

#include <vrj/vrjConfig.h>

#include <GL/gl.h>

#include <gmtl/Math.h>
#include <gmtl/Matrix.h>
#include <gmtl/Generate.h>
#include <gmtl/Vec.h>

#include <gadget/Type/Position/PositionUnitConversion.h>

#include <vrj/Draw/OGL/GlDrawManager.h>
#include <vrj/Display/DisplayManager.h>
#include <vrj/Display/SurfaceViewport.h>

#include "WallTest.h"

using namespace gmtl;
using namespace vrj;

void WallTest::bufferPreDraw()
{
   glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
   glClear(GL_COLOR_BUFFER_BIT);
}

void WallTest::draw()
{
   glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

   if(mUseLights){
      glEnable(GL_NORMALIZE);
      glEnable(GL_LIGHT0);
      glLightfv(GL_LIGHT0,GL_POSITION,mLightPosition.getData());
      glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.1f);
      glEnable(GL_COLOR_MATERIAL);
      glEnable(GL_LIGHTING);
   }
   else{
      glDisable(GL_LIGHTING);
   }

   glEnable(GL_DEPTH_TEST);

   glMatrixMode(GL_MODELVIEW);
   glLoadIdentity();

   DisplayManager* displayManager=vrj::GlDrawManager::instance()->getDisplayManager();
   std::vector<Display*> disps=displayManager->getAllDisplays();
   gmtl::Point3f ur,lr,ul,ll;

   int numSurfacesDrawn=0;
   float scale=gadget::PositionUnitConversion::ConvertToFeet;

   for(unsigned int i=0;i<disps.size();i++)
   {
      for (unsigned int v=0;v<disps[i]->getNumViewports();v++)
      {
         Viewport* viewport=disps[i]->getViewport(v);

         if (viewport->isSurface())
         {
            // Get a pointer to the surface
            SurfaceViewport* surface = dynamic_cast<SurfaceViewport*>(viewport);
            vprASSERT(surface!=NULL);

            surface->getCorners(ll,lr,ur,ul);

            ll=ll*scale;
            lr=lr*scale;
            ul=ul*scale;
            ur=ur*scale;

            drawWall(ll,lr,ul,ur);

	    numSurfacesDrawn++;
	 }
      }
   }

   if(numSurfacesDrawn==0)
   {
      drawC6();
   }
}

void WallTest::drawC6()
{
   gmtl::Point3f ll,lr,ul,ur;

   // Floor
   ll=gmtl::Point3f(-5,0,-5);
   lr=gmtl::Point3f(5,0,-5);
   ur=gmtl::Point3f(5,0,5);
   ul=gmtl::Point3f(-5,0,5);
   drawWall(ll,lr,ul,ur);

   // Ceiling
   ll=gmtl::Point3f(-5,10,5);
   lr=gmtl::Point3f(5,10,5);
   ur=gmtl::Point3f(5,10,-5);
   ul=gmtl::Point3f(-5,10,-5);
   drawWall(ll,lr,ul,ur);

   // Front
   ll=gmtl::Point3f(-5,0,5);
   lr=gmtl::Point3f(5,0,5);
   ur=gmtl::Point3f(5,10,5);
   ul=gmtl::Point3f(-5,10,5);
   drawWall(ll,lr,ul,ur);

   // Back
   ll=gmtl::Point3f(5,0,-5);
   lr=gmtl::Point3f(-5,0,-5);
   ur=gmtl::Point3f(-5,10,-5);
   ul=gmtl::Point3f(5,10,-5);
   drawWall(ll,lr,ul,ur);

   // Left
   ll=gmtl::Point3f(-5,0,-5);
   lr=gmtl::Point3f(-5,0,5);
   ur=gmtl::Point3f(-5,10,5);
   ul=gmtl::Point3f(-5,10,-5);
   drawWall(ll,lr,ul,ur);

   // Right
   ll=gmtl::Point3f(5,0,5);
   lr=gmtl::Point3f(5,0,-5);
   ur=gmtl::Point3f(5,10,-5);
   ul=gmtl::Point3f(5,10,5);
   drawWall(ll,lr,ul,ur);
}

void WallTest::drawWall(gmtl::Point3f ll,gmtl::Point3f lr,gmtl::Point3f ul,gmtl::Point3f ur)
{
   gmtl::Matrix44f rotate=calculateSurfaceRotation(ll,lr,ul,ur);
   gmtl::Vec3f origin=(ll+lr+ul+ur)/4.0;
   gmtl::Vec3f scale(gmtl::length(lr-ll),gmtl::length(ur-lr),1);
   scale[2]=scale[0]; // To keep the cubes and tetrahedrons happy
   scale*=0.1f;

   glPushMatrix();
   glTranslatef(origin[0],origin[1],origin[2]);
   glMultMatrixf(rotate.getData());
   glPushMatrix();
   glScalef(scale[0],scale[1],scale[2]);
   drawGrid();
   if(mUseCubesOrTriangles)
   {
      drawCubeOrTriangle();
   }
   glPopMatrix();
   glRotatef(90,0,1,0);
   if(mUseCubes)
   {
      drawCubeLine();
   }
   glPopMatrix();
}

gmtl::Matrix44f WallTest::calculateSurfaceRotation(gmtl::Point3f ll,gmtl::Point3f lr,gmtl::Point3f ul,gmtl::Point3f ur)
{
   // Find the base vectors for the surface axiis (in terms of the base coord system)
   // With z out, x to the right, and y up
   gmtl::Vec3f x_base, y_base, z_base;
   x_base = (lr-ll);
   y_base = (ur-lr);
   gmtl::cross( z_base, x_base, y_base);

   // They must be normalized
   gmtl::normalize(x_base); gmtl::normalize(y_base); gmtl::normalize(z_base);

   // Calculate the surfaceRotMat using law of cosines
   return gmtl::makeDirCos<gmtl::Matrix44f>(x_base,y_base,z_base);
}

void WallTest::preFrame()
{
   if(mButton1->getData()==gadget::Digital::TOGGLE_ON)
   {
      mUseLights=!mUseLights;
   }

   if(mButton0->getData()==gadget::Digital::ON)
   {
      Matrix44f wandMatrix=mWand->getData();
      gmtl::setTrans(mLightPosition,wandMatrix);
      mLightPosition[3]=1;
   }
   else
   {
      mLightPosition=gmtl::Point4f(0,5,0,1);
   }

   if(mButton2->getData()==gadget::Digital::TOGGLE_ON)
   {
      mUseCubesOrTriangles=!mUseCubesOrTriangles;
   }

   if(mButton3->getData()==gadget::Digital::TOGGLE_ON)
   {
      mUseCubes=!mUseCubes;
   }
}

void WallTest::drawGrid()
{
   glPushAttrib(GL_LIGHTING);
   glDisable(GL_LIGHTING);

   glLineWidth(2);

   glBegin(GL_LINES);

   float x;
   for(x=-5;x<=5;x+=0.5)
   {
      if(x==-2.5)      glColor3f(0,1,1);
      else if(x==-2)   glColor3f(1,1,0);
      else if(x==-1.5) glColor3f(1,0,1);
      else if(x==-1)   glColor3f(1,0,0);
      else if(x==-0.5) glColor3f(0,1,0);
      else if(x==0)    glColor3f(0,0,1);
      else if(x==0.5)  glColor3f(0,1,0);
      else if(x==1)    glColor3f(1,0,0);
      else if(x==1.5)  glColor3f(1,0,1);
      else if(x==2)    glColor3f(1,1,0);
      else if(x==2.5)  glColor3f(0,1,1);
      else             glColor3f(1,1,1);

      glVertex2f(x,-5);
      glVertex2f(x,5);

      glVertex2f(-5,x);
      glVertex2f(5,x);
   }

   glEnd();

   glColor3f(1,1,0);
   glBegin(GL_LINE_LOOP);
   for ( x = 0; x < Math::TWO_PI; x += Math::PI / 20.0 )
   {
      glVertex2f(sin(x)*5,cos(x)*5);
   }
   glEnd();

   glColor3f(0,1,1);
   glLineWidth(5);
   glBegin(GL_LINES);
      glVertex2f(-1,0);
      glVertex2f(1,0);
      glVertex2f(0,-1);
      glVertex2f(0,1);
   glEnd();
   glLineWidth(1);

   glPopAttrib();
}

void WallTest::drawCubeLine()
{
   glColor3f(0,0,1);

   float x;
   for(x=-5;x<=25;x+=2.5)
   {
      glPushMatrix();
      glTranslatef(x,0,0);
      glScalef(0.25,0.25,0.25);
      drawCube();
      glPopMatrix();
   }
}

void WallTest::drawCube()
{
   glBegin(GL_QUADS);

   glNormal3f(0,-1,0);
   glVertex3f(-1,-1,-1);
   glVertex3f(1,-1,-1);
   glVertex3f(1,-1,1);
   glVertex3f(-1,-1,1);

   glNormal3f(0,1,0);
   glVertex3f(-1,1,-1);
   glVertex3f(-1,1,1);
   glVertex3f(1,1,1);
   glVertex3f(1,1,-1);

   glNormal3f(-1,0,0);
   glVertex3f(-1,-1,-1);
   glVertex3f(-1,-1,1);
   glVertex3f(-1,1,1);
   glVertex3f(-1,1,-1);

   glNormal3f(1,0,0);
   glVertex3f(1,-1,-1);
   glVertex3f(1,1,-1);
   glVertex3f(1,1,1);
   glVertex3f(1,-1,1);

   glNormal3f(0,0,-1);
   glVertex3f(-1,-1,-1);
   glVertex3f(1,-1,-1);
   glVertex3f(1,1,-1);
   glVertex3f(-1,1,-1);

   glNormal3f(0,0,1);
   glVertex3f(-1,-1,1);
   glVertex3f(1,-1,1);
   glVertex3f(1,1,1);
   glVertex3f(-1,1,1);

   glEnd();
}

void WallTest::drawCubeOrTriangle()
{
   vrj::Projection *currentProjection=vrj::GlDrawManager::instance()->currentUserData()->getProjection();
   int currentEye=currentProjection->getEye();

   glPushMatrix();

   if(currentEye==vrj::Projection::LEFT)
   {
      glTranslatef(1.5,0,0);
      glColor3f(1,0,0);
      drawCube();
   }
   else
   {
      glTranslatef(-1.5,0,0);
      glColor3f(0,1,0);

      glBegin(GL_TRIANGLES);
      glNormal3f(0,-1,0);
      glVertex3f(-1,-1,-1);
      glVertex3f(0,-1,1);
      glVertex3f(1,-1,-1);

      glNormal3f(0,1,0);
      glVertex3f(-1,-1,-1);
      glVertex3f(0,1,0);
      glVertex3f(0,-1,1);

      glNormal3f(0,1,0);
      glVertex3f(0,-1,1);
      glVertex3f(0,1,0);
      glVertex3f(1,-1,-1);

      glNormal3f(0,1,0);
      glVertex3f(1,-1,-1);
      glVertex3f(0,1,0);
      glVertex3f(-1,-1,-1);
      glEnd();
   }

   glPopMatrix();
}
<commit_msg>- Added in a workaround so that this will build against the head branch of   GMTL.<commit_after>/*************** <auto-copyright.pl BEGIN do not edit this line> **************
 *
 * VR Juggler is (C) Copyright 1998-2003 by Iowa State University
 *
 * Original Authors:
 *   Allen Bierbaum, Christopher Just,
 *   Patrick Hartling, Kevin Meinert,
 *   Carolina Cruz-Neira, Albert Baker
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 * -----------------------------------------------------------------
 * File:          $RCSfile$
 * Date modified: $Date$
 * Version:       $Revision$
 * -----------------------------------------------------------------
 *
 *************** <auto-copyright.pl END do not edit this line> ***************/

#include <vrj/vrjConfig.h>

#include <GL/gl.h>

#include <gmtl/Math.h>
#include <gmtl/Matrix.h>
#include <gmtl/Generate.h>
#include <gmtl/Vec.h>

#include <gadget/Type/Position/PositionUnitConversion.h>

#include <vrj/Draw/OGL/GlDrawManager.h>
#include <vrj/Display/DisplayManager.h>
#include <vrj/Display/SurfaceViewport.h>

#include "WallTest.h"

using namespace gmtl;
using namespace vrj;

void WallTest::bufferPreDraw()
{
   glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
   glClear(GL_COLOR_BUFFER_BIT);
}

void WallTest::draw()
{
   glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

   if(mUseLights){
      glEnable(GL_NORMALIZE);
      glEnable(GL_LIGHT0);
      glLightfv(GL_LIGHT0,GL_POSITION,mLightPosition.getData());
      glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.1f);
      glEnable(GL_COLOR_MATERIAL);
      glEnable(GL_LIGHTING);
   }
   else{
      glDisable(GL_LIGHTING);
   }

   glEnable(GL_DEPTH_TEST);

   glMatrixMode(GL_MODELVIEW);
   glLoadIdentity();

   DisplayManager* displayManager=vrj::GlDrawManager::instance()->getDisplayManager();
   std::vector<Display*> disps=displayManager->getAllDisplays();
   gmtl::Point3f ur,lr,ul,ll;

   int numSurfacesDrawn=0;
   float scale=gadget::PositionUnitConversion::ConvertToFeet;

   for(unsigned int i=0;i<disps.size();i++)
   {
      for (unsigned int v=0;v<disps[i]->getNumViewports();v++)
      {
         Viewport* viewport=disps[i]->getViewport(v);

         if (viewport->isSurface())
         {
            // Get a pointer to the surface
            SurfaceViewport* surface = dynamic_cast<SurfaceViewport*>(viewport);
            vprASSERT(surface!=NULL);

            surface->getCorners(ll,lr,ur,ul);

            ll=ll*scale;
            lr=lr*scale;
            ul=ul*scale;
            ur=ur*scale;

            drawWall(ll,lr,ul,ur);

	    numSurfacesDrawn++;
	 }
      }
   }

   if(numSurfacesDrawn==0)
   {
      drawC6();
   }
}

void WallTest::drawC6()
{
   gmtl::Point3f ll,lr,ul,ur;

   // Floor
   ll=gmtl::Point3f(-5,0,-5);
   lr=gmtl::Point3f(5,0,-5);
   ur=gmtl::Point3f(5,0,5);
   ul=gmtl::Point3f(-5,0,5);
   drawWall(ll,lr,ul,ur);

   // Ceiling
   ll=gmtl::Point3f(-5,10,5);
   lr=gmtl::Point3f(5,10,5);
   ur=gmtl::Point3f(5,10,-5);
   ul=gmtl::Point3f(-5,10,-5);
   drawWall(ll,lr,ul,ur);

   // Front
   ll=gmtl::Point3f(-5,0,5);
   lr=gmtl::Point3f(5,0,5);
   ur=gmtl::Point3f(5,10,5);
   ul=gmtl::Point3f(-5,10,5);
   drawWall(ll,lr,ul,ur);

   // Back
   ll=gmtl::Point3f(5,0,-5);
   lr=gmtl::Point3f(-5,0,-5);
   ur=gmtl::Point3f(-5,10,-5);
   ul=gmtl::Point3f(5,10,-5);
   drawWall(ll,lr,ul,ur);

   // Left
   ll=gmtl::Point3f(-5,0,-5);
   lr=gmtl::Point3f(-5,0,5);
   ur=gmtl::Point3f(-5,10,5);
   ul=gmtl::Point3f(-5,10,-5);
   drawWall(ll,lr,ul,ur);

   // Right
   ll=gmtl::Point3f(5,0,5);
   lr=gmtl::Point3f(5,0,-5);
   ur=gmtl::Point3f(5,10,-5);
   ul=gmtl::Point3f(5,10,5);
   drawWall(ll,lr,ul,ur);
}

void WallTest::drawWall(gmtl::Point3f ll,gmtl::Point3f lr,gmtl::Point3f ul,gmtl::Point3f ur)
{
   gmtl::Matrix44f rotate=calculateSurfaceRotation(ll,lr,ul,ur);
   // FIXME:  The following is a workaround for GMTL CVS Head's meta
   //         programming.  It should be removed as soon as the GMTL API
   //         addresses this.
   gmtl::Vec3f origin = ll + lr + ul + ur;
   origin /= 4.0;
   //gmtl::Vec3f origin=(ll+lr+ul+ur)/4.0;
   gmtl::Vec3f lr_ll = lr - ll;
   gmtl::Vec3f ur_lr = ur - lr;
   gmtl::Vec3f scale(gmtl::length(lr_ll), gmtl::length(ur_lr));
   scale[2]=scale[0]; // To keep the cubes and tetrahedrons happy
   scale*=0.1f;

   glPushMatrix();
   glTranslatef(origin[0],origin[1],origin[2]);
   glMultMatrixf(rotate.getData());
   glPushMatrix();
   glScalef(scale[0],scale[1],scale[2]);
   drawGrid();
   if(mUseCubesOrTriangles)
   {
      drawCubeOrTriangle();
   }
   glPopMatrix();
   glRotatef(90,0,1,0);
   if(mUseCubes)
   {
      drawCubeLine();
   }
   glPopMatrix();
}

gmtl::Matrix44f WallTest::calculateSurfaceRotation(gmtl::Point3f ll,gmtl::Point3f lr,gmtl::Point3f ul,gmtl::Point3f ur)
{
   // Find the base vectors for the surface axiis (in terms of the base coord system)
   // With z out, x to the right, and y up
   gmtl::Vec3f x_base, y_base, z_base;
   x_base = (lr-ll);
   y_base = (ur-lr);
   gmtl::cross( z_base, x_base, y_base);

   // They must be normalized
   gmtl::normalize(x_base); gmtl::normalize(y_base); gmtl::normalize(z_base);

   // Calculate the surfaceRotMat using law of cosines
   return gmtl::makeDirCos<gmtl::Matrix44f>(x_base,y_base,z_base);
}

void WallTest::preFrame()
{
   if(mButton1->getData()==gadget::Digital::TOGGLE_ON)
   {
      mUseLights=!mUseLights;
   }

   if(mButton0->getData()==gadget::Digital::ON)
   {
      Matrix44f wandMatrix=mWand->getData();
      gmtl::setTrans(mLightPosition,wandMatrix);
      mLightPosition[3]=1;
   }
   else
   {
      mLightPosition=gmtl::Point4f(0,5,0,1);
   }

   if(mButton2->getData()==gadget::Digital::TOGGLE_ON)
   {
      mUseCubesOrTriangles=!mUseCubesOrTriangles;
   }

   if(mButton3->getData()==gadget::Digital::TOGGLE_ON)
   {
      mUseCubes=!mUseCubes;
   }
}

void WallTest::drawGrid()
{
   glPushAttrib(GL_LIGHTING);
   glDisable(GL_LIGHTING);

   glLineWidth(2);

   glBegin(GL_LINES);

   float x;
   for(x=-5;x<=5;x+=0.5)
   {
      if(x==-2.5)      glColor3f(0,1,1);
      else if(x==-2)   glColor3f(1,1,0);
      else if(x==-1.5) glColor3f(1,0,1);
      else if(x==-1)   glColor3f(1,0,0);
      else if(x==-0.5) glColor3f(0,1,0);
      else if(x==0)    glColor3f(0,0,1);
      else if(x==0.5)  glColor3f(0,1,0);
      else if(x==1)    glColor3f(1,0,0);
      else if(x==1.5)  glColor3f(1,0,1);
      else if(x==2)    glColor3f(1,1,0);
      else if(x==2.5)  glColor3f(0,1,1);
      else             glColor3f(1,1,1);

      glVertex2f(x,-5);
      glVertex2f(x,5);

      glVertex2f(-5,x);
      glVertex2f(5,x);
   }

   glEnd();

   glColor3f(1,1,0);
   glBegin(GL_LINE_LOOP);
   for ( x = 0; x < Math::TWO_PI; x += Math::PI / 20.0 )
   {
      glVertex2f(sin(x)*5,cos(x)*5);
   }
   glEnd();

   glColor3f(0,1,1);
   glLineWidth(5);
   glBegin(GL_LINES);
      glVertex2f(-1,0);
      glVertex2f(1,0);
      glVertex2f(0,-1);
      glVertex2f(0,1);
   glEnd();
   glLineWidth(1);

   glPopAttrib();
}

void WallTest::drawCubeLine()
{
   glColor3f(0,0,1);

   float x;
   for(x=-5;x<=25;x+=2.5)
   {
      glPushMatrix();
      glTranslatef(x,0,0);
      glScalef(0.25,0.25,0.25);
      drawCube();
      glPopMatrix();
   }
}

void WallTest::drawCube()
{
   glBegin(GL_QUADS);

   glNormal3f(0,-1,0);
   glVertex3f(-1,-1,-1);
   glVertex3f(1,-1,-1);
   glVertex3f(1,-1,1);
   glVertex3f(-1,-1,1);

   glNormal3f(0,1,0);
   glVertex3f(-1,1,-1);
   glVertex3f(-1,1,1);
   glVertex3f(1,1,1);
   glVertex3f(1,1,-1);

   glNormal3f(-1,0,0);
   glVertex3f(-1,-1,-1);
   glVertex3f(-1,-1,1);
   glVertex3f(-1,1,1);
   glVertex3f(-1,1,-1);

   glNormal3f(1,0,0);
   glVertex3f(1,-1,-1);
   glVertex3f(1,1,-1);
   glVertex3f(1,1,1);
   glVertex3f(1,-1,1);

   glNormal3f(0,0,-1);
   glVertex3f(-1,-1,-1);
   glVertex3f(1,-1,-1);
   glVertex3f(1,1,-1);
   glVertex3f(-1,1,-1);

   glNormal3f(0,0,1);
   glVertex3f(-1,-1,1);
   glVertex3f(1,-1,1);
   glVertex3f(1,1,1);
   glVertex3f(-1,1,1);

   glEnd();
}

void WallTest::drawCubeOrTriangle()
{
   vrj::Projection *currentProjection=vrj::GlDrawManager::instance()->currentUserData()->getProjection();
   int currentEye=currentProjection->getEye();

   glPushMatrix();

   if(currentEye==vrj::Projection::LEFT)
   {
      glTranslatef(1.5,0,0);
      glColor3f(1,0,0);
      drawCube();
   }
   else
   {
      glTranslatef(-1.5,0,0);
      glColor3f(0,1,0);

      glBegin(GL_TRIANGLES);
      glNormal3f(0,-1,0);
      glVertex3f(-1,-1,-1);
      glVertex3f(0,-1,1);
      glVertex3f(1,-1,-1);

      glNormal3f(0,1,0);
      glVertex3f(-1,-1,-1);
      glVertex3f(0,1,0);
      glVertex3f(0,-1,1);

      glNormal3f(0,1,0);
      glVertex3f(0,-1,1);
      glVertex3f(0,1,0);
      glVertex3f(1,-1,-1);

      glNormal3f(0,1,0);
      glVertex3f(1,-1,-1);
      glVertex3f(0,1,0);
      glVertex3f(-1,-1,-1);
      glEnd();
   }

   glPopMatrix();
}
<|endoftext|>


<commit_before>
#include <globjects/Shader.h>

#include <glbinding/gl/enum.h>
#include <glbinding/gl/functions.h>
#include <glbinding/gl/boolean.h>

#include <globjects/base/AbstractStringSource.h>
#include <globjects/base/StaticStringSource.h>
#include <globjects/base/File.h>
#include <globjects/base/StringTemplate.h>

#include <globjects/Program.h>
#include <globjects/ObjectVisitor.h>

#include <globjects/Resource.h>

#include "registry/ImplementationRegistry.h"
#include "implementations/AbstractShadingLanguageIncludeImplementation.h"

using namespace gl;

namespace
{

const globjects::AbstractShadingLanguageIncludeImplementation & shadingLanguageIncludeImplementation()
{
    return globjects::ImplementationRegistry::current().shadingLanguageIncludeImplementation();
}

} // namespace

namespace globjects
{

void Shader::hintIncludeImplementation(const IncludeImplementation impl)
{
    ImplementationRegistry::current().initialize(impl);
}

std::map<std::string, std::string> Shader::s_globalReplacements;

Shader::Shader(const GLenum type)
: Object(std::unique_ptr<IDResource>(new ShaderResource(type)))
, m_type(type)
, m_source(nullptr)
, m_compiled(false)
, m_compilationFailed(false)
{
}

Shader::Shader(const GLenum type, AbstractStringSource * source, const IncludePaths & includePaths)
: Shader(type)
{
    setIncludePaths(includePaths);
    setSource(source);
}

std::unique_ptr<StaticStringSource> Shader::sourceFromString(const std::string & sourceString)
{
    return StaticStringSource::create(sourceString);
}

std::unique_ptr<File> Shader::sourceFromFile(const std::string & filename)
{
    return File::create(filename, false);
}

std::unique_ptr<AbstractStringSource> Shader::applyGlobalReplacements(AbstractStringSource * source)
{
    auto sourceTemplate = StringTemplate::create(source);

    for (const auto & pair : s_globalReplacements)
    {
        sourceTemplate->replace(pair.first, pair.second);
    }

    return std::unique_ptr<AbstractStringSource>(sourceTemplate.release());
}

Shader::~Shader()
{
    for (auto program : m_programs)
    {
        program->detach(this);
    }
}

void Shader::globalReplace(const std::string & search, const std::string & replacement)
{
    s_globalReplacements[search] = replacement;
}

void Shader::globalReplace(const std::string & search, const int i)
{
    globalReplace(search, std::to_string(i));
}

void Shader::clearGlobalReplacements()
{
    s_globalReplacements.clear();
}

void Shader::accept(ObjectVisitor & visitor)
{
    visitor.visitShader(this);
}

GLenum Shader::type() const
{
    return m_type;
}

void Shader::setSource(AbstractStringSource * source)
{
    if (source == m_source)
        return;

    if (m_source)
        m_source->deregisterListener(this);

    m_source = source;

    if (m_source)
        m_source->registerListener(this);

    updateSource();
}

const AbstractStringSource* Shader::source() const
{
    return m_source;
}

void Shader::notifyChanged(const Changeable *)
{
    updateSource();
}

void Shader::updateSource()
{
    shadingLanguageIncludeImplementation().updateSources(this);

    invalidate();
}

bool Shader::compile() const
{
    if (m_compilationFailed)
        return false;

    shadingLanguageIncludeImplementation().compile(this);

    m_compiled = checkCompileStatus();

    m_compilationFailed = !m_compiled;

    changed();

    return m_compiled;
}

bool Shader::isCompiled() const
{
    return m_compiled;
}

void Shader::invalidate()
{
    m_compiled = false;
    m_compilationFailed = false;
    changed();
}

const Shader::IncludePaths & Shader::includePaths() const
{
    return m_includePaths;
}

void Shader::setIncludePaths(const std::vector<std::string> & includePaths)
{
    m_includePaths = includePaths;

    invalidate();
}

GLint Shader::get(GLenum pname) const
{
    GLint value = 0;
    glGetShaderiv(id(), pname, &value);

    return value;
}

std::string Shader::getSource() const
{
    GLint sourceLength = get(GL_SHADER_SOURCE_LENGTH);
    std::vector<char> source(sourceLength);

    glGetShaderSource(id(), sourceLength, nullptr, source.data());

    return std::string(source.data(), sourceLength);
}

bool Shader::checkCompileStatus() const
{
    GLboolean status = static_cast<GLboolean>(get(GL_COMPILE_STATUS));

    if (status == GL_FALSE)
    {
        critical()
            << "Compiler error:" << std::endl
            << shaderString() << std::endl
            << infoLog();

        return false;
    }

    return true;
}

std::string Shader::infoLog() const
{
    GLsizei length = get(GL_INFO_LOG_LENGTH);
    std::vector<char> log(length);

    glGetShaderInfoLog(id(), length, &length, log.data());

    return std::string(log.data(), length);
}

std::string Shader::shaderString() const
{
    std::stringstream ss;

    ss << "Shader(" << typeString(m_type);

    std::string shortInfo = m_source->shortInfo();
    if (shortInfo.size() > 0)
        ss << ", " << shortInfo;

    ss << ")";

    return ss.str();
}

std::string Shader::typeString() const
{
    return typeString(m_type);
}

std::string Shader::typeString(GLenum type)
{
    switch (type)
    {
    case GL_GEOMETRY_SHADER:
        return "GL_GEOMETRY_SHADER";
    case GL_FRAGMENT_SHADER:
        return "GL_FRAGMENT_SHADER";
    case GL_VERTEX_SHADER:
        return "GL_VERTEX_SHADER";
    case GL_TESS_EVALUATION_SHADER:
        return "GL_TESS_EVALUATION_SHADER";
    case GL_TESS_CONTROL_SHADER:
        return "GL_TESS_CONTROL_SHADER";
    case GL_COMPUTE_SHADER:
        return "GL_COMPUTE_SHADER";
    default:
        return "Unknown Shader Type";
    }
}

GLenum Shader::objectType() const
{
    return GL_SHADER;
}

} // namespace globjects
<commit_msg>Fix shader deinitialization<commit_after>
#include <globjects/Shader.h>

#include <glbinding/gl/enum.h>
#include <glbinding/gl/functions.h>
#include <glbinding/gl/boolean.h>

#include <globjects/base/AbstractStringSource.h>
#include <globjects/base/StaticStringSource.h>
#include <globjects/base/File.h>
#include <globjects/base/StringTemplate.h>

#include <globjects/Program.h>
#include <globjects/ObjectVisitor.h>

#include <globjects/Resource.h>

#include "registry/ImplementationRegistry.h"
#include "implementations/AbstractShadingLanguageIncludeImplementation.h"

using namespace gl;

namespace
{

const globjects::AbstractShadingLanguageIncludeImplementation & shadingLanguageIncludeImplementation()
{
    return globjects::ImplementationRegistry::current().shadingLanguageIncludeImplementation();
}

} // namespace

namespace globjects
{

void Shader::hintIncludeImplementation(const IncludeImplementation impl)
{
    ImplementationRegistry::current().initialize(impl);
}

std::map<std::string, std::string> Shader::s_globalReplacements;

Shader::Shader(const GLenum type)
: Object(std::unique_ptr<IDResource>(new ShaderResource(type)))
, m_type(type)
, m_source(nullptr)
, m_compiled(false)
, m_compilationFailed(false)
{
}

Shader::Shader(const GLenum type, AbstractStringSource * source, const IncludePaths & includePaths)
: Shader(type)
{
    setIncludePaths(includePaths);
    setSource(source);
}

std::unique_ptr<StaticStringSource> Shader::sourceFromString(const std::string & sourceString)
{
    return StaticStringSource::create(sourceString);
}

std::unique_ptr<File> Shader::sourceFromFile(const std::string & filename)
{
    return File::create(filename, false);
}

std::unique_ptr<AbstractStringSource> Shader::applyGlobalReplacements(AbstractStringSource * source)
{
    auto sourceTemplate = StringTemplate::create(source);

    for (const auto & pair : s_globalReplacements)
    {
        sourceTemplate->replace(pair.first, pair.second);
    }

    return std::unique_ptr<AbstractStringSource>(sourceTemplate.release());
}

Shader::~Shader()
{
    while (!m_programs.empty())
    {
        (*m_programs.begin())->detach(this);
    }
}

void Shader::globalReplace(const std::string & search, const std::string & replacement)
{
    s_globalReplacements[search] = replacement;
}

void Shader::globalReplace(const std::string & search, const int i)
{
    globalReplace(search, std::to_string(i));
}

void Shader::clearGlobalReplacements()
{
    s_globalReplacements.clear();
}

void Shader::accept(ObjectVisitor & visitor)
{
    visitor.visitShader(this);
}

GLenum Shader::type() const
{
    return m_type;
}

void Shader::setSource(AbstractStringSource * source)
{
    if (source == m_source)
        return;

    if (m_source)
        m_source->deregisterListener(this);

    m_source = source;

    if (m_source)
        m_source->registerListener(this);

    updateSource();
}

const AbstractStringSource* Shader::source() const
{
    return m_source;
}

void Shader::notifyChanged(const Changeable *)
{
    updateSource();
}

void Shader::updateSource()
{
    shadingLanguageIncludeImplementation().updateSources(this);

    invalidate();
}

bool Shader::compile() const
{
    if (m_compilationFailed)
        return false;

    shadingLanguageIncludeImplementation().compile(this);

    m_compiled = checkCompileStatus();

    m_compilationFailed = !m_compiled;

    changed();

    return m_compiled;
}

bool Shader::isCompiled() const
{
    return m_compiled;
}

void Shader::invalidate()
{
    m_compiled = false;
    m_compilationFailed = false;
    changed();
}

const Shader::IncludePaths & Shader::includePaths() const
{
    return m_includePaths;
}

void Shader::setIncludePaths(const std::vector<std::string> & includePaths)
{
    m_includePaths = includePaths;

    invalidate();
}

GLint Shader::get(GLenum pname) const
{
    GLint value = 0;
    glGetShaderiv(id(), pname, &value);

    return value;
}

std::string Shader::getSource() const
{
    GLint sourceLength = get(GL_SHADER_SOURCE_LENGTH);
    std::vector<char> source(sourceLength);

    glGetShaderSource(id(), sourceLength, nullptr, source.data());

    return std::string(source.data(), sourceLength);
}

bool Shader::checkCompileStatus() const
{
    GLboolean status = static_cast<GLboolean>(get(GL_COMPILE_STATUS));

    if (status == GL_FALSE)
    {
        critical()
            << "Compiler error:" << std::endl
            << shaderString() << std::endl
            << infoLog();

        return false;
    }

    return true;
}

std::string Shader::infoLog() const
{
    GLsizei length = get(GL_INFO_LOG_LENGTH);
    std::vector<char> log(length);

    glGetShaderInfoLog(id(), length, &length, log.data());

    return std::string(log.data(), length);
}

std::string Shader::shaderString() const
{
    std::stringstream ss;

    ss << "Shader(" << typeString(m_type);

    std::string shortInfo = m_source->shortInfo();
    if (shortInfo.size() > 0)
        ss << ", " << shortInfo;

    ss << ")";

    return ss.str();
}

std::string Shader::typeString() const
{
    return typeString(m_type);
}

std::string Shader::typeString(GLenum type)
{
    switch (type)
    {
    case GL_GEOMETRY_SHADER:
        return "GL_GEOMETRY_SHADER";
    case GL_FRAGMENT_SHADER:
        return "GL_FRAGMENT_SHADER";
    case GL_VERTEX_SHADER:
        return "GL_VERTEX_SHADER";
    case GL_TESS_EVALUATION_SHADER:
        return "GL_TESS_EVALUATION_SHADER";
    case GL_TESS_CONTROL_SHADER:
        return "GL_TESS_CONTROL_SHADER";
    case GL_COMPUTE_SHADER:
        return "GL_COMPUTE_SHADER";
    default:
        return "Unknown Shader Type";
    }
}

GLenum Shader::objectType() const
{
    return GL_SHADER;
}

} // namespace globjects
<|endoftext|>