<commit_before>
#include "FemusInit.hpp"
#include "MultiLevelProblem.hpp"
#include "VTKWriter.hpp"
#include "TransientSystem.hpp"
#include "NonLinearImplicitSystem.hpp"
#include "Marker.hpp"
#include "Line.hpp"

#include "Fluid.hpp"
#include "Solid.hpp"
#include "Parameter.hpp"

#include "NumericVector.hpp"
#include "adept.h"

#include "../include/mpmFem.hpp"

double yMin;

using namespace femus;

double SetVariableTimeStep(const double time)
{
  double dt = 0.01;
//   if(time >= 0.5311 - 0.012 && time <= 0.5311 + 0.012) {
//     dt =  0.0001;
//   }
//   else if(time >= 3 * 0.5311 - 0.012 && time <= 3 * 0.5311 + 0.012) {
//     dt =  0.0001;
//   }
//   else if(time >= 5 * 0.5311 - 0.012 && time <= 5 * 0.5311 + 0.012) {
//     dt =  0.0001;
//   }
//
  if( yMin <= -1.42533) {
       dt =  0.0001;
  }

  return dt;
}

bool SetBoundaryCondition(const std::vector < double >& x, const char name[], double& value, const int facename, const double time)
{
  bool test = 1; //dirichlet
  value = 0.;

  if(1 == facename) test = 0;

  return test;

}

int main(int argc, char** args)
{

  // init Petsc-MPI communicator
  FemusInit mpinit(argc, args, MPI_COMM_WORLD);

  MultiLevelMesh mlMsh;
  double scalingFactor = 1.;
  unsigned numberOfUniformLevels = 2; //for refinement in 3D
  //unsigned numberOfUniformLevels = 1;
  unsigned numberOfSelectiveLevels = 0;

  double Lref = 1.;
  double Uref = 1.;

  //initialize parameters for rolling ball (MPM)
  double rho_MPM = 1000.;
  double nu_MPM = 0.4;
  double E_MPM = 5.91 * 1.e8;

  //initialize parameters for plate (FEM)
  double rho_FEM = 10000.;
  double nu_FEM = 0.4;
  double E_FEM = 4.2 * 1.e9;

  beta = 0.3; //was 0.25
  Gamma = 0.5;

  Parameter par(Lref, Uref);

  // Generate Solid Object
  Solid solidMPM;
  Solid solidFEM;

  solidMPM = Solid(par, E_MPM, nu_MPM, rho_MPM, "Neo-Hookean");
  solidFEM = Solid(par, E_FEM, nu_FEM, rho_FEM, "Neo-Hookean");

  mlMsh.ReadCoarseMesh("../input/basket.Scaled.neu", "fifth", scalingFactor);
  mlMsh.RefineMesh(numberOfUniformLevels + numberOfSelectiveLevels, numberOfUniformLevels , NULL);

  mlMsh.EraseCoarseLevels(numberOfUniformLevels - 1);
  numberOfUniformLevels = 1;

  unsigned dim = mlMsh.GetDimension();

  MultiLevelSolution mlSol(&mlMsh);
  // add variables to mlSol
  mlSol.AddSolution("DX", LAGRANGE, SECOND, 2);
  if(dim > 1) mlSol.AddSolution("DY", LAGRANGE, SECOND, 2);
  if(dim > 2) mlSol.AddSolution("DZ", LAGRANGE, SECOND, 2);

  mlSol.AddSolution("VX", LAGRANGE, SECOND, 2);
  if(dim > 1) mlSol.AddSolution("VY", LAGRANGE, SECOND, 2);
  if(dim > 2) mlSol.AddSolution("VZ", LAGRANGE, SECOND, 2);

  mlSol.AddSolution("AX", LAGRANGE, SECOND, 2);
  if(dim > 1) mlSol.AddSolution("AY", LAGRANGE, SECOND, 2);
  if(dim > 2) mlSol.AddSolution("AZ", LAGRANGE, SECOND, 2);

  mlSol.AddSolution("M", LAGRANGE, SECOND, 2);
  mlSol.AddSolution("Mat", DISCONTINOUS_POLYNOMIAL, ZERO, 0, false);

  mlSol.Initialize("All");

  mlSol.AttachSetBoundaryConditionFunction(SetBoundaryCondition);

  mlSol.SetIfFSI(true);

  // ******* Set boundary conditions *******
  mlSol.GenerateBdc("DX", "Steady");
  if(dim > 1) mlSol.GenerateBdc("DY", "Steady");
  if(dim > 2) mlSol.GenerateBdc("DZ", "Steady");
  mlSol.GenerateBdc("M", "Steady");

  MultiLevelProblem ml_prob(&mlSol);

  ml_prob.parameters.set<Solid> ("SolidMPM") = solidMPM;
  ml_prob.parameters.set<Solid> ("SolidFEM") = solidFEM;

  // ******* Add MPM system to the MultiLevel problem *******
  TransientNonlinearImplicitSystem& system = ml_prob.add_system < TransientNonlinearImplicitSystem > ("MPM_FEM");
  system.AddSolutionToSystemPDE("DX");
  if(dim > 1)system.AddSolutionToSystemPDE("DY");
  if(dim > 2) system.AddSolutionToSystemPDE("DZ");

  // ******* System MPM Assembly *******
  system.SetAssembleFunction(AssembleMPMSys);
  //system.SetAssembleFunction(AssembleFEM);
  // ******* set MG-Solver *******
  system.SetMgType(V_CYCLE);

  system.SetAbsoluteLinearConvergenceTolerance(1.0e-10);
  system.SetMaxNumberOfLinearIterations(1);
  system.SetNonLinearConvergenceTolerance(1.e-9);
  system.SetMaxNumberOfNonLinearIterations(20);

  system.SetNumberPreSmoothingStep(1);
  system.SetNumberPostSmoothingStep(1);

  // ******* Set Preconditioner *******
  system.SetMgSmoother(GMRES_SMOOTHER);

  system.init();

  // ******* Set Smoother *******
  system.SetSolverFineGrids(GMRES);

  system.SetPreconditionerFineGrids(ILU_PRECOND);

  system.SetTolerances(1.e-10, 1.e-15, 1.e+50, 40, 40);

  //BEGIN init particles
  unsigned size = 1;
  std::vector < std::vector < double > > x; // marker
  double yc = 0.;  // FOR E = 4.2 * 1.e8 --> 0.115 (for 3 refinements) 0.09 (for 4) and 0.05  (for 5, this one maybe to be changed)
  // FOR E = 4.2 * 1.e6 --> 0.1. (for 3 refinements) 0.075 (for 4) and 0.05  (for 5)

  x.resize(size);
  x[0].resize(dim, 0.);
  x[0][1] = yc;

  double R = 0.16;
  double R0 = 0.14;

  double PI = acos(-1.);
  unsigned NR = 300;
  unsigned NL = NR / (2 * PI);
  double DL = R0 / NL;

  for(unsigned i = 0; i < NL; i++) {
    double  r = R0 - i * DL;
    unsigned Nr = static_cast <unsigned>(ceil(NR * r / R0));
    double dtheta = 2 * PI / Nr;
    unsigned sizeOld = x.size();
    x.resize(sizeOld + Nr);
    for(unsigned s = sizeOld; s < x.size(); s++) {
      x[s].resize(dim);
    }
    for(unsigned j = 0; j < Nr; j++) {
      x[sizeOld + j][0] = r * cos(j * dtheta);
      x[sizeOld + j][1] = yc + r * sin(j * dtheta);
    }
  }
  double MASS = PI * R0 * R0 * rho_MPM;
  size = x.size();
  std::vector < double > mass(x.size(), MASS / x.size()); // uniform marker volume

  if( fabs(R - R0) > 1.0e-10 ) {

    double factor = 1.14;
    unsigned NL = getNumberOfLayers((R - R0) / DL, factor);
    std::cout << NL << std::endl;

    double  r = R0;
    for(unsigned i = 1; i <= NL; i++) {
      DL = DL / factor;
      r += DL;
      NR = static_cast <unsigned>(ceil (NR * factor) );
      double dtheta = 2 * PI / NR;
      unsigned sizeOld = x.size();
      x.resize(sizeOld + NR);
      for(unsigned s = sizeOld; s < x.size(); s++) {
        x[s].resize(dim);
      }
      for(unsigned j = 0; j < NR; j++) {
        x[sizeOld + j][0] = r * cos(j * dtheta);
        x[sizeOld + j][1] = yc + r * sin(j * dtheta);
      }
      mass.resize(x.size(), rho_MPM * r * dtheta * DL);
    }
    size = x.size();
  }

  double totalMass = 0;
  for(unsigned i = 0; i < mass.size(); i++) {
    totalMass += mass[i];
  }

  std::cout << totalMass << " " << rho_MPM * PI * R * R << std::endl;

  //return 1;

  std::vector < MarkerType > markerType;
  markerType.resize(size);

  for(unsigned j = 0; j < size; j++) {
    markerType[j] = VOLUME;
  }
  std::vector < std::vector < std::vector < double > > > line(1);
  std::vector < std::vector < std::vector < double > > > line0(1);

  unsigned solType = 2;
  linea = new Line(x, mass, markerType, mlSol.GetLevel(numberOfUniformLevels - 1), solType);

  //linea->SetParticlesMass(MASS/rhos, rhos);
  //linea->ScaleParticleMass(scale);

  linea->GetLine(line0[0]);
  PrintLine(DEFAULT_OUTPUTDIR, line0, false, 0);
  linea->GetParticlesToGridMaterial();

  //END init particles

  // ******* Print solution *******
  mlSol.SetWriter(VTK);

  std::vector<std::string> mov_vars;
  mov_vars.push_back("DX");
  mov_vars.push_back("DY");
  mov_vars.push_back("DZ");
  mlSol.GetWriter()->SetMovingMesh(mov_vars);

  std::vector<std::string> print_vars;
  print_vars.push_back("All");

  mlSol.GetWriter()->SetDebugOutput(true);
  mlSol.GetWriter()->Write(DEFAULT_OUTPUTDIR, "biquadratic", print_vars, 0);

  double theta = 0;
  gravity[0] = 9.81 * sin(theta);
  gravity[1] = -9.81 * cos(theta);

  system.AttachGetTimeIntervalFunction(SetVariableTimeStep);
  unsigned n_timesteps = 3500;
  for(unsigned time_step = 1; time_step <= n_timesteps; time_step++) {

    std::vector< double > xMin(3);
    std::vector< double > xMax(3);

    linea->GetExtrema(xMin, xMax);

    yMin = xMin[1];

    system.CopySolutionToOldSolution();

    system.MGsolve();

    // ******* Print solution *******
    mlSol.GetWriter()->Write(DEFAULT_OUTPUTDIR, "biquadratic", print_vars, time_step);

    GridToParticlesProjection(ml_prob, *linea);

    linea->GetLine(line[0]);
    PrintLine(DEFAULT_OUTPUTDIR, line, false, time_step);

  }

  delete linea;
  return 0;

} //end main

<commit_msg>basketball runna ma causa vibrazioni barra varia la x-position<commit_after>
#include "FemusInit.hpp"
#include "MultiLevelProblem.hpp"
#include "VTKWriter.hpp"
#include "TransientSystem.hpp"
#include "NonLinearImplicitSystem.hpp"
#include "Marker.hpp"
#include "Line.hpp"

#include "Fluid.hpp"
#include "Solid.hpp"
#include "Parameter.hpp"

#include "NumericVector.hpp"
#include "adept.h"

#include "../include/mpmFem.hpp"

double yMin;

using namespace femus;

double SetVariableTimeStep(const double time)
{
  double dt = 0.01;
//   if(time >= 0.5311 - 0.012 && time <= 0.5311 + 0.012) {
//     dt =  0.0001;
//   }
//   else if(time >= 3 * 0.5311 - 0.012 && time <= 3 * 0.5311 + 0.012) {
//     dt =  0.0001;
//   }
//   else if(time >= 5 * 0.5311 - 0.012 && time <= 5 * 0.5311 + 0.012) {
//     dt =  0.0001;
//   }
//
  if( yMin <= -1.42533) {
       dt =  0.0001;
  }

  return dt;
}

bool SetBoundaryCondition(const std::vector < double >& x, const char name[], double& value, const int facename, const double time)
{
  bool test = 1; //dirichlet
  value = 0.;

  if(1 == facename) test = 0;

  return test;

}

int main(int argc, char** args)
{

  // init Petsc-MPI communicator
  FemusInit mpinit(argc, args, MPI_COMM_WORLD);

  MultiLevelMesh mlMsh;
  double scalingFactor = 1.;
  unsigned numberOfUniformLevels = 2; //for refinement in 3D
  //unsigned numberOfUniformLevels = 1;
  unsigned numberOfSelectiveLevels = 0;

  double Lref = 1.;
  double Uref = 1.;

  //initialize parameters for rolling ball (MPM)
  double rho_MPM = 1000.;
  double nu_MPM = 0.4;
  double E_MPM = 5.91 * 1.e8;

  //initialize parameters for plate (FEM)
  double rho_FEM = 10000.;
  double nu_FEM = 0.4;
  double E_FEM = 4.2 * 1.e10;

  beta = 0.3; //was 0.25
  Gamma = 0.5;

  Parameter par(Lref, Uref);

  // Generate Solid Object
  Solid solidMPM;
  Solid solidFEM;

  solidMPM = Solid(par, E_MPM, nu_MPM, rho_MPM, "Neo-Hookean");
  solidFEM = Solid(par, E_FEM, nu_FEM, rho_FEM, "Neo-Hookean");

  mlMsh.ReadCoarseMesh("../input/basket.Scaled.neu", "fifth", scalingFactor);
  mlMsh.RefineMesh(numberOfUniformLevels + numberOfSelectiveLevels, numberOfUniformLevels , NULL);

  mlMsh.EraseCoarseLevels(numberOfUniformLevels - 1);
  numberOfUniformLevels = 1;

  unsigned dim = mlMsh.GetDimension();

  MultiLevelSolution mlSol(&mlMsh);
  // add variables to mlSol
  mlSol.AddSolution("DX", LAGRANGE, SECOND, 2);
  if(dim > 1) mlSol.AddSolution("DY", LAGRANGE, SECOND, 2);
  if(dim > 2) mlSol.AddSolution("DZ", LAGRANGE, SECOND, 2);

  mlSol.AddSolution("VX", LAGRANGE, SECOND, 2);
  if(dim > 1) mlSol.AddSolution("VY", LAGRANGE, SECOND, 2);
  if(dim > 2) mlSol.AddSolution("VZ", LAGRANGE, SECOND, 2);

  mlSol.AddSolution("AX", LAGRANGE, SECOND, 2);
  if(dim > 1) mlSol.AddSolution("AY", LAGRANGE, SECOND, 2);
  if(dim > 2) mlSol.AddSolution("AZ", LAGRANGE, SECOND, 2);

  mlSol.AddSolution("M", LAGRANGE, SECOND, 2);
  mlSol.AddSolution("Mat", DISCONTINOUS_POLYNOMIAL, ZERO, 0, false);

  mlSol.Initialize("All");

  mlSol.AttachSetBoundaryConditionFunction(SetBoundaryCondition);

  mlSol.SetIfFSI(true);

  // ******* Set boundary conditions *******
  mlSol.GenerateBdc("DX", "Steady");
  if(dim > 1) mlSol.GenerateBdc("DY", "Steady");
  if(dim > 2) mlSol.GenerateBdc("DZ", "Steady");
  mlSol.GenerateBdc("M", "Steady");

  MultiLevelProblem ml_prob(&mlSol);

  ml_prob.parameters.set<Solid> ("SolidMPM") = solidMPM;
  ml_prob.parameters.set<Solid> ("SolidFEM") = solidFEM;

  // ******* Add MPM system to the MultiLevel problem *******
  TransientNonlinearImplicitSystem& system = ml_prob.add_system < TransientNonlinearImplicitSystem > ("MPM_FEM");
  system.AddSolutionToSystemPDE("DX");
  if(dim > 1)system.AddSolutionToSystemPDE("DY");
  if(dim > 2) system.AddSolutionToSystemPDE("DZ");

  // ******* System MPM Assembly *******
  system.SetAssembleFunction(AssembleMPMSys);
  //system.SetAssembleFunction(AssembleFEM);
  // ******* set MG-Solver *******
  system.SetMgType(V_CYCLE);

  system.SetAbsoluteLinearConvergenceTolerance(1.0e-10);
  system.SetMaxNumberOfLinearIterations(1);
  system.SetNonLinearConvergenceTolerance(1.e-9);
  system.SetMaxNumberOfNonLinearIterations(20);

  system.SetNumberPreSmoothingStep(1);
  system.SetNumberPostSmoothingStep(1);

  // ******* Set Preconditioner *******
  system.SetMgSmoother(GMRES_SMOOTHER);

  system.init();

  // ******* Set Smoother *******
  system.SetSolverFineGrids(GMRES);

  system.SetPreconditionerFineGrids(ILU_PRECOND);

  system.SetTolerances(1.e-10, 1.e-15, 1.e+50, 40, 40);

  //BEGIN init particles
  unsigned size = 1;
  std::vector < std::vector < double > > x; // marker
  double yc = 0.;  // FOR E = 4.2 * 1.e8 --> 0.115 (for 3 refinements) 0.09 (for 4) and 0.05  (for 5, this one maybe to be changed)
  // FOR E = 4.2 * 1.e6 --> 0.1. (for 3 refinements) 0.075 (for 4) and 0.05  (for 5)

  x.resize(size);
  x[0].resize(dim, 0.);
  x[0][1] = yc;

  double R = 0.16;
  double R0 = 0.14;

  double PI = acos(-1.);
  unsigned NR = 300;
  unsigned NL = NR / (2 * PI);
  double DL = R0 / NL;

  for(unsigned i = 0; i < NL; i++) {
    double  r = R0 - i * DL;
    unsigned Nr = static_cast <unsigned>(ceil(NR * r / R0));
    double dtheta = 2 * PI / Nr;
    unsigned sizeOld = x.size();
    x.resize(sizeOld + Nr);
    for(unsigned s = sizeOld; s < x.size(); s++) {
      x[s].resize(dim);
    }
    for(unsigned j = 0; j < Nr; j++) {
      x[sizeOld + j][0] = r * cos(j * dtheta);
      x[sizeOld + j][1] = yc + r * sin(j * dtheta);
    }
  }
  double MASS = PI * R0 * R0 * rho_MPM;
  size = x.size();
  std::vector < double > mass(x.size(), MASS / x.size()); // uniform marker volume

  if( fabs(R - R0) > 1.0e-10 ) {

    double factor = 1.14;
    unsigned NL = getNumberOfLayers((R - R0) / DL, factor);
    std::cout << NL << std::endl;

    double  r = R0;
    for(unsigned i = 1; i <= NL; i++) {
      DL = DL / factor;
      r += DL;
      NR = static_cast <unsigned>(ceil (NR * factor) );
      double dtheta = 2 * PI / NR;
      unsigned sizeOld = x.size();
      x.resize(sizeOld + NR);
      for(unsigned s = sizeOld; s < x.size(); s++) {
        x[s].resize(dim);
      }
      for(unsigned j = 0; j < NR; j++) {
        x[sizeOld + j][0] = r * cos(j * dtheta);
        x[sizeOld + j][1] = yc + r * sin(j * dtheta);
      }
      mass.resize(x.size(), rho_MPM * r * dtheta * DL);
    }
    size = x.size();
  }

  double totalMass = 0;
  for(unsigned i = 0; i < mass.size(); i++) {
    totalMass += mass[i];
  }

  std::cout << totalMass << " " << rho_MPM * PI * R * R << std::endl;

  //return 1;

  std::vector < MarkerType > markerType;
  markerType.resize(size);

  for(unsigned j = 0; j < size; j++) {
    markerType[j] = VOLUME;
  }
  std::vector < std::vector < std::vector < double > > > line(1);
  std::vector < std::vector < std::vector < double > > > line0(1);

  unsigned solType = 2;
  linea = new Line(x, mass, markerType, mlSol.GetLevel(numberOfUniformLevels - 1), solType);

  //linea->SetParticlesMass(MASS/rhos, rhos);
  //linea->ScaleParticleMass(scale);

  linea->GetLine(line0[0]);
  PrintLine(DEFAULT_OUTPUTDIR, line0, false, 0);
  linea->GetParticlesToGridMaterial();

  //END init particles

  // ******* Print solution *******
  mlSol.SetWriter(VTK);

  std::vector<std::string> mov_vars;
  mov_vars.push_back("DX");
  mov_vars.push_back("DY");
  mov_vars.push_back("DZ");
  mlSol.GetWriter()->SetMovingMesh(mov_vars);

  std::vector<std::string> print_vars;
  print_vars.push_back("All");

  mlSol.GetWriter()->SetDebugOutput(true);
  mlSol.GetWriter()->Write(DEFAULT_OUTPUTDIR, "biquadratic", print_vars, 0);

  double theta = 0;
  gravity[0] = 9.81 * sin(theta);
  gravity[1] = -9.81 * cos(theta);

  system.AttachGetTimeIntervalFunction(SetVariableTimeStep);
  unsigned n_timesteps = 3500;
  for(unsigned time_step = 1; time_step <= n_timesteps; time_step++) {

    std::vector< double > xMin(3);
    std::vector< double > xMax(3);

    linea->GetExtrema(xMin, xMax);

    yMin = xMin[1];

    system.CopySolutionToOldSolution();

    system.MGsolve();

    // ******* Print solution *******
    mlSol.GetWriter()->Write(DEFAULT_OUTPUTDIR, "biquadratic", print_vars, time_step);

    GridToParticlesProjection(ml_prob, *linea);

    linea->GetLine(line[0]);
    PrintLine(DEFAULT_OUTPUTDIR, line, false, time_step);

  }

  delete linea;
  return 0;

} //end main

<|endoftext|>


<commit_before>/*!
 * \file gpu_dirty_state.hpp
 * \brief file gpu_dirty_state.hpp
 *
 * Copyright 2018 by Intel.
 *
 * Contact: kevin.rogovin@intel.com
 *
 * This Source Code Form is subject to the
 * terms of the Mozilla Public License, v. 2.0.
 * If a copy of the MPL was not distributed with
 * this file, You can obtain one at
 * http://mozilla.org/MPL/2.0/.
 *
 * \author Kevin Rogovin <kevin.rogovin@intel.com>
 *
 */

#pragma once

#include <stdint.h>

namespace fastuidraw
{
/*!\addtogroup Utility
 * @{
 */
  /*!
   * Object to encapsulate GPU dirty state via bit-flags.
   */
  class gpu_dirty_state
  {
  public:
    /*!
     * Enumeration to specify the bit-flags to specify
     * dirty GPU state.
     */
    enum bit_flags
      {
        /*!
         * If this bit is up, indicates that the shaders used
         * by the GPU has changed.
         */
        shader = 1 << 0,

        /*!
         * If this bit is up, indicates that  the binding
         * of the texture binding slots used by the shader
         * of a PainterBackend derived class have changed.
         * For example, in GL these changes are accompished
         * by calling glBindTexture().
         */
        textures = 1 << 1,

        /*!
         * If this bit is up, indicates that the binding
         * of the image binding slots used by the shader
         * of a PainterBackend derived class have changed.
         * For example, in GL these changes are accompished
         * by calling glBindImageTexture().
         */
        images = 1 << 2,

        /*!
         * If this bit is up, indicates that the blend
         * state of the GPU has changed.
         */
        blend_mode = 1 << 3,

        /*!
         * If this bit is up, indicates that the bound
         * render-target of the GPU has changed. For example,
         * in GL changing the render-target is accomplished
         * by glBindFramgebuffer() and/or glDrawBuffers().
         */
        render_target = 1 << 4,

        /*!
         * If this bit is up, indicates that the viewport
         * or scissor values have changed. For example, in GL
         * this is accomplished by calling glViewport(),
         * glScissor() or glEnable/glDisable() passing
         * GL_SCISSOR_TEST.
         */
        viewport_scissor = 1 << 5,

        /*!
         * If this bit is up, indicates that the source or format
         * for index or vertex buffers has changed. For example,
         * in GL, this can be accomplished by calling
         * glBindVertexArray() or modifying the currently bound
         * vertex array object.
         */
        vertex_index_source = 1 << 6,

        /*!
         * If this bit is up, indicates that a constant buffer
         * source has changed. For GL, these are UBOs. For example,
         * in GL, this can be accomplished by calling glBindBuffer()
         * with the binding target as GL_UNIFORM_BUFFER.
         */
        constant_buffers = 1 << 7,

        /*!
         * If this bit is up, indicates that a storage buffer
         * source has changed. For GL, these are UBOs. For example,
         * in GL, this can be accomplished by calling glBindBuffer()
         * with the binding target as GL_SHADER_STORAGE_BUFFER.
         */
        storage_buffer = 1 << 8,

        /*!
         * If this bit is up, the depth or stencil test has been
         * modified.
         */
        depth_stencil = 1 << 9,

        /*!
         * If this bit is up, the color, depth or stencil masks
         * have changed. For example, in GL this is accomlished
         * by called glColorMask() glDepthMask() or glStencilMask().
         */
        buffer_masks = 1 << 10,

        /*!
         * If this bit is up, indicates that the HW clip planes
         * has changed.
         */
        hw_clip = 1 << 11,

        /*!
         * Specify that all state is dirty.
         */
        all = ~0u,
      };

    /*!
     * Ctor.
     * \param flags bit field using \ref bit_flags to specify
     *              what portion of GPU state is firty
     */
    gpu_dirty_state(uint32_t flags = 0u):
      m_flags(flags)
    {}

    /*!
     * Implicit cast-operator to uint32_t.
     */
    operator uint32_t() const { return m_flags; }

    /*!
     * Implicit cast-operator to uint32_t.
     */
    operator uint32_t&() { return m_flags; }

  private:
    uint32_t m_flags;
  };
/*! @} */
}
<commit_msg>gpu_dirty_state: change enum name for naming constitency<commit_after>/*!
 * \file gpu_dirty_state.hpp
 * \brief file gpu_dirty_state.hpp
 *
 * Copyright 2018 by Intel.
 *
 * Contact: kevin.rogovin@intel.com
 *
 * This Source Code Form is subject to the
 * terms of the Mozilla Public License, v. 2.0.
 * If a copy of the MPL was not distributed with
 * this file, You can obtain one at
 * http://mozilla.org/MPL/2.0/.
 *
 * \author Kevin Rogovin <kevin.rogovin@intel.com>
 *
 */

#pragma once

#include <stdint.h>

namespace fastuidraw
{
/*!\addtogroup Utility
 * @{
 */
  /*!
   * Object to encapsulate GPU dirty state via bit-flags.
   */
  class gpu_dirty_state
  {
  public:
    /*!
     * Enumeration to specify the bit-flags to specify
     * dirty GPU state.
     */
    enum bit_flags
      {
        /*!
         * If this bit is up, indicates that the shaders used
         * by the GPU has changed.
         */
        shader = 1 << 0,

        /*!
         * If this bit is up, indicates that  the binding
         * of the texture binding slots used by the shader
         * of a PainterBackend derived class have changed.
         * For example, in GL these changes are accompished
         * by calling glBindTexture().
         */
        textures = 1 << 1,

        /*!
         * If this bit is up, indicates that the binding
         * of the image binding slots used by the shader
         * of a PainterBackend derived class have changed.
         * For example, in GL these changes are accompished
         * by calling glBindImageTexture().
         */
        images = 1 << 2,

        /*!
         * If this bit is up, indicates that the blend
         * state of the GPU has changed.
         */
        blend_mode = 1 << 3,

        /*!
         * If this bit is up, indicates that the bound
         * render-target of the GPU has changed. For example,
         * in GL changing the render-target is accomplished
         * by glBindFramgebuffer() and/or glDrawBuffers().
         */
        render_target = 1 << 4,

        /*!
         * If this bit is up, indicates that the viewport
         * or scissor values have changed. For example, in GL
         * this is accomplished by calling glViewport(),
         * glScissor() or glEnable/glDisable() passing
         * GL_SCISSOR_TEST.
         */
        viewport_scissor = 1 << 5,

        /*!
         * If this bit is up, indicates that the source or format
         * for index or vertex buffers has changed. For example,
         * in GL, this can be accomplished by calling
         * glBindVertexArray() or modifying the currently bound
         * vertex array object.
         */
        vertex_index_source = 1 << 6,

        /*!
         * If this bit is up, indicates that a constant buffer
         * source has changed. For GL, these are UBOs. For example,
         * in GL, this can be accomplished by calling glBindBuffer()
         * with the binding target as GL_UNIFORM_BUFFER.
         */
        constant_buffers = 1 << 7,

        /*!
         * If this bit is up, indicates that a storage buffer
         * source has changed. For GL, these are UBOs. For example,
         * in GL, this can be accomplished by calling glBindBuffer()
         * with the binding target as GL_SHADER_STORAGE_BUFFER.
         */
        storage_buffers = 1 << 8,

        /*!
         * If this bit is up, the depth or stencil test has been
         * modified.
         */
        depth_stencil = 1 << 9,

        /*!
         * If this bit is up, the color, depth or stencil masks
         * have changed. For example, in GL this is accomlished
         * by called glColorMask() glDepthMask() or glStencilMask().
         */
        buffer_masks = 1 << 10,

        /*!
         * If this bit is up, indicates that the HW clip planes
         * has changed.
         */
        hw_clip = 1 << 11,

        /*!
         * Specify that all state is dirty.
         */
        all = ~0u,
      };

    /*!
     * Ctor.
     * \param flags bit field using \ref bit_flags to specify
     *              what portion of GPU state is firty
     */
    gpu_dirty_state(uint32_t flags = 0u):
      m_flags(flags)
    {}

    /*!
     * Implicit cast-operator to uint32_t.
     */
    operator uint32_t() const { return m_flags; }

    /*!
     * Implicit cast-operator to uint32_t.
     */
    operator uint32_t&() { return m_flags; }

  private:
    uint32_t m_flags;
  };
/*! @} */
}
<|endoftext|>


<commit_before>// -*- Mode:C++ -*-

/**************************************************************************************************/
/*                                                                                */
/* Copyright (C) 2016 University of Hull                                                          */
/*                                                                                */
/**************************************************************************************************/
/*                                                                                */
/*  module     :  hugh/platform/window/interactive.hpp                                            */
/*  project    :                                                                                */
/*  description:                                                                                */
/*                                                                                */
/**************************************************************************************************/

#if !defined(HUGH_PLATFORM_WINDOW_INTERACTIVE_HPP)

#define HUGH_PLATFORM_WINDOW_INTERACTIVE_HPP

// includes, system

//#include <>

// includes, project

#include <hugh/platform/window/simple.hpp>

namespace hugh {

  namespace platform {

    namespace window {

      class HUGH_PLATFORM_EXPORT interactive : private simple {

      public:

      protected:

      };

      // types, exported (class, enum, struct, union, typedef)

      // variables, exported (extern)

      // functions, inlined (inline)

      // functions, exported (extern)

    } // namespace window {

  } // namespace platform {

} // namespace hugh {

#endif // #if !defined(HUGH_PLATFORM_WINDOW_INTERACTIVE_HPP)
<commit_msg>removed: some leftovers<commit_after><|endoftext|>


<commit_before>#ifndef INCLUDE_AL_SYSTEM_PRINTING_H
#define INCLUDE_AL_SYSTEM_PRINTING_H

/*
 *  AlloSphere Research Group / Media Arts & Technology, UCSB, 2009
 */

/*
	Copyright (C) 2006-2008. The Regents of the University of California (REGENTS).
	All Rights Reserved.

	Permission to use, copy, modify, distribute, and distribute modified versions
	of this software and its documentation without fee and without a signed
	licensing agreement, is hereby granted, provided that the above copyright
	notice, the list of contributors, this paragraph and the following two paragraphs
	appear in all copies, modifications, and distributions.

	IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
	SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING
	OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS
	BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

	REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
	THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
	PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED
	HEREUNDER IS PROVIDED "AS IS". REGENTS HAS  NO OBLIGATION TO PROVIDE
	MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/

#include <stdio.h>
#include "allocore/system/al_Config.h"

namespace al{

/// Returns an ASCII character most closely matching an intensity value in [0,1].
char intensityToASCII(float v);

/// Print an array of numbers
template <class T>
void print(const T * arr, int size, const char * append="");

/// Print an array of number with new line
template <class T>
void println(const T * arr, int size){ print(arr, size, "\n"); }

/// Print value
template <class T>
void print(const T& v, const char * append=""){ print(&v, 1, append); }

/// Print value with new line
template <class T>
void println(const T& v){ print(v, "\n"); }

/// Prints 2D pixel array
template<class T> void print2D(T* pix, int nx, int ny, FILE * fp=stdout);

/// Print signed unit value on a horizontal plot.

/// @param[in]	value	Normalized value to plot
/// @param[in]	width	Character width of plot excluding center point
/// @param[in]	spaces	Print extra filling spaces to the right
/// @param[in]	point	The print character for points
void printPlot(float value, uint32_t width=50, bool spaces=true, const char * point="o");

/// Prints error messge to stderr and optionally calls exit()
void err(const char * msg, const char * src="", bool exits=true);

/// Prints warning messge to stderr
void warn(const char * msg, const char * src="");

// StateChange --------------------------------------------------------------

inline char intensityToASCII(float v){
	static const char map[] =
	" .,;-~_+<>i!lI?/|)(1}{][rcvunxzjftLCJUYXZO0Qoahkbdpqwm*WMB8&%$#@";
	//"$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ";
//	 123456789.123456789.123456789.123456789.123456789.123456789.1234
	static const int N = sizeof(map)-1;
	v = v<0 ? 0 : (v>0.9999999f ? 0.9999999f : v);
	return map[int(N*v)];
}

#define DEF_PRINT(T, code)\
template<>\
inline void print<T>(const T * arr, int size, const char * append){\
	for(int i=0; i<size; ++i){ printf(code" ", arr[i]); } if(append[0]) printf(append);\
}

DEF_PRINT(float, "%g")
DEF_PRINT(double, "%g")
DEF_PRINT(char, "%d")
DEF_PRINT(unsigned char, "%d")
DEF_PRINT(int, "%d")
DEF_PRINT(unsigned int, "%d")

#undef DEF_PRINT

template<class T> void print2D(T* pix, int nx, int ny, FILE * fp){
	for(int j=0; j<nx; ++j){
	for(int i=0; i<ny; ++i){
		float v = pix[j*nx + i];
		fprintf(fp, "%c ", intensityToASCII(v));
	} printf("\n"); }
}

} // ::al::

#endif
<commit_msg>additional types to printing functions<commit_after>#ifndef INCLUDE_AL_SYSTEM_PRINTING_H
#define INCLUDE_AL_SYSTEM_PRINTING_H

/*
 *  AlloSphere Research Group / Media Arts & Technology, UCSB, 2009
 */

/*
	Copyright (C) 2006-2008. The Regents of the University of California (REGENTS).
	All Rights Reserved.

	Permission to use, copy, modify, distribute, and distribute modified versions
	of this software and its documentation without fee and without a signed
	licensing agreement, is hereby granted, provided that the above copyright
	notice, the list of contributors, this paragraph and the following two paragraphs
	appear in all copies, modifications, and distributions.

	IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
	SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING
	OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS
	BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

	REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
	THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
	PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED
	HEREUNDER IS PROVIDED "AS IS". REGENTS HAS  NO OBLIGATION TO PROVIDE
	MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/

#include <stdio.h>
#include "allocore/system/al_Config.h"

namespace al{

/// Returns an ASCII character most closely matching an intensity value in [0,1].
char intensityToASCII(float v);

/// Print an array of numbers
template <typename T>
void print(const T * arr, int size, const char * append="");

/// Print an array of number with new line
template <typename T>
void println(const T * arr, int size){ print(arr, size, "\n"); }

/// Print value
template <typename T>
void print(const T& v, const char * append=""){ print(&v, 1, append); }

/// Print value with new line
template <typename T>
void println(const T& v){ print(v, "\n"); }

/// Prints 2D pixel array
template<class T> void print2D(T* pix, int nx, int ny, FILE * fp=stdout);

/// Print signed unit value on a horizontal plot.

/// @param[in]	value	Normalized value to plot
/// @param[in]	width	Character width of plot excluding center point
/// @param[in]	spaces	Print extra filling spaces to the right
/// @param[in]	point	The print character for points
void printPlot(float value, uint32_t width=50, bool spaces=true, const char * point="o");

/// Prints error messge to stderr and optionally calls exit()
void err(const char * msg, const char * src="", bool exits=true);

/// Prints warning messge to stderr
void warn(const char * msg, const char * src="");

// StateChange --------------------------------------------------------------

inline char intensityToASCII(float v){
	static const char map[] =
	" .,;-~_+<>i!lI?/|)(1}{][rcvunxzjftLCJUYXZO0Qoahkbdpqwm*WMB8&%$#@";
	//"$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ";
//	 123456789.123456789.123456789.123456789.123456789.123456789.1234
	static const int N = sizeof(map)-1;
	v = v<0 ? 0 : (v>0.9999999f ? 0.9999999f : v);
	return map[int(N*v)];
}

#define DEF_PRINT(T, code)\
template<>\
inline void print<T>(const T * arr, int size, const char * append){\
	for(int i=0; i<size; ++i){ printf(code" ", arr[i]); } if(append[0]) printf(append);\
}

DEF_PRINT(float, "%g")
DEF_PRINT(double, "%g")
DEF_PRINT(char, "%d")
DEF_PRINT(unsigned char, "%d")
DEF_PRINT(short, "%d")
DEF_PRINT(unsigned short, "%d")
DEF_PRINT(int, "%d")
DEF_PRINT(unsigned int, "%d")
DEF_PRINT(long, "%ld")
DEF_PRINT(unsigned long, "%ld")
DEF_PRINT(long long, "%lld")
DEF_PRINT(unsigned long long, "%lld")

#undef DEF_PRINT

template<class T> void print2D(T* pix, int nx, int ny, FILE * fp){
	for(int j=0; j<nx; ++j){
	for(int i=0; i<ny; ++i){
		float v = pix[j*nx + i];
		fprintf(fp, "%c ", intensityToASCII(v));
	} printf("\n"); }
}

} // ::al::

#endif
<|endoftext|>


<commit_before>#include "cvm.h"

#include "defaults_shared.h"

DabClass &DabVM::define_builtin_class(const std::string &name, dab_class_t class_index,
                                      dab_class_t superclass_index)
{
    DabClass klass;
    klass.index            = class_index;
    klass.name             = name;
    klass.builtin          = true;
    klass.superclass_index = superclass_index;
    classes[class_index]   = klass;
    return classes[class_index];
}

void DabVM::predefine_default_classes()
{
    fprintf(stderr, "vm: predefine default classes\n");

    define_builtin_class("Object", CLASS_OBJECT);
    define_builtin_class("String", CLASS_STRING);
    define_builtin_class("Fixnum", CLASS_FIXNUM);
    define_builtin_class("Boolean", CLASS_BOOLEAN);
    define_builtin_class("NilClass", CLASS_NILCLASS);
    define_builtin_class("Array", CLASS_ARRAY);
    define_builtin_class("Uint8", CLASS_UINT8, CLASS_FIXNUM);
    define_builtin_class("Uint16", CLASS_UINT16, CLASS_FIXNUM);
    define_builtin_class("Uint32", CLASS_UINT32, CLASS_FIXNUM);
    define_builtin_class("Uint64", CLASS_UINT64, CLASS_FIXNUM);
    define_builtin_class("Int8", CLASS_INT8, CLASS_FIXNUM);
    define_builtin_class("Int16", CLASS_INT16, CLASS_FIXNUM);
    define_builtin_class("Int32", CLASS_INT32, CLASS_FIXNUM);
    define_builtin_class("Int64", CLASS_INT64, CLASS_FIXNUM);
    define_builtin_class("Method", CLASS_METHOD);
    define_builtin_class("IntPtr", CLASS_INTPTR);
    define_builtin_class("ByteBuffer", CLASS_BYTEBUFFER);
    define_builtin_class("LiteralString", CLASS_LITERALSTRING, CLASS_STRING);
    define_builtin_class("DynamicString", CLASS_DYNAMICSTRING, CLASS_STRING);
}

void DabVM::define_default_classes()
{
    fprintf(stderr, "vm: define default classes\n");

    auto &object_class = get_class(CLASS_OBJECT);
    object_class.add_static_reg_function("new", [this](DabValue self, std::vector<DabValue>) {
        auto arg = self;
        assert(arg.data.type == TYPE_CLASS);
        auto instance = arg.create_instance();
        cinstcall(instance, "__construct");
        return instance;
    });
    object_class.add_reg_function(
        "class", [](DabValue self, std::vector<DabValue>) { return self.get_class(); });
    object_class.add_reg_function("to_s", [](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 0);
        return self.print_value();
    });
    object_class.add_reg_function("__construct", [](DabValue, std::vector<DabValue> args) {
        assert(args.size() == 0);
        return nullptr;
    });
    object_class.add_reg_function("__destruct", [](DabValue, std::vector<DabValue> args) {
        assert(args.size() == 0);
        return nullptr;
    });
    object_class.add_reg_function("is", [](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 1);
        auto arg0 = self;
        auto arg1 = args[0];
        return arg0.is_a(arg1.get_class());
    });
    object_class.add_static_reg_function("to_s", [](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 0);
        return self.class_name();
    });
    object_class.add_static_reg_function("==", [](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 1);
        auto arg0 = self;
        auto arg1 = args[0];
        assert(arg0.data.type == TYPE_CLASS);
        assert(arg1.data.type == TYPE_CLASS);
        return DabValue(arg0.data.fixnum == arg1.data.fixnum);
    });

    auto &string_class = get_class(CLASS_STRING);
    string_class.add_reg_function("upcase", [](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 0);
        auto s = self.string();
        std::transform(s.begin(), s.end(), s.begin(), ::toupper);
        return s;
    });
    string_class.add_reg_function("length", [](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 0);
        auto     s = self.string();
        DabValue ret(CLASS_INT32, (int)s.size());
        return ret;
    });
    string_class.add_reg_function("[]", [](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 1);
        auto arg = $VM->cast(args[0], CLASS_FIXNUM);
        auto s   = self.string();
        auto n   = arg.data.fixnum;
        return DabValue(s.substr(n, 1));
    });
    string_class.add_reg_function("+", [](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 1);
        auto arg0 = self;
        auto arg1 = $VM->cast(args[0], CLASS_STRING);
        auto s0   = arg0.string();
        auto s1   = arg1.string();
        return DabValue(s0 + s1);
    });
    string_class.add_static_reg_function("new", [](DabValue, std::vector<DabValue> args) {
        auto argc = args.size();
        assert(argc <= 2);
        DabValue ret_value;
        ret_value.data.type = TYPE_STRING;
        if (argc == 2)
        {
            auto        arg1   = $VM->cast(args[0], CLASS_BYTEBUFFER);
            auto        arg2   = $VM->cast(args[1], CLASS_FIXNUM);
            const auto &buffer = arg1.bytebuffer();
            const auto  length = arg2.data.fixnum;
            if (length)
            {
                ret_value.data.legacy_string = std::string((const char *)&buffer[0], length);
            }
        }
        else if (argc == 1)
        {
            ret_value.data.legacy_string = args[0].string();
        }
        return ret_value;
    });
    string_class.add_reg_function("to_s", [](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 0);
        return self;
    });
    DAB_MEMBER_EQUALS_OPERATORS(string_class, CLASS_STRING, .string());
    DAB_MEMBER_COMPARE_OPERATORS(string_class, CLASS_STRING, .string());

    auto &fixnum_class = get_class(CLASS_FIXNUM);
    fixnum_class.add_static_reg_function("new", [](DabValue self, std::vector<DabValue> args) {
        assert(args.size() <= 1);
        auto     klass = self;
        DabValue ret_value;
        ret_value.data.type   = TYPE_FIXNUM;
        ret_value.data.fixnum = 0;
        if (args.size() == 1)
        {
            auto arg = args[0];
            assert(arg.data.type == TYPE_FIXNUM);
            ret_value.data.fixnum = arg.data.fixnum;
        }
        return ret_value;
    });
    DAB_MEMBER_NUMERIC_OPERATORS(fixnum_class, CLASS_FIXNUM, uint64_t, .data.fixnum);

    define_default_classes_int();

    auto &intptr_class = get_class(CLASS_INTPTR);
    intptr_class.add_reg_function("fetch_int32", [](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 0);
        auto     ptr   = self.data.intptr;
        auto     iptr  = (int32_t *)ptr;
        auto     value = *iptr;
        DabValue ret(CLASS_INT32, value);
        return ret;
    });

    auto &boolean_class = get_class(CLASS_BOOLEAN);
    DAB_MEMBER_EQUALS_OPERATORS(boolean_class, CLASS_BOOLEAN, .data.boolean);

    auto &array_class = get_class(CLASS_ARRAY);
    array_class.add_reg_function("count", [](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 0);
        assert(self.data.type == TYPE_ARRAY);
        return (uint64_t)self.array().size();
    });
    array_class.add_reg_function("shift", [this](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 0);
        assert(self.data.type == TYPE_ARRAY);
        auto &a = self.array();
        if (a.size() == 0)
        {
            return DabValue(nullptr);
        }
        else
        {
            auto ret = a[0];
            a.erase(a.begin());
            return ret;
        }
    });
    array_class.add_reg_function("insert", [this](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 1);
        auto arg = args[0];
        assert(self.data.type == TYPE_ARRAY);
        auto &a = self.array();
        a.push_back(arg);
        return nullptr;
    });
    array_class.add_reg_function("[]", [this](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 1);
        auto arg0 = self;
        auto arg1 = args[0];
        assert(arg0.data.type == TYPE_ARRAY);
        assert(arg1.data.type == TYPE_FIXNUM);
        auto &a = arg0.array();
        auto  n = arg1.data.fixnum;
        if (n < 0)
            n = a.size() + n;
        if (n < 0 || n >= (int64_t)a.size())
            return DabValue(nullptr);
        else
            return a[n];
    });
    array_class.add_reg_function("[]=", [this](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 2);
        auto arg0 = self;
        auto arg1 = args[0];
        auto arg2 = args[1];
        assert(arg0.data.type == TYPE_ARRAY);
        assert(arg1.data.type == TYPE_FIXNUM);
        auto &a = arg0.array();
        auto  n = arg1.data.fixnum;
        if (n < 0)
            n = a.size() + n;
        if (n < 0 || n >= (int64_t)a.size())
        {
            fprintf(stderr, "vm: index outside of array bounds.\n");
            exit(1);
        }
        else
        {
            a[n] = arg2;
        }
        return nullptr;
    });
    array_class.add_reg_function("join", [this](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 0);
        std::string ret;
        auto &      a = self.array();
        for (size_t i = 0; i < a.size(); i++)
        {
            if (i)
                ret += ", ";
            auto val = cinstcall(a[i], "to_s");
            ret += val.string();
        }
        return ret;
    });
    array_class.add_reg_function("to_s", [this](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 0);
        auto inner = cinstcall(self, "join");
        auto ret   = std::string("[" + inner.string() + "]");
        if (!$VM->options.autorelease)
        {
            inner.release();
        }
        return ret;
    });
    array_class.add_reg_function("+", [](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 1);
        auto arg = $VM->cast(args[0], CLASS_ARRAY);
        return $VM->merge_arrays(self, arg);
    });

    auto &method_class = get_class(CLASS_METHOD);
    method_class.add_reg_function("to_s", [this](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 0);
        return std::string("@method(" + self.string() + ")");
    });

    auto &bytebuffer_class = get_class(CLASS_BYTEBUFFER);
    bytebuffer_class.add_static_reg_function("new", [](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 1);
        auto klass = self;
        assert(klass.data.type == TYPE_CLASS);

        auto instance = klass.create_instance();

        auto _size = $VM->cast(args[0], CLASS_FIXNUM);
        auto size  = _size.data.fixnum;
        instance.bytebuffer().resize(size);
        return instance;
    });
    bytebuffer_class.add_reg_function("[]", [this](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 1);
        auto arg0 = self;
        auto arg1 = args[0];
        assert(arg0.data.type == TYPE_BYTEBUFFER);
        assert(arg1.data.type == TYPE_FIXNUM);
        auto &a = arg0.bytebuffer();
        auto  n = arg1.data.fixnum;
        if (n < 0)
            n = a.size() + n;
        if (n < 0 || n >= (int64_t)a.size())
            return DabValue(nullptr);
        else
            return DabValue(CLASS_UINT8, a[n]);
    });
    bytebuffer_class.add_reg_function("[]=", [this](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 2);
        auto arg0 = self;
        auto arg1 = args[0];
        auto arg2 = args[1];
        assert(arg0.data.type == TYPE_BYTEBUFFER);
        assert(arg1.data.type == TYPE_FIXNUM);
        auto &a = arg0.bytebuffer();
        auto  n = arg1.data.fixnum;
        if (n < 0)
            n = a.size() + n;
        if (n >= 0 && n < (int64_t)a.size())
        {
            a[n] = $VM->cast(arg2, CLASS_UINT8).data.num_uint8;
        }
        return nullptr;
    });
    bytebuffer_class.add_reg_function("to_s", [this](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 0);
        std::string ret;
        auto &      a = self.bytebuffer();
        for (size_t i = 0; i < a.size(); i++)
        {
            if (i)
                ret += ", ";
            char string[32];
            sprintf(string, "%d", (int)a[i]);
            ret += string;
        }
        return "[" + ret + "]";
    });
}
<commit_msg>vm: String.self should retain return value<commit_after>#include "cvm.h"

#include "defaults_shared.h"

DabClass &DabVM::define_builtin_class(const std::string &name, dab_class_t class_index,
                                      dab_class_t superclass_index)
{
    DabClass klass;
    klass.index            = class_index;
    klass.name             = name;
    klass.builtin          = true;
    klass.superclass_index = superclass_index;
    classes[class_index]   = klass;
    return classes[class_index];
}

void DabVM::predefine_default_classes()
{
    fprintf(stderr, "vm: predefine default classes\n");

    define_builtin_class("Object", CLASS_OBJECT);
    define_builtin_class("String", CLASS_STRING);
    define_builtin_class("Fixnum", CLASS_FIXNUM);
    define_builtin_class("Boolean", CLASS_BOOLEAN);
    define_builtin_class("NilClass", CLASS_NILCLASS);
    define_builtin_class("Array", CLASS_ARRAY);
    define_builtin_class("Uint8", CLASS_UINT8, CLASS_FIXNUM);
    define_builtin_class("Uint16", CLASS_UINT16, CLASS_FIXNUM);
    define_builtin_class("Uint32", CLASS_UINT32, CLASS_FIXNUM);
    define_builtin_class("Uint64", CLASS_UINT64, CLASS_FIXNUM);
    define_builtin_class("Int8", CLASS_INT8, CLASS_FIXNUM);
    define_builtin_class("Int16", CLASS_INT16, CLASS_FIXNUM);
    define_builtin_class("Int32", CLASS_INT32, CLASS_FIXNUM);
    define_builtin_class("Int64", CLASS_INT64, CLASS_FIXNUM);
    define_builtin_class("Method", CLASS_METHOD);
    define_builtin_class("IntPtr", CLASS_INTPTR);
    define_builtin_class("ByteBuffer", CLASS_BYTEBUFFER);
    define_builtin_class("LiteralString", CLASS_LITERALSTRING, CLASS_STRING);
    define_builtin_class("DynamicString", CLASS_DYNAMICSTRING, CLASS_STRING);
}

void DabVM::define_default_classes()
{
    fprintf(stderr, "vm: define default classes\n");

    auto &object_class = get_class(CLASS_OBJECT);
    object_class.add_static_reg_function("new", [this](DabValue self, std::vector<DabValue>) {
        auto arg = self;
        assert(arg.data.type == TYPE_CLASS);
        auto instance = arg.create_instance();
        cinstcall(instance, "__construct");
        return instance;
    });
    object_class.add_reg_function(
        "class", [](DabValue self, std::vector<DabValue>) { return self.get_class(); });
    object_class.add_reg_function("to_s", [](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 0);
        return self.print_value();
    });
    object_class.add_reg_function("__construct", [](DabValue, std::vector<DabValue> args) {
        assert(args.size() == 0);
        return nullptr;
    });
    object_class.add_reg_function("__destruct", [](DabValue, std::vector<DabValue> args) {
        assert(args.size() == 0);
        return nullptr;
    });
    object_class.add_reg_function("is", [](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 1);
        auto arg0 = self;
        auto arg1 = args[0];
        return arg0.is_a(arg1.get_class());
    });
    object_class.add_static_reg_function("to_s", [](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 0);
        return self.class_name();
    });
    object_class.add_static_reg_function("==", [](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 1);
        auto arg0 = self;
        auto arg1 = args[0];
        assert(arg0.data.type == TYPE_CLASS);
        assert(arg1.data.type == TYPE_CLASS);
        return DabValue(arg0.data.fixnum == arg1.data.fixnum);
    });

    auto &string_class = get_class(CLASS_STRING);
    string_class.add_reg_function("upcase", [](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 0);
        auto s = self.string();
        std::transform(s.begin(), s.end(), s.begin(), ::toupper);
        return s;
    });
    string_class.add_reg_function("length", [](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 0);
        auto     s = self.string();
        DabValue ret(CLASS_INT32, (int)s.size());
        return ret;
    });
    string_class.add_reg_function("[]", [](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 1);
        auto arg = $VM->cast(args[0], CLASS_FIXNUM);
        auto s   = self.string();
        auto n   = arg.data.fixnum;
        return DabValue(s.substr(n, 1));
    });
    string_class.add_reg_function("+", [](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 1);
        auto arg0 = self;
        auto arg1 = $VM->cast(args[0], CLASS_STRING);
        auto s0   = arg0.string();
        auto s1   = arg1.string();
        return DabValue(s0 + s1);
    });
    string_class.add_static_reg_function("new", [](DabValue, std::vector<DabValue> args) {
        auto argc = args.size();
        assert(argc <= 2);
        DabValue ret_value;
        ret_value.data.type = TYPE_STRING;
        if (argc == 2)
        {
            auto        arg1   = $VM->cast(args[0], CLASS_BYTEBUFFER);
            auto        arg2   = $VM->cast(args[1], CLASS_FIXNUM);
            const auto &buffer = arg1.bytebuffer();
            const auto  length = arg2.data.fixnum;
            if (length)
            {
                ret_value.data.legacy_string = std::string((const char *)&buffer[0], length);
            }
        }
        else if (argc == 1)
        {
            ret_value.data.legacy_string = args[0].string();
        }
        return ret_value;
    });
    string_class.add_reg_function("to_s", [](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 0);
        if (!$VM->options.autorelease)
        {
            self.retain();
        }
        return self;
    });
    DAB_MEMBER_EQUALS_OPERATORS(string_class, CLASS_STRING, .string());
    DAB_MEMBER_COMPARE_OPERATORS(string_class, CLASS_STRING, .string());

    auto &fixnum_class = get_class(CLASS_FIXNUM);
    fixnum_class.add_static_reg_function("new", [](DabValue self, std::vector<DabValue> args) {
        assert(args.size() <= 1);
        auto     klass = self;
        DabValue ret_value;
        ret_value.data.type   = TYPE_FIXNUM;
        ret_value.data.fixnum = 0;
        if (args.size() == 1)
        {
            auto arg = args[0];
            assert(arg.data.type == TYPE_FIXNUM);
            ret_value.data.fixnum = arg.data.fixnum;
        }
        return ret_value;
    });
    DAB_MEMBER_NUMERIC_OPERATORS(fixnum_class, CLASS_FIXNUM, uint64_t, .data.fixnum);

    define_default_classes_int();

    auto &intptr_class = get_class(CLASS_INTPTR);
    intptr_class.add_reg_function("fetch_int32", [](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 0);
        auto     ptr   = self.data.intptr;
        auto     iptr  = (int32_t *)ptr;
        auto     value = *iptr;
        DabValue ret(CLASS_INT32, value);
        return ret;
    });

    auto &boolean_class = get_class(CLASS_BOOLEAN);
    DAB_MEMBER_EQUALS_OPERATORS(boolean_class, CLASS_BOOLEAN, .data.boolean);

    auto &array_class = get_class(CLASS_ARRAY);
    array_class.add_reg_function("count", [](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 0);
        assert(self.data.type == TYPE_ARRAY);
        return (uint64_t)self.array().size();
    });
    array_class.add_reg_function("shift", [this](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 0);
        assert(self.data.type == TYPE_ARRAY);
        auto &a = self.array();
        if (a.size() == 0)
        {
            return DabValue(nullptr);
        }
        else
        {
            auto ret = a[0];
            a.erase(a.begin());
            return ret;
        }
    });
    array_class.add_reg_function("insert", [this](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 1);
        auto arg = args[0];
        assert(self.data.type == TYPE_ARRAY);
        auto &a = self.array();
        a.push_back(arg);
        return nullptr;
    });
    array_class.add_reg_function("[]", [this](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 1);
        auto arg0 = self;
        auto arg1 = args[0];
        assert(arg0.data.type == TYPE_ARRAY);
        assert(arg1.data.type == TYPE_FIXNUM);
        auto &a = arg0.array();
        auto  n = arg1.data.fixnum;
        if (n < 0)
            n = a.size() + n;
        if (n < 0 || n >= (int64_t)a.size())
            return DabValue(nullptr);
        else
            return a[n];
    });
    array_class.add_reg_function("[]=", [this](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 2);
        auto arg0 = self;
        auto arg1 = args[0];
        auto arg2 = args[1];
        assert(arg0.data.type == TYPE_ARRAY);
        assert(arg1.data.type == TYPE_FIXNUM);
        auto &a = arg0.array();
        auto  n = arg1.data.fixnum;
        if (n < 0)
            n = a.size() + n;
        if (n < 0 || n >= (int64_t)a.size())
        {
            fprintf(stderr, "vm: index outside of array bounds.\n");
            exit(1);
        }
        else
        {
            a[n] = arg2;
        }
        return nullptr;
    });
    array_class.add_reg_function("join", [this](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 0);
        std::string ret;
        auto &      a = self.array();
        for (size_t i = 0; i < a.size(); i++)
        {
            if (i)
                ret += ", ";
            auto val = cinstcall(a[i], "to_s");
            ret += val.string();
            if (!$VM->options.autorelease)
            {
                val.release();
            }
        }
        return ret;
    });
    array_class.add_reg_function("to_s", [this](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 0);
        auto inner = cinstcall(self, "join");
        auto ret   = std::string("[" + inner.string() + "]");
        if (!$VM->options.autorelease)
        {
            inner.release();
        }
        return ret;
    });
    array_class.add_reg_function("+", [](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 1);
        auto arg = $VM->cast(args[0], CLASS_ARRAY);
        return $VM->merge_arrays(self, arg);
    });

    auto &method_class = get_class(CLASS_METHOD);
    method_class.add_reg_function("to_s", [this](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 0);
        return std::string("@method(" + self.string() + ")");
    });

    auto &bytebuffer_class = get_class(CLASS_BYTEBUFFER);
    bytebuffer_class.add_static_reg_function("new", [](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 1);
        auto klass = self;
        assert(klass.data.type == TYPE_CLASS);

        auto instance = klass.create_instance();

        auto _size = $VM->cast(args[0], CLASS_FIXNUM);
        auto size  = _size.data.fixnum;
        instance.bytebuffer().resize(size);
        return instance;
    });
    bytebuffer_class.add_reg_function("[]", [this](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 1);
        auto arg0 = self;
        auto arg1 = args[0];
        assert(arg0.data.type == TYPE_BYTEBUFFER);
        assert(arg1.data.type == TYPE_FIXNUM);
        auto &a = arg0.bytebuffer();
        auto  n = arg1.data.fixnum;
        if (n < 0)
            n = a.size() + n;
        if (n < 0 || n >= (int64_t)a.size())
            return DabValue(nullptr);
        else
            return DabValue(CLASS_UINT8, a[n]);
    });
    bytebuffer_class.add_reg_function("[]=", [this](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 2);
        auto arg0 = self;
        auto arg1 = args[0];
        auto arg2 = args[1];
        assert(arg0.data.type == TYPE_BYTEBUFFER);
        assert(arg1.data.type == TYPE_FIXNUM);
        auto &a = arg0.bytebuffer();
        auto  n = arg1.data.fixnum;
        if (n < 0)
            n = a.size() + n;
        if (n >= 0 && n < (int64_t)a.size())
        {
            a[n] = $VM->cast(arg2, CLASS_UINT8).data.num_uint8;
        }
        return nullptr;
    });
    bytebuffer_class.add_reg_function("to_s", [this](DabValue self, std::vector<DabValue> args) {
        assert(args.size() == 0);
        std::string ret;
        auto &      a = self.bytebuffer();
        for (size_t i = 0; i < a.size(); i++)
        {
            if (i)
                ret += ", ";
            char string[32];
            sprintf(string, "%d", (int)a[i]);
            ret += string;
        }
        return "[" + ret + "]";
    });
}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#pragma once

#include "etl/expr/base_temporary_expr.hpp"

//Get the implementations
#include "etl/impl/conv.hpp"

namespace etl {

/*!
 * \brief A transposition expression.
 * \tparam A The transposed type
 */
template <typename A, typename B, size_t S1, size_t S2, size_t P1, size_t P2, bool Flipped>
struct conv_2d_valid_expr : base_temporary_expr_bin<conv_2d_valid_expr<A, B, S1, S2, P1, P2, Flipped>, A, B> {
    using value_type  = value_t<A>;                               ///< The type of value of the expression
    using this_type   = conv_2d_valid_expr<A, B, S1, S2, P1, P2, Flipped>;         ///< The type of this expression
    using base_type   = base_temporary_expr_bin<this_type, A, B>; ///< The base type
    using left_traits = decay_traits<A>;                          ///< The traits of the sub type

    static constexpr auto storage_order = left_traits::storage_order; ///< The sub storage order

    /*!
     * \brief Construct a new expression
     * \param a The sub expression
     */
    explicit conv_2d_valid_expr(A a, B b) : base_type(a, b) {
        //Nothing else to init
    }

    // Assignment functions

    /*!
     * \brief Assert that the convolution is done on correct dimensions
     */
    template <typename I, typename K, typename C, cpp_disable_if(all_fast<A, B, C>::value)>
    static void check(const I& input, const K& kernel, const C& conv){
        static_assert(etl::dimensions<I>() == 2, "Invalid number of dimensions for input of conv2_valid");
        static_assert(etl::dimensions<K>() == 2, "Invalid number of dimensions for kernel of conv2_valid");
        static_assert(etl::dimensions<C>() == 2, "Invalid number of dimensions for conv of conv2_valid");

        cpp_assert(etl::dim(conv, 0) == (etl::dim(input, 0) - etl::dim(kernel, 0) + 2 * P1) / S1 + 1, "Invalid dimensions for conv2_valid");
        cpp_assert(etl::dim(conv, 1) == (etl::dim(input, 1) - etl::dim(kernel, 1) + 2 * P2) / S2 + 1, "Invalid dimensions for conv2_valid");

        cpp_unused(input);
        cpp_unused(kernel);
        cpp_unused(conv);
    }

    /*!
     * \brief Assert that the convolution is done on correct dimensions
     */
    template <typename I, typename K, typename C, cpp_enable_if(all_fast<A, B, C>::value)>
    static void check(const I& input, const K& kernel, const C& conv){
        static_assert(etl::dimensions<I>() == 2, "Invalid number of dimensions for input of conv2_valid");
        static_assert(etl::dimensions<K>() == 2, "Invalid number of dimensions for kernel of conv2_valid");
        static_assert(etl::dimensions<C>() == 2, "Invalid number of dimensions for conv of conv2_valid");

        static_assert(etl::dim<0, C>() == (etl::dim<0, I>() - etl::dim<0, K>() + 2 * P1) / S1 + 1, "Invalid dimensions for conv2_valid");
        static_assert(etl::dim<1, C>() == (etl::dim<1, I>() - etl::dim<1, K>() + 2 * P2) / S2 + 1, "Invalid dimensions for conv2_valid");

        cpp_unused(input);
        cpp_unused(kernel);
        cpp_unused(conv);
    }

    /*!
     * \brief Assign to a matrix
     * \param c The expression to which assign
     */
    template<typename C>
    void assign_to(C&& c)  const {
        static_assert(all_etl_expr<A, B, C>::value, "conv2_valid only supported for ETL expressions");

        auto& a = this->a();
        auto& b = this->b();

        check(a, b, c);

        standard_evaluator::pre_assign_rhs(a);
        standard_evaluator::pre_assign_rhs(b);
        standard_evaluator::pre_assign_lhs(c);

        if /* constexpr */ (Flipped){
            detail::conv2_valid_flipped_impl<S1, S2, P1, P2>::apply(make_temporary(a), make_temporary(b), c);
        } else {
            detail::conv2_valid_impl<S1, S2, P1, P2>::apply(make_temporary(a), make_temporary(b), c);
        }
    }

    /*!
     * \brief Add to the given left-hand-side expression
     * \param lhs The expression to which assign
     */
    template<typename L>
    void assign_add_to(L&& lhs)  const {
        std_add_evaluate(*this, lhs);
    }

    /*!
     * \brief Sub from the given left-hand-side expression
     * \param lhs The expression to which assign
     */
    template<typename L>
    void assign_sub_to(L&& lhs)  const {
        std_sub_evaluate(*this, lhs);
    }

    /*!
     * \brief Multiply the given left-hand-side expression
     * \param lhs The expression to which assign
     */
    template<typename L>
    void assign_mul_to(L&& lhs)  const {
        std_mul_evaluate(*this, lhs);
    }

    /*!
     * \brief Divide the given left-hand-side expression
     * \param lhs The expression to which assign
     */
    template<typename L>
    void assign_div_to(L&& lhs)  const {
        std_div_evaluate(*this, lhs);
    }

    /*!
     * \brief Modulo the given left-hand-side expression
     * \param lhs The expression to which assign
     */
    template<typename L>
    void assign_mod_to(L&& lhs)  const {
        std_mod_evaluate(*this, lhs);
    }

    /*!
     * \brief Print a representation of the expression on the given stream
     * \param os The output stream
     * \param expr The expression to print
     * \return the output stream
     */
    friend std::ostream& operator<<(std::ostream& os, const conv_2d_valid_expr& expr) {
        return os << "conv2_valid(" << expr._a << ", " << expr._b << ")";
    }
};

/*!
 * \brief Traits for a transpose expression
 * \tparam A The transposed sub type
 */
template <typename A, typename B, size_t S1, size_t S2, size_t P1, size_t P2, bool Flipped>
struct etl_traits<etl::conv_2d_valid_expr<A, B, S1, S2, P1, P2, Flipped>> {
    using expr_t       = etl::conv_2d_valid_expr<A, B, S1, S2, P1, P2, Flipped>; ///< The expression type
    using left_expr_t  = std::decay_t<A>;                                       ///< The left sub expression type
    using right_expr_t = std::decay_t<B>;                                       ///< The right sub expression type
    using left_traits  = etl_traits<left_expr_t>;                               ///< The left sub traits
    using right_traits = etl_traits<right_expr_t>;                              ///< The right sub traits
    using value_type   = value_t<A>;                                            ///< The value type of the expression

    static constexpr bool is_etl          = true;                       ///< Indicates if the type is an ETL expression
    static constexpr bool is_transformer  = false;                      ///< Indicates if the type is a transformer
    static constexpr bool is_view         = false;                      ///< Indicates if the type is a view
    static constexpr bool is_magic_view   = false;                      ///< Indicates if the type is a magic view
    static constexpr bool is_fast         = all_fast<A, B>::value;      ///< Indicates if the expression is fast
    static constexpr bool is_linear       = true;                       ///< Indicates if the expression is linear
    static constexpr bool is_thread_safe  = true;                       ///< Indicates if the expression is thread safe
    static constexpr bool is_value        = false;                      ///< Indicates if the expression is of value type
    static constexpr bool is_direct       = true;                       ///< Indicates if the expression has direct memory access
    static constexpr bool is_generator    = false;                      ///< Indicates if the expression is a generator
    static constexpr bool is_padded       = false;                      ///< Indicates if the expression is padded
    static constexpr bool is_aligned      = true;                       ///< Indicates if the expression is padded
    static constexpr bool is_gpu          = false;                      ///< Indicates if the expression can be done on GPU
    static constexpr bool needs_evaluator = true;                       ///< Indicates if the expression needs a evaluator visitor
    static constexpr order storage_order  = left_traits::storage_order; ///< The expression's storage order

    /*!
     * \brief Indicates if the expression is vectorizable using the
     * given vector mode
     * \tparam V The vector mode
     */
    template <vector_mode_t V>
    using vectorizable = std::true_type;

    /*!
     * \brief Returns the DDth dimension of the expression
     * \return the DDth dimension of the expression
     */
    template <size_t DD>
    static constexpr size_t dim() {
        return DD == 0 ? (etl::dim<0, A>() - etl::dim<0, B>() + 2 * P1) / S1 + 1
                       : (etl::dim<1, A>() - etl::dim<1, B>() + 2 * P2) / S2 + 1;
    }

    /*!
     * \brief Returns the dth dimension of the expression
     * \param e The sub expression
     * \param d The dimension to get
     * \return the dth dimension of the expression
     */
    static size_t dim(const expr_t& e, size_t d) {
        if (d == 0){
            return (etl::dim(e._a, 0) - etl::dim(e._b, 0) + 2 * P1) / S1 + 1;
        } else {
            return (etl::dim(e._a, 1) - etl::dim(e._b, 1) + 2 * P2) / S2 + 1;
        }
    }

    /*!
     * \brief Returns the size of the expression
     * \param e The sub expression
     * \return the size of the expression
     */
    static size_t size(const expr_t& e) {
        return ((etl::dim(e._a, 0) - etl::dim(e._b, 0) + 2 * P1) / S1 + 1)
            *  ((etl::dim(e._a, 1) - etl::dim(e._b, 1) + 2 * P2) / S2 + 1);
    }

    /*!
     * \brief Returns the size of the expression
     * \return the size of the expression
     */
    static constexpr size_t size() {
        return  ((etl::dim<0, A>() - etl::dim<0, B>() + 2 * P1) / S1 + 1)
              * ((etl::dim<1, A>() - etl::dim<1, B>() + 2 * P2) / S2 + 1);
    }

    /*!
     * \brief Returns the number of dimensions of the expression
     * \return the number of dimensions of the expression
     */
    static constexpr size_t dimensions() {
        return 2;
    }
};

/*!
 * \brief Creates an expression representing the 'valid' 1D convolution of a and b.
 *
 * \param a The input expression
 * \param b The kernel expression
 *
 * \return an expression representing the 'valid' 1D convolution of a and b
 */
template <size_t S1 = 1, size_t S2 = 1, size_t P1 = 0, size_t P2 = 0, typename A, typename B>
conv_2d_valid_expr<detail::build_type<A>, detail::build_type<B>, S1, S2, P1, P2, false> conv_2d_valid(A&& a, B&& b) {
    static_assert(all_etl_expr<A, B>::value, "Convolution only supported for ETL expressions");

    return conv_2d_valid_expr<detail::build_type<A>, detail::build_type<B>, S1, S2, P1, P2, false>{a, b};
}

/*!
 * \brief Creates an expression representing the 'valid' 1D convolution of a and b, the result will be stored in c
 *
 * \param a The input expression
 * \param b The kernel expression
 * \param c The result
 *
 * \return an expression representing the 'valid' 1D convolution of a and b
 */
template <size_t S1 = 1, size_t S2 = 1, size_t P1 = 0, size_t P2 = 0, typename A, typename B, typename C>
auto conv_2d_valid(A&& a, B&& b, C&& c){
    static_assert(all_etl_expr<A, B, C>::value, "Convolution only supported for ETL expressions");

    c = conv_2d_valid<S1, S2, P1, P2>(a, b);

    return c;
}

/*!
 * \brief Creates an expression representing the 'valid' 1D convolution of a and flipped b.
 *
 * \param a The input expression
 * \param b The kernel expression
 *
 * \return an expression representing the 'valid' 1D convolution of a and b
 */
template <size_t S1 = 1, size_t S2 = 1, size_t P1 = 0, size_t P2 = 0, typename A, typename B>
conv_2d_valid_expr<detail::build_type<A>, detail::build_type<B>, S1, S2, P1, P2, true> conv_2d_valid_flipped(A&& a, B&& b) {
    static_assert(all_etl_expr<A, B>::value, "Convolution only supported for ETL expressions");

    return conv_2d_valid_expr<detail::build_type<A>, detail::build_type<B>, S1, S2, P1, P2, true>{a, b};
}

/*!
 * \brief Creates an expression representing the 'valid' 1D convolution of a and flipped b, the result will be stored in c
 *
 * \param a The input expression
 * \param b The kernel expression
 * \param c The result
 *
 * \return an expression representing the 'valid' 1D convolution of a and b
 */
template <size_t S1 = 1, size_t S2 = 1, size_t P1 = 0, size_t P2 = 0, typename A, typename B, typename C>
auto conv_2d_valid_flipped(A&& a, B&& b, C&& c){
    static_assert(all_etl_expr<A, B, C>::value, "Convolution only supported for ETL expressions");

    c = conv_2d_valid_flipped<S1, S2, P1, P2>(a, b);

    return c;
}

} //end of namespace etl
<commit_msg>Complete doc<commit_after>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#pragma once

#include "etl/expr/base_temporary_expr.hpp"

//Get the implementations
#include "etl/impl/conv.hpp"

namespace etl {

/*!
 * \brief Expression representing the 2D 'valid' convolution of an
 * image with a kernel.
 *
 * \tparam A The input type
 * \tparam B The kernel type
 * \tparam S1 The stride of the first dimension
 * \tparam S2 The stride of the second dimension
 * \tparam P1 The padding of the first dimension
 * \tparam P2 The padding of the second dimension
 * \tparam Flipped Indicates if Flipped already or not or not
 */
template <typename A, typename B, size_t S1, size_t S2, size_t P1, size_t P2, bool Flipped>
struct conv_2d_valid_expr : base_temporary_expr_bin<conv_2d_valid_expr<A, B, S1, S2, P1, P2, Flipped>, A, B> {
    using value_type  = value_t<A>;                               ///< The type of value of the expression
    using this_type   = conv_2d_valid_expr<A, B, S1, S2, P1, P2, Flipped>;         ///< The type of this expression
    using base_type   = base_temporary_expr_bin<this_type, A, B>; ///< The base type
    using left_traits = decay_traits<A>;                          ///< The traits of the sub type

    static constexpr auto storage_order = left_traits::storage_order; ///< The sub storage order

    /*!
     * \brief Construct a new expression
     * \param a The sub expression
     */
    explicit conv_2d_valid_expr(A a, B b) : base_type(a, b) {
        //Nothing else to init
    }

    // Assignment functions

    /*!
     * \brief Assert that the convolution is done on correct dimensions
     */
    template <typename I, typename K, typename C, cpp_disable_if(all_fast<A, B, C>::value)>
    static void check(const I& input, const K& kernel, const C& conv){
        static_assert(etl::dimensions<I>() == 2, "Invalid number of dimensions for input of conv2_valid");
        static_assert(etl::dimensions<K>() == 2, "Invalid number of dimensions for kernel of conv2_valid");
        static_assert(etl::dimensions<C>() == 2, "Invalid number of dimensions for conv of conv2_valid");

        cpp_assert(etl::dim(conv, 0) == (etl::dim(input, 0) - etl::dim(kernel, 0) + 2 * P1) / S1 + 1, "Invalid dimensions for conv2_valid");
        cpp_assert(etl::dim(conv, 1) == (etl::dim(input, 1) - etl::dim(kernel, 1) + 2 * P2) / S2 + 1, "Invalid dimensions for conv2_valid");

        cpp_unused(input);
        cpp_unused(kernel);
        cpp_unused(conv);
    }

    /*!
     * \brief Assert that the convolution is done on correct dimensions
     */
    template <typename I, typename K, typename C, cpp_enable_if(all_fast<A, B, C>::value)>
    static void check(const I& input, const K& kernel, const C& conv){
        static_assert(etl::dimensions<I>() == 2, "Invalid number of dimensions for input of conv2_valid");
        static_assert(etl::dimensions<K>() == 2, "Invalid number of dimensions for kernel of conv2_valid");
        static_assert(etl::dimensions<C>() == 2, "Invalid number of dimensions for conv of conv2_valid");

        static_assert(etl::dim<0, C>() == (etl::dim<0, I>() - etl::dim<0, K>() + 2 * P1) / S1 + 1, "Invalid dimensions for conv2_valid");
        static_assert(etl::dim<1, C>() == (etl::dim<1, I>() - etl::dim<1, K>() + 2 * P2) / S2 + 1, "Invalid dimensions for conv2_valid");

        cpp_unused(input);
        cpp_unused(kernel);
        cpp_unused(conv);
    }

    /*!
     * \brief Assign to a matrix
     * \param c The expression to which assign
     */
    template<typename C>
    void assign_to(C&& c)  const {
        static_assert(all_etl_expr<A, B, C>::value, "conv2_valid only supported for ETL expressions");

        auto& a = this->a();
        auto& b = this->b();

        check(a, b, c);

        standard_evaluator::pre_assign_rhs(a);
        standard_evaluator::pre_assign_rhs(b);
        standard_evaluator::pre_assign_lhs(c);

        if /* constexpr */ (Flipped){
            detail::conv2_valid_flipped_impl<S1, S2, P1, P2>::apply(make_temporary(a), make_temporary(b), c);
        } else {
            detail::conv2_valid_impl<S1, S2, P1, P2>::apply(make_temporary(a), make_temporary(b), c);
        }
    }

    /*!
     * \brief Add to the given left-hand-side expression
     * \param lhs The expression to which assign
     */
    template<typename L>
    void assign_add_to(L&& lhs)  const {
        std_add_evaluate(*this, lhs);
    }

    /*!
     * \brief Sub from the given left-hand-side expression
     * \param lhs The expression to which assign
     */
    template<typename L>
    void assign_sub_to(L&& lhs)  const {
        std_sub_evaluate(*this, lhs);
    }

    /*!
     * \brief Multiply the given left-hand-side expression
     * \param lhs The expression to which assign
     */
    template<typename L>
    void assign_mul_to(L&& lhs)  const {
        std_mul_evaluate(*this, lhs);
    }

    /*!
     * \brief Divide the given left-hand-side expression
     * \param lhs The expression to which assign
     */
    template<typename L>
    void assign_div_to(L&& lhs)  const {
        std_div_evaluate(*this, lhs);
    }

    /*!
     * \brief Modulo the given left-hand-side expression
     * \param lhs The expression to which assign
     */
    template<typename L>
    void assign_mod_to(L&& lhs)  const {
        std_mod_evaluate(*this, lhs);
    }

    /*!
     * \brief Print a representation of the expression on the given stream
     * \param os The output stream
     * \param expr The expression to print
     * \return the output stream
     */
    friend std::ostream& operator<<(std::ostream& os, const conv_2d_valid_expr& expr) {
        return os << "conv2_valid(" << expr._a << ", " << expr._b << ")";
    }
};

/*!
 * \brief Traits for a transpose expression
 * \tparam A The transposed sub type
 */
template <typename A, typename B, size_t S1, size_t S2, size_t P1, size_t P2, bool Flipped>
struct etl_traits<etl::conv_2d_valid_expr<A, B, S1, S2, P1, P2, Flipped>> {
    using expr_t       = etl::conv_2d_valid_expr<A, B, S1, S2, P1, P2, Flipped>; ///< The expression type
    using left_expr_t  = std::decay_t<A>;                                       ///< The left sub expression type
    using right_expr_t = std::decay_t<B>;                                       ///< The right sub expression type
    using left_traits  = etl_traits<left_expr_t>;                               ///< The left sub traits
    using right_traits = etl_traits<right_expr_t>;                              ///< The right sub traits
    using value_type   = value_t<A>;                                            ///< The value type of the expression

    static constexpr bool is_etl          = true;                       ///< Indicates if the type is an ETL expression
    static constexpr bool is_transformer  = false;                      ///< Indicates if the type is a transformer
    static constexpr bool is_view         = false;                      ///< Indicates if the type is a view
    static constexpr bool is_magic_view   = false;                      ///< Indicates if the type is a magic view
    static constexpr bool is_fast         = all_fast<A, B>::value;      ///< Indicates if the expression is fast
    static constexpr bool is_linear       = true;                       ///< Indicates if the expression is linear
    static constexpr bool is_thread_safe  = true;                       ///< Indicates if the expression is thread safe
    static constexpr bool is_value        = false;                      ///< Indicates if the expression is of value type
    static constexpr bool is_direct       = true;                       ///< Indicates if the expression has direct memory access
    static constexpr bool is_generator    = false;                      ///< Indicates if the expression is a generator
    static constexpr bool is_padded       = false;                      ///< Indicates if the expression is padded
    static constexpr bool is_aligned      = true;                       ///< Indicates if the expression is padded
    static constexpr bool is_gpu          = false;                      ///< Indicates if the expression can be done on GPU
    static constexpr bool needs_evaluator = true;                       ///< Indicates if the expression needs a evaluator visitor
    static constexpr order storage_order  = left_traits::storage_order; ///< The expression's storage order

    /*!
     * \brief Indicates if the expression is vectorizable using the
     * given vector mode
     * \tparam V The vector mode
     */
    template <vector_mode_t V>
    using vectorizable = std::true_type;

    /*!
     * \brief Returns the DDth dimension of the expression
     * \return the DDth dimension of the expression
     */
    template <size_t DD>
    static constexpr size_t dim() {
        return DD == 0 ? (etl::dim<0, A>() - etl::dim<0, B>() + 2 * P1) / S1 + 1
                       : (etl::dim<1, A>() - etl::dim<1, B>() + 2 * P2) / S2 + 1;
    }

    /*!
     * \brief Returns the dth dimension of the expression
     * \param e The sub expression
     * \param d The dimension to get
     * \return the dth dimension of the expression
     */
    static size_t dim(const expr_t& e, size_t d) {
        if (d == 0){
            return (etl::dim(e._a, 0) - etl::dim(e._b, 0) + 2 * P1) / S1 + 1;
        } else {
            return (etl::dim(e._a, 1) - etl::dim(e._b, 1) + 2 * P2) / S2 + 1;
        }
    }

    /*!
     * \brief Returns the size of the expression
     * \param e The sub expression
     * \return the size of the expression
     */
    static size_t size(const expr_t& e) {
        return ((etl::dim(e._a, 0) - etl::dim(e._b, 0) + 2 * P1) / S1 + 1)
            *  ((etl::dim(e._a, 1) - etl::dim(e._b, 1) + 2 * P2) / S2 + 1);
    }

    /*!
     * \brief Returns the size of the expression
     * \return the size of the expression
     */
    static constexpr size_t size() {
        return  ((etl::dim<0, A>() - etl::dim<0, B>() + 2 * P1) / S1 + 1)
              * ((etl::dim<1, A>() - etl::dim<1, B>() + 2 * P2) / S2 + 1);
    }

    /*!
     * \brief Returns the number of dimensions of the expression
     * \return the number of dimensions of the expression
     */
    static constexpr size_t dimensions() {
        return 2;
    }
};

/*!
 * \brief Creates an expression representing the 'valid' 1D convolution of a and b.
 *
 * \param a The input expression
 * \param b The kernel expression
 *
 * \return an expression representing the 'valid' 1D convolution of a and b
 */
template <size_t S1 = 1, size_t S2 = 1, size_t P1 = 0, size_t P2 = 0, typename A, typename B>
conv_2d_valid_expr<detail::build_type<A>, detail::build_type<B>, S1, S2, P1, P2, false> conv_2d_valid(A&& a, B&& b) {
    static_assert(all_etl_expr<A, B>::value, "Convolution only supported for ETL expressions");

    return conv_2d_valid_expr<detail::build_type<A>, detail::build_type<B>, S1, S2, P1, P2, false>{a, b};
}

/*!
 * \brief Creates an expression representing the 'valid' 1D convolution of a and b, the result will be stored in c
 *
 * \param a The input expression
 * \param b The kernel expression
 * \param c The result
 *
 * \return an expression representing the 'valid' 1D convolution of a and b
 */
template <size_t S1 = 1, size_t S2 = 1, size_t P1 = 0, size_t P2 = 0, typename A, typename B, typename C>
auto conv_2d_valid(A&& a, B&& b, C&& c){
    static_assert(all_etl_expr<A, B, C>::value, "Convolution only supported for ETL expressions");

    c = conv_2d_valid<S1, S2, P1, P2>(a, b);

    return c;
}

/*!
 * \brief Creates an expression representing the 'valid' 1D convolution of a and flipped b.
 *
 * \param a The input expression
 * \param b The kernel expression
 *
 * \return an expression representing the 'valid' 1D convolution of a and b
 */
template <size_t S1 = 1, size_t S2 = 1, size_t P1 = 0, size_t P2 = 0, typename A, typename B>
conv_2d_valid_expr<detail::build_type<A>, detail::build_type<B>, S1, S2, P1, P2, true> conv_2d_valid_flipped(A&& a, B&& b) {
    static_assert(all_etl_expr<A, B>::value, "Convolution only supported for ETL expressions");

    return conv_2d_valid_expr<detail::build_type<A>, detail::build_type<B>, S1, S2, P1, P2, true>{a, b};
}

/*!
 * \brief Creates an expression representing the 'valid' 1D convolution of a and flipped b, the result will be stored in c
 *
 * \param a The input expression
 * \param b The kernel expression
 * \param c The result
 *
 * \return an expression representing the 'valid' 1D convolution of a and b
 */
template <size_t S1 = 1, size_t S2 = 1, size_t P1 = 0, size_t P2 = 0, typename A, typename B, typename C>
auto conv_2d_valid_flipped(A&& a, B&& b, C&& c){
    static_assert(all_etl_expr<A, B, C>::value, "Convolution only supported for ETL expressions");

    c = conv_2d_valid_flipped<S1, S2, P1, P2>(a, b);

    return c;
}

} //end of namespace etl
<|endoftext|>


<commit_before>/*
    SWARM

    Copyright (C) 2012-2022 Torbjorn Rognes and Frederic Mahe

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program 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 Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    Contact: Torbjorn Rognes <torognes@ifi.uio.no>,
    Department of Informatics, University of Oslo,
    PO Box 1080 Blindern, NO-0316 Oslo, Norway
*/

#include "swarm.h"
#include "util.h"

unsigned char * score_matrix_8 {nullptr};
unsigned short * score_matrix_16 {nullptr};
int64_t * score_matrix_63 {nullptr};

void score_matrix_read(struct Parameters const & p)
{
  constexpr int n_cells {32};  // number of chars in sym_nt
  constexpr long long int one_thousand {1000};
  long long int sc {0};
  long long int hi {-one_thousand};
  long long int lo {one_thousand};

  score_matrix_8 = static_cast<unsigned char *>(xmalloc(n_cells * n_cells * sizeof(char)));
  score_matrix_16 = static_cast<unsigned short *>(xmalloc(n_cells * n_cells * sizeof(short)));
  score_matrix_63 = static_cast<int64_t *>(xmalloc(n_cells * n_cells * sizeof(int64_t)));

  for(auto a = 0; a < n_cells / 2; a++) {
    for(auto b = 0; b < n_cells / 2; b++) {
      sc = ((a == b) && (a > 0) && (b > 0)) ? 0 : p.penalty_mismatch;
      // sc = (a==b) ? matchscore : mismatchscore;
      if (sc < lo) {
        lo = sc;
      }
      if (sc > hi) {
        hi = sc;
      }
      score_matrix_63[(a * n_cells) + b] = sc;
    }
  }

  for(auto a = 0; a < n_cells; a++) {
    for(auto b = 0; b < n_cells; b++) {
      sc = score_matrix_63[(a * n_cells) + b];
      score_matrix_8[(a * n_cells) + b] = static_cast<unsigned char>(sc);
      score_matrix_16[(a * n_cells) + b] = static_cast<unsigned short>(sc);
    }
  }
}

void score_matrix_free()
{
  xfree(score_matrix_8);
  score_matrix_8 = nullptr;
  xfree(score_matrix_16);
  score_matrix_16 = nullptr;
  xfree(score_matrix_63);
  score_matrix_63 = nullptr;
}
<commit_msg>use new and delete rather than malloc and free<commit_after>/*
    SWARM

    Copyright (C) 2012-2022 Torbjorn Rognes and Frederic Mahe

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program 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 Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    Contact: Torbjorn Rognes <torognes@ifi.uio.no>,
    Department of Informatics, University of Oslo,
    PO Box 1080 Blindern, NO-0316 Oslo, Norway
*/

#include "swarm.h"
#include "util.h"

unsigned char * score_matrix_8 {nullptr};
unsigned short * score_matrix_16 {nullptr};
int64_t * score_matrix_63 {nullptr};

void score_matrix_read(struct Parameters const & p)
{
  constexpr int n_cells {32};  // number of chars in sym_nt
  constexpr long long int one_thousand {1000};
  long long int sc {0};
  long long int hi {-one_thousand};
  long long int lo {one_thousand};

  score_matrix_8 = new unsigned char[n_cells * n_cells];
  score_matrix_16 = new unsigned short[n_cells * n_cells];
  score_matrix_63 = new int64_t[n_cells * n_cells];

  for(auto a = 0; a < n_cells / 2; a++) {
    for(auto b = 0; b < n_cells / 2; b++) {
      sc = ((a == b) && (a > 0) && (b > 0)) ? 0 : p.penalty_mismatch;
      // sc = (a==b) ? matchscore : mismatchscore;
      if (sc < lo) {
        lo = sc;
      }
      if (sc > hi) {
        hi = sc;
      }
      score_matrix_63[(a * n_cells) + b] = sc;
    }
  }

  for(auto a = 0; a < n_cells; a++) {
    for(auto b = 0; b < n_cells; b++) {
      sc = score_matrix_63[(a * n_cells) + b];
      score_matrix_8[(a * n_cells) + b] = static_cast<unsigned char>(sc);
      score_matrix_16[(a * n_cells) + b] = static_cast<unsigned short>(sc);
    }
  }
}

void score_matrix_free()
{
  delete [] score_matrix_8;
  score_matrix_8 = nullptr;
  delete [] score_matrix_16;
  score_matrix_16 = nullptr;
  delete [] score_matrix_63;
  score_matrix_63 = nullptr;
}
<|endoftext|>


<commit_before>#include "helloworld.h"

using namespace samp;

static HelloWorld theGameMode;

void HelloWorld::OnGameModeInit() {
    SetGameModeText("Hello, World!");

    AddPlayerClass(0, 1958.3783f, 1343.1572f, 15.3746f, 269.1425f, 0, 0, 0, 0, 0, 0);

    logprintf("------------------------------------------\n");
    logprintf("      HelloWorld gamemode got loaded.     \n");
    logprintf("------------------------------------------\n");
}

bool HelloWorld::OnPlayerConnect(int playerid) {
    SendClientMessage(playerid, 0xFFFFFFFF, "Welcome to the HelloWorld server!");
    return true;
}

bool HelloWorld::OnPlayerRequestClass(int playerid) {
    SetPlayerPos(playerid, 1958.3783f, 1343.1572f, 15.3746f);
    SetPlayerCameraPos(playerid, 1958.3783f, 1343.1572f, 15.3746f);
    SetPlayerCameraLookAt(playerid, 1958.3783f, 1343.1572f, 15.3746f);
    return true;
}

bool HelloWorld::OnPlayerCommandText(int playerid, const std::string &cmdtext) {
    // Define a command in a "classic" way.
    // Most likely you will want to do this more efficiently, e.g. with a hash map.
    if (cmdtext == "/hello") {
        SendClientMessage(playerid, 0x00FF00FF, "Hello, " + GetPlayerName(playerid) + "!");
        return true;
    }
    return false;
}

PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports()  {
    return SUPPORTS_VERSION;
}

PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppPluginData)  {
    // This always must be called first
    Wrapper::GetInstance()->Initialize(ppPluginData);
    // Set our gamemode as the main event handler
    EventHandler::SetEventHandler(&::theGameMode);
    return true;
}

PLUGIN_EXPORT void PLUGIN_CALL Unload() {
    return;
}
<commit_msg>missing classid<commit_after>#include "helloworld.h"

using namespace samp;

static HelloWorld theGameMode;

void HelloWorld::OnGameModeInit() {
    SetGameModeText("Hello, World!");

    AddPlayerClass(0, 1958.3783f, 1343.1572f, 15.3746f, 269.1425f, 0, 0, 0, 0, 0, 0);

    logprintf("------------------------------------------\n");
    logprintf("      HelloWorld gamemode got loaded.     \n");
    logprintf("------------------------------------------\n");
}

bool HelloWorld::OnPlayerConnect(int playerid) {
    SendClientMessage(playerid, 0xFFFFFFFF, "Welcome to the HelloWorld server!");
    return true;
}

bool HelloWorld::OnPlayerRequestClass(int playerid, int classid) {
    SetPlayerPos(playerid, 1958.3783f, 1343.1572f, 15.3746f);
    SetPlayerCameraPos(playerid, 1958.3783f, 1343.1572f, 15.3746f);
    SetPlayerCameraLookAt(playerid, 1958.3783f, 1343.1572f, 15.3746f);
    return true;
}

bool HelloWorld::OnPlayerCommandText(int playerid, const std::string &cmdtext) {
    // Define a command in a "classic" way.
    // Most likely you will want to do this more efficiently, e.g. with a hash map.
    if (cmdtext == "/hello") {
        SendClientMessage(playerid, 0x00FF00FF, "Hello, " + GetPlayerName(playerid) + "!");
        return true;
    }
    return false;
}

PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports()  {
    return SUPPORTS_VERSION;
}

PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppPluginData)  {
    // This always must be called first
    Wrapper::GetInstance()->Initialize(ppPluginData);
    // Set our gamemode as the main event handler
    EventHandler::SetEventHandler(&::theGameMode);
    return true;
}

PLUGIN_EXPORT void PLUGIN_CALL Unload() {
    return;
}
<|endoftext|>


<commit_before>

// This file contains definition of C++ new/delete operators

#include <stddef.h>
#include <malloc.h>
#include "stdexcept.h"

namespace std {
    void terminate();
}

typedef void (*new_handler)();
static new_handler new_handl = &std::terminate;

namespace std {
    new_handler set_new_handler(new_handler handl) {
        new_handler old = new_handl;
        new_handl = handl;
        return old;
    }
}

__attribute__((weak))
void * operator new(size_t size) {

    void * mem = malloc(size);
    while(mem == NULL) {
        if(new_handl != NULL) {
            new_handl();
        } else {
            throw std::bad_alloc();
        }
        mem = malloc(size);
    }

    return mem;
}

__attribute__((weak))
void operator delete(void * ptr) {
    free(ptr);
}

__attribute__((weak))
void * operator new[](size_t size) {
    return ::operator new(size);
}

__attribute__((weak))
void operator delete[](void * ptr) {
    ::operator delete(ptr);
}

<commit_msg>nothrow operator new was implemented (fix for COMPILER-8913)<commit_after>

// This file contains definition of C++ new/delete operators

#include <stddef.h>
#include <malloc.h>
#include "stdexcept.h"

namespace std {
    void terminate();
}

typedef void (*new_handler)();
static new_handler new_handl = &std::terminate;

namespace std {
    new_handler set_new_handler(new_handler handl) {
        new_handler old = new_handl;
        new_handl = handl;
        return old;
    }
}

__attribute__((weak))
void * operator new(size_t size) {

    void * mem = malloc(size);
    while(mem == NULL) {
        if(new_handl != NULL) {
            new_handl();
        } else {
            throw std::bad_alloc();
        }
        mem = malloc(size);
    }

    return mem;
}

namespace std {
    struct nothrow_t {};
}

__attribute__((weak))
void * operator new(size_t size, const std::nothrow_t &) throw() {

    void * mem = malloc(size);
    while(mem == NULL) {
        if(new_handl != NULL) {
            new_handl();
        } else {
            return NULL;
        }
        mem = malloc(size);
    }

    return mem;
}

__attribute__((weak))
void operator delete(void * ptr) {
    free(ptr);
}

__attribute__((weak))
void * operator new[](size_t size) {
    return ::operator new(size);
}

__attribute__((weak))
void operator delete[](void * ptr) {
    ::operator delete(ptr);
}

<|endoftext|>