repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
---|---|---|
notjosh/NTJBilateralCIFilter | NTJBilateralCIFilteriOSDemo/ViewController.h | <reponame>notjosh/NTJBilateralCIFilter<filename>NTJBilateralCIFilteriOSDemo/ViewController.h
//
// ViewController.h
// NTJBilateralCIFilteriOSDemo
//
// Created by <NAME> on 17/10/17.
// Copyright © 2017 nojo inc. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
|
notjosh/NTJBilateralCIFilter | NTJBilateralCIFilterDemo/ViewController.h | <filename>NTJBilateralCIFilterDemo/ViewController.h
//
// ViewController.h
// NTJBilateralCIFilterDemo
//
// Created by <NAME> on 6/06/2016.
// Copyright © 2016 nojo inc. All rights reserved.
//
#import <Cocoa/Cocoa.h>
@interface ViewController : NSViewController
@end
|
lahoising/MobRend | include/mobrend/texture.h | #ifndef _MR_TEXTURE_H_
#define _MR_TEXTURE_H_
#include <inttypes.h>
#include <unordered_map>
#include <mobrend/asset_manager.h>
#include <mobrend/image_loader.h>
namespace mr
{
class Texture
{
public:
enum Format
{
TEXTURE_FORMAT_RGB,
TEXTURE_FORMAT_RGBA,
TEXTURE_FORMAT_DEPTH,
TEXTURE_FORMAT_DEPTH_STENCIL
};
enum Type
{
TEXTURE_TYPE_2D,
TEXTURE_TYPE_CUBE,
};
struct Specs
{
ImageData info;
const void *content;
Format format;
};
struct CubeSpecs
{
Specs right;
Specs left;
Specs top;
Specs bottom;
Specs front;
Specs back;
};
struct CreateParams
{
union
{
const Specs *specs;
const CubeSpecs *cubeSpecs;
};
std::string referenceName;
Type type;
CreateParams() :
specs(nullptr), referenceName(""), type(TEXTURE_TYPE_2D)
{}
};
struct CubePaths
{
char right[MR_MAX_PATH];
char left[MR_MAX_PATH];
char top[MR_MAX_PATH];
char bottom[MR_MAX_PATH];
char front[MR_MAX_PATH];
char back[MR_MAX_PATH];
};
struct LoadParams
{
union
{
const char *filepath;
const CubePaths *cubeMapPaths;
};
Type type;
bool invertVertically;
LoadParams() :
filepath(nullptr), type(TEXTURE_TYPE_2D),
invertVertically(true)
{}
};
public:
static Texture *Load(const LoadParams ¶ms);
static Texture *Create(const CreateParams ¶ms);
virtual ~Texture() = 0;
virtual void Bind() = 0;
virtual void Unbind() = 0;
uint32_t GetWidth(){ return this->w; }
uint32_t GetHeight(){ return this->h; }
protected:
uint32_t w, h;
};
class TextureManager
{
public:
static TextureManager &GetInstance();
~TextureManager();
inline void AddTexture(const char *filepath, Texture *texture)
{
this->loadedTextures[filepath] = texture;
}
inline Texture *GetTexture(const char *filepath)
{
return this->loadedTextures[filepath];
}
bool Contains(const char *filepath);
private:
TextureManager();
private:
std::unordered_map<std::string,Texture*> loadedTextures;
};
} // namespace mr
#endif
|
lahoising/MobRend | include/mobrend/opengl/vertex_buffer.h | #ifndef _MR_GL_VERTEX_BUFFER_H_
#define _MR_GL_VERTEX_BUFFER_H_
#include <mobrend/vertex_buffer.h>
#include <mobrend/vertex_layout.h>
namespace mr
{
class GlVertexBuffer : public VertexBuffer
{
public:
GlVertexBuffer(VertexBuffer::CreateParams ¶ms);
virtual ~GlVertexBuffer() override;
virtual void Bind() const override;
virtual void Unbind() const override;
private:
static unsigned int GetAttribType(AttributeType attributeType);
private:
unsigned int vao;
unsigned int bufferId;
};
} // namespace mr
#endif
|
lahoising/MobRend | include/mobrend/shader.h | <gh_stars>0
#ifndef _MR_SHADER_H_
#define _MR_SHADER_H_
#include <glm/glm.hpp>
#include <mobrend/asset_manager.h>
namespace mr
{
class Texture;
class UniformBuffer;
class Shader
{
public:
typedef struct create_params_s
{
char vertFilePath[MR_MAX_PATH];
char fragFilePath[MR_MAX_PATH];
char geomFilePath[MR_MAX_PATH];
create_params_s()
: vertFilePath(""),
fragFilePath(""),
geomFilePath("")
{}
} CreateParams;
public:
static Shader *Create(CreateParams params);
virtual ~Shader() = 0;
virtual void Bind() = 0;
virtual void Unbind() = 0;
/// Remember to bind the shader before uploading any uniform
virtual void UploadMat3(const char *uniformName,const glm::mat3 &matrix) = 0;
virtual void UploadMat4(const char *uniformName,const glm::mat4 &matrix) = 0;
virtual void UploadFloat(const char *uniformName, float val) = 0;
virtual void UploadVec3(const char *uniformName,const glm::vec3 &vec) = 0;
virtual void UploadVec4(const char *uniformName,const glm::vec4 &vec) = 0;
virtual void UploadInt(const char *uniformName, int32_t i) = 0;
virtual void UploadBool(const char *uniformName, bool val) = 0;
virtual void UploadTexture(const char *uniformName, Texture *texture) = 0;
virtual void UploadUniformBuffer(const char *uniformBufferName, UniformBuffer *ubo) = 0;
};
} // namespace mr
#endif
|
lahoising/MobRend | include/mobrend/opengl/renderer.h | <gh_stars>0
#ifndef _MR_GL_RENDERER_H_
#define _MR_GL_RENDERER_H_
#ifdef MOBREND_GL_RENDERING
#include <glad/glad.h>
#include <mobrend/renderer.h>
#include <mobrend/vertex_layout.h>
namespace mr
{
class GlRenderer : public Renderer
{
public:
GlRenderer();
virtual ~GlRenderer() override;
virtual void Clear() override;
virtual void SetViewport(int x, int y, int width, int height) override;
virtual void OnRenderBegin() override;
virtual void OnRenderEnd() override;
virtual Renderer::gui_init_info_s *GetGuiInitInfo() override;
virtual void DeleteGuiInitInfo(Renderer::gui_init_info_s *info) override;
virtual void Render(Renderer::Command &cmd) override;
virtual void EnableRenderPass(RenderPassMask renderPassMask, bool enable) override;
virtual void EnableFeatures(RendererFeatureMask mask, bool enable) override;
virtual void SetDepthTestFn(RenderPassFn fn) override;
void SetDepthMask(bool writeable) override;
virtual void SetStencilTestFn(RenderPassFn fn, int refValue, unsigned int mask) override;
virtual void SetStencilTestAction(
StencilAction stencilFailAction,
StencilAction depthFailAction,
StencilAction bothPass) override;
virtual void SetStencilMask(uint32_t mask) override;
virtual void SetBlendFn(BlendFn srcFactor, BlendFn dstFactor) override;
virtual void SetCullFace(CullFace cullFace) override;
virtual void SetFrontFaceWinding(FrontFaceWinding winding) override;
private:
static GLenum GetTopology(TopologyType type);
static GLenum GetRendererFeature(RendererFeature feature);
static GLenum GetRenderPass(RenderPass pass);
static GLenum GetRenderPassFn(RenderPassFn fn);
static GLenum GetStencilAction(StencilAction action);
static GLenum GetBlendFn(BlendFn fn);
static GLenum GetCullFace(CullFace cullFace);
static GLenum GetWinding(FrontFaceWinding winding);
};
} // namespace mr
#endif
#endif
|
lahoising/MobRend | include/mobrend/uniform_buffer.h | <reponame>lahoising/MobRend
#ifndef _MR_UNIFORM_BUFFER_H_
#define _MR_UNIFORM_BUFFER_H_
#include <inttypes.h>
#include <mobrend/buffer.h>
namespace mr
{
class UniformBuffer : public Buffer
{
public:
struct CreateParams
{
uint32_t bufferSize;
uint32_t binding;
};
public:
static UniformBuffer *Create(const CreateParams ¶ms);
virtual ~UniformBuffer() = 0;
virtual void Bind() const = 0;
virtual void Unbind() const = 0;
virtual void SetData(const void *data, uint32_t size, uint32_t offset) = 0;
};
} // namespace mr
#endif
|
lahoising/MobRend | include/mobrend/framebuffer.h | <reponame>lahoising/MobRend
#ifndef _MR_FRAMEBUFFER_H_
#define _MR_FRAMEBUFFER_H_
#include <vector>
#include <mobrend/texture.h>
namespace mr
{
enum FramebufferUsage
{
FRAMEBUFFER_USAGE_READ_WRITE,
FRAMEBUFFER_USAGE_READ,
FRAMEBUFFER_USAGE_WRITE
};
class Framebuffer
{
public:
enum AttachmentType
{
ATTACHMENT_COLOR_0,
ATTACHMENT_DEPTH,
ATTACHMENT_DEPTH24_STENCIL8,
};
struct Attachment
{
AttachmentType type;
bool isRenderbufferObject;
};
struct CreateParams
{
std::vector<Attachment> attachments;
uint32_t width, height;
};
public:
static Framebuffer *Create(CreateParams &createParams);
virtual ~Framebuffer() = 0;
virtual void Bind(FramebufferUsage usage) = 0;
virtual void Unbind(FramebufferUsage usage) = 0;
virtual void Clear(FramebufferUsage usage) = 0;
virtual Texture *GetTextureAttachment(uint32_t index) = 0;
};
} // namespace mr
#endif
|
lahoising/MobRend | include/mobrend/asset_manager.h | #ifndef _MR_ASSET_MANAGER_H_
#define _MR_ASSET_MANAGER_H_
#include <vector>
#include <cstring>
#include <string>
#include <inttypes.h>
#define MR_MAX_PATH 260
namespace mr
{
class AssetManager
{
public:
~AssetManager(){}
/// TODO: replace std::vector<char> to a data type that doesn't allocate in heap
std::vector<char> GetFileContent(const char *filepath);
std::vector<uint32_t> GetFileContentInBinary(const char *filePath);
inline static void GetAssetPath(char *dst, const char *path)
{
snprintf(dst, MR_MAX_PATH, "%s/%s", MOBREND_ASSETS_RELATIVE_PATH, path);
}
private:
AssetManager(){}
FILE *OpenFile(const char *filepath, long &outSize);
public:
static AssetManager &GetInstance()
{
static AssetManager manager = AssetManager();
return manager;
}
};
} // namespace mr
#endif |
lahoising/MobRend | include/mobrend/glfw/window.h | <reponame>lahoising/MobRend<gh_stars>0
#ifndef _MR_GLFW_WINDOW_H_
#define _MR_GLFW_WINDOW_H_
#ifdef MOBREND_GLFW_WINDOW
#define GLFW_INCLUDE_NONE
#include "GLFW/glfw3.h"
#include <mobrend/window.h>
namespace mr
{
class GlfwWindow : public Window
{
public:
GlfwWindow(Window::CreateParams createParams);
virtual ~GlfwWindow() override;
virtual void SwapBuffers() override;
virtual void PollEvents() override;
virtual void SetCursorVisible(bool visible) override;
virtual void *GetHandle() override { return this->window; }
virtual uint32_t GetWidth() override;
virtual uint32_t GetHeight() override;
virtual uint32_t GetFramebufferWidth() override;
virtual uint32_t GetFramebufferHeight() override;
GLFWwindow *GetWindow() { return this->window; }
private:
GLFWwindow *window;
};
} // namespace mr
#endif
#endif
|
lahoising/MobRend | include/mobrend/index_buffer.h | <reponame>lahoising/MobRend
#ifndef _MR_INDEX_BUFFER_H_
#define _MR_INDEX_BUFFER_H_
#include <inttypes.h>
#include <mobrend/buffer.h>
namespace mr
{
class IndexBuffer : public Buffer
{
public:
typedef struct
{
const uint32_t *data;
uint32_t elementCount;
} CreateParams;
public:
static IndexBuffer *Create(CreateParams ¶ms);
virtual ~IndexBuffer() = 0;
virtual void Bind() const = 0;
virtual void Unbind() const = 0;
uint32_t GetElementCount() const { return this->elementCount; }
protected:
uint32_t elementCount;
};
} // namespace mr
#endif
|
lahoising/MobRend | include/mobrend/opengl/index_buffer.h | <filename>include/mobrend/opengl/index_buffer.h
#ifndef _MR_GL_INDEX_BUFFER_H_
#define _MR_GL_INDEX_BUFFER_H_
#include <mobrend/index_buffer.h>
namespace mr
{
class GlIndexBuffer : public IndexBuffer
{
public:
GlIndexBuffer(IndexBuffer::CreateParams ¶ms);
virtual ~GlIndexBuffer() override;
virtual void Bind() const override;
virtual void Unbind() const override;
private:
unsigned int bufferId;
};
} // namespace mr
#endif
|
lahoising/MobRend | include/mobrend/model.h | #ifndef _MR_MODEL_H_
#define _MR_MODEL_H_
#include <vector>
#include <string>
#include <mobrend/mesh.h>
namespace mr
{
class Model
{
public:
static Model *Load(const char *filepath);
Model();
Model(const std::vector<Mesh*> &meshes);
~Model();
const std::vector<Mesh*> &GetMeshes(){ return this->meshes; };
private:
std::vector<Mesh*> meshes;
};
} // namespace mr
#endif
|
lahoising/MobRend | include/mobrend/opengl/uniform_buffer.h | #ifndef _MR_GL_UNIFORM_BUFFER_H_
#define _MR_GL_UNIFORM_BUFFER_H_
#include <mobrend/uniform_buffer.h>
namespace mr
{
class GlUniformBuffer : public UniformBuffer
{
public:
GlUniformBuffer(const UniformBuffer::CreateParams ¶ms);
virtual ~GlUniformBuffer() override;
virtual void Bind() const override;
virtual void Unbind() const override;
virtual void SetData(const void *data, uint32_t size, uint32_t offset) override;
unsigned int GetBufferId(){ return this->bufferId; }
uint32_t GetBinding(){ return this->binding; }
private:
unsigned int bufferId;
uint32_t binding;
};
} // namespace mr
#endif
|
lahoising/MobRend | include/mobrend/observer_camera.h | <reponame>lahoising/MobRend
#ifndef _MR_OBSERVER_CAMERA_H_
#define _MR_OBSERVER_CAMERA_H_
#include <glm/glm.hpp>
#include <mobrend/camera.h>
namespace mr
{
class ObserverCamera
{
public:
ObserverCamera()
: camera(Camera()), focusPoint(glm::vec3(0.0f, 0.0f, 0.0f)) {}
void Update();
void SetFocusPoint(glm::vec3 point);
Camera camera;
private:
glm::vec3 focusPoint;
};
} // namespace mr
#endif
|
lahoising/MobRend | include/mobrend/gui.h | #ifndef _MR_GUI_H_
#define _MR_GUI_H_
#include <mobrend/renderer.h>
namespace mr
{
class Gui
{
public:
typedef struct
{
void *windowHandle;
struct Renderer::gui_init_info_s *rendererInitInfo;
} CreateParams;
public:
Gui(CreateParams params);
~Gui();
void BeginFrame();
void EndFrame();
};
} // namespace mr
#endif
|
lahoising/MobRend | include/mobrend/camera.h | <gh_stars>0
#ifndef _MR_CAMERA_H_
#define _MR_CAMERA_H_
#include <glm/glm.hpp>
#include <glm/gtc/quaternion.hpp>
namespace mr
{
class Camera
{
public:
enum Type : int
{
PERSPECTIVE,
ORTHOGRAPHIC
};
typedef struct
{
float fov;
float aspectRatio;
float near, far;
} PerspectiveConfig;
typedef struct
{
float size;
float aspectRatio;
float near, far;
} OrthographicConfig;
union Config
{
PerspectiveConfig perspective;
OrthographicConfig ortho;
};
public:
Camera(Type type, Config config);
Camera() : Camera(
Type::PERSPECTIVE,
{{60.0f, 16.0f/9.0f, 0.1f, 100.0f}}){}
void SetConfiguration(Type type, Config config);
const glm::mat4 &GetViewProjection() const { return this->viewProjMat; }
const glm::mat4 &GetViewMatrix() const { return this->viewMatrix; }
const glm::mat4 &GetProjectionMatrix() const { return this->projMatrix; }
const glm::vec3 &GetPosition() const { return this->position; }
void SetPosition(const glm::vec3 &position);
const glm::quat &GetRotation() const { return this->rotation; }
void SetRotation(const glm::quat &rotation);
private:
void SetPerspective(PerspectiveConfig config);
void SetOrtho(OrthographicConfig config);
void RecalculateViewMatrix();
inline void RecalculateViewProjection(){ this->viewProjMat = this->projMatrix * this->viewMatrix; }
private:
glm::mat4 viewMatrix;
glm::mat4 projMatrix;
glm::mat4 viewProjMat;
glm::quat rotation;
glm::vec3 position;
Type type;
};
} // namespace mr
#endif |
lahoising/MobRend | include/mobrend/image_loader.h | #ifndef _MR_IMAGE_LOADER_H_
#define _MR_IMAGE_LOADER_H_
namespace mr
{
typedef struct
{
int width, height;
int nrChannels;
} ImageData;
class ImageLoader
{
public:
static unsigned char *Load(const char *filepath, ImageData *dataOutput, bool inverted = true);
static void DeleteImage(unsigned char *imageData);
};
} // namespace mr
#endif |
lahoising/MobRend | include/mobrend/opengl/texture.h | #ifndef _MR_GL_TEXTURE_H_
#define _MR_GL_TEXTURE_H_
#include <mobrend/image_loader.h>
#include <mobrend/texture.h>
namespace mr
{
class GlTexture : public Texture
{
public:
GlTexture(const Texture::LoadParams ¶ms);
GlTexture(const Texture::CreateParams ¶ms);
void GenerateTexture(const Texture::CreateParams ¶ms);
virtual ~GlTexture() override;
virtual void Bind() override;
virtual void Unbind() override;
unsigned int GetTextureId(){ return this->textureId; }
private:
static unsigned int GetFormat(Texture::Format format);
static unsigned int GetInternalFormat(Texture::Format format);
static unsigned int GetContentType(Texture::Format format);
static unsigned int GetTextureType(Texture::Type type);
static Texture::Specs CreateSpecs(const char *filepath, bool invertVertically);
private:
typedef struct
{
void (*generate)(GlTexture *texture, const Texture::CreateParams ¶ms);
unsigned int type;
} GeneratorInfo;
static GeneratorInfo BuildGeneratorInfo(GlTexture::Type type);
static void Texture2D(const Texture::Specs *specs, unsigned int textureType);
static void GenerateTexture2D(GlTexture *texture, const Texture::CreateParams ¶ms);
static void GenerateTextureCube(GlTexture *texture, const Texture::CreateParams ¶ms);
private:
unsigned int textureId;
unsigned int textureType;
// unsigned char *imageContent;
};
} // namespace mr
#endif
|
lahoising/MobRend | include/mobrend/fps_camera.h | <gh_stars>0
#ifndef _MR_FPS_CAMERA_H_
#define _MR_FPS_CAMERA_H_
#include <mobrend/camera.h>
namespace mr
{
class FPSCamera
{
public:
FPSCamera() : camera(Camera()), yaw(0.0f), pitch(0.0f),
movementSpeed(0.7f), sensitivity(0.01f) {}
void Update();
public:
Camera camera;
float movementSpeed;
float sensitivity;
private:
float pitch, yaw;
};
} // namespace mr
#endif
|
lahoising/MobRend | include/mobrend/material.h | #ifndef _MR_MATERIAL_H_
#define _MR_MATERIAL_H_
namespace mr
{
class Material
{
};
} // namespace mr
#endif |
lahoising/MobRend | include/mobrend/light.h | <gh_stars>0
#ifndef _MR_LIGHT_H_
#define _MR_LIGHT_H_
#include <glm/glm.hpp>
#include <glm/gtc/quaternion.hpp>
namespace mr
{
class Shader;
/// ================== BASE LIGHT ===================
class Light
{
public:
enum Type : int
{
AMBIENT = 0,
POINT,
DIRECTIONAL,
SPOTLIGHT,
};
public:
virtual ~Light() = 0;
virtual void Bind(Shader *shader, const char *name) = 0;
Type GetType() { return this->type; }
protected:
Light(Type type, glm::vec3 color, float intensity)
: color(color), position(glm::vec3()), intensity(intensity), type(type) {}
public:
glm::vec3 color;
glm::vec3 position;
float intensity;
protected:
Type type;
};
/// ================ AMBIENT LIGHT =============
class AmbientLight : public Light
{
public:
AmbientLight(glm::vec3 color, float intensity);
virtual void Bind(Shader *shader, const char *name) override;
};
/// ================== POINT LIGHT ===================
class PointLight : public Light
{
public:
PointLight(glm::vec3 color, float intensity);
virtual void Bind(Shader *shader, const char *name) override;
public:
glm::vec3 attenuation;
};
/// ====================== DIRECTIONAL LIGHT ================
class DirectionalLight : public Light
{
public:
DirectionalLight(glm::vec3 color, float intensity);
virtual void Bind(Shader *shader, const char *name) override;
public:
glm::vec3 direction;
};
/// =========== SPOTLIGHT =============
class Spotlight : public Light
{
public:
Spotlight(glm::vec3 color, float intensity);
virtual void Bind(Shader *shader, const char *name) override;
public:
glm::quat rotation;
float innerCutoff;
float outerCutoff;
};
} // namespace mr
#endif |
lahoising/MobRend | include/mobrend/renderer.h | <filename>include/mobrend/renderer.h<gh_stars>0
#ifndef _MR_RENDERER_H_
#define _MR_RENDERER_H_
#include <inttypes.h>
namespace mr
{
class Mesh;
class Model;
enum TopologyType
{
TOPOLOGY_TRIANGLES = 0,
TOPOLOGY_WIREFRAME,
TOPOLOGY_POINTS,
};
enum RenderObjectType
{
RENDER_OBJECT_NONE = 0,
RENDER_OBJECT_MESH,
RENDER_OBJECT_MODEL
};
enum RenderPass
{
RENDER_PASS_NONE = 0,
RENDER_PASS_DEPTH = 1 << 0,
RENDER_PASS_STENCIL = 1 << 1,
// the following might not be render passes
RENDER_PASS_BLEND = 1 << 2,
RENDER_PASS_CULLING = 1 << 3,
};
enum RendererFeature
{
RENDERER_FEATURE_SHADER_POINT_SIZE = 1 << 0
};
enum RenderPassFn
{
RENDER_PASS_FN_ALWAYS,
RENDER_PASS_FN_NEVER,
RENDER_PASS_FN_LESS,
RENDER_PASS_FN_EQUAL,
RENDER_PASS_FN_LESS_OR_EQUEAL,
RENDER_PASS_FN_GREATER,
RENDER_PASS_FN_NOT_EQUAL,
RENDER_PASS_FN_GREATER_OR_EQUAL,
};
enum StencilAction
{
STENCIL_ACTION_KEEP,
STENCIL_ACTION_ZERO,
STENCIL_ACTION_REPLACE,
STENCIL_ACTION_INCREASE,
STENCIL_ACTION_INCREASE_WRAP,
STENCIL_ACTION_DECREASE,
STENCIL_ACTION_DECREASE_WRAP,
STENCIL_ACTION_INVERT,
};
enum BlendFn
{
BLEND_FN_ZERO,
BLEND_FN_ONE,
BLEND_FN_SRC_COLOR,
BLEND_FN_ONE_MINUS_SRC_COLOR,
BLEND_FN_DST_COLOR,
BLEND_FN_ONE_MINUS_DST_COLOR,
BLEND_FN_SRC_ALPHA,
BLEND_FN_ONE_MINUS_SRC_ALPHA,
BLEND_FN_DST_ALPHA,
BLEND_FN_ONE_MINUS_DST_ALPHA,
BLEND_FN_CONSTANT_COLOR,
BLEND_FN_ONE_MINUS_CONSTANT_COLOR,
BLEND_FN_CONSTANT_ALPHA,
BLEND_FN_ONE_MINUS_CONSTANT_ALPHA,
};
enum FrontFaceWinding
{
FF_WINDING_CCW,
FF_WINDING_CW,
};
enum CullFace
{
CULL_FACE_FRONT,
CULL_FACE_BACK,
CULL_FACE_FRONT_AND_BACK,
};
typedef unsigned int RenderPassMask;
typedef unsigned int RendererFeatureMask;
class Renderer
{
public:
struct gui_init_info_s;
typedef struct command_s
{
union
{
Mesh *mesh;
Model *model;
};
TopologyType topologyType;
RenderObjectType renderObjectType;
command_s()
: mesh(nullptr),
topologyType(TopologyType::TOPOLOGY_TRIANGLES),
renderObjectType(RenderObjectType::RENDER_OBJECT_NONE)
{}
} Command;
public:
static Renderer *Create();
virtual ~Renderer() = 0;
virtual void Clear() = 0;
virtual void SetViewport(int x, int y, int width, int height) = 0;
virtual void OnRenderBegin() = 0;
virtual void OnRenderEnd() = 0;
virtual gui_init_info_s *GetGuiInitInfo() = 0;
virtual void DeleteGuiInitInfo(gui_init_info_s *info) = 0;
virtual void Render(Command &cmd) = 0;
virtual void EnableRenderPass(RenderPassMask renderPassMask, bool enable) = 0;
virtual void EnableFeatures(RendererFeatureMask mask, bool enable) = 0;
virtual void SetDepthTestFn(RenderPassFn fn) = 0;
virtual void SetDepthMask(bool writeable) = 0;
virtual void SetStencilTestFn(RenderPassFn fn, int refValue, unsigned int mask) = 0;
virtual void SetStencilTestAction(
StencilAction stencilFailAction,
StencilAction depthFailAction,
StencilAction bothPass) = 0;
virtual void SetStencilMask(uint32_t mask) = 0;
virtual void SetBlendFn(BlendFn srcFactor, BlendFn dstFactor) = 0; /// TODO: research order independent transparency
virtual void SetCullFace(CullFace cullFace) = 0;
virtual void SetFrontFaceWinding(FrontFaceWinding winding) = 0;
};
} // namespace mr
#endif
|
lahoising/MobRend | include/mobrend/input_event.h | #ifndef _MR_INPUT_EVENT_H_
#define _MR_INPUT_EVENT_H_
namespace mr
{
class Window;
enum InputEventType
{
UNKNOWN = 0,
KEY_EVENT,
MOUSE_POSITION,
WINDOW_CLOSE
};
enum KeyCode
{
KEY_UNKNOWN = 0,
KEY_Q, KEY_W, KEY_E, KEY_R, KEY_T, KEY_Y, KEY_U, KEY_I, KEY_O, KEY_P,
KEY_A, KEY_S, KEY_D, KEY_F, KEY_G, KEY_H, KEY_J, KEY_K, KEY_L,
KEY_Z, KEY_X, KEY_C, KEY_V, KEY_B, KEY_N, KEY_M,
KEY_COMMA, KEY_PERIOD, KEY_SLASH, KEY_DASH, KEY_BACKSLASH, KEY_EQUALS,
KEY_LBRACKET, KEY_RBRACKET,
KEY_ESC, KEY_APOSTROPHE,
KEY_1, KEY_2, KEY_3, KEY_4, KEY_5, KEY_6, KEY_7, KEY_8, KEY_9, KEY_0,
KEY_SEMICOLON, KEY_GRAVE,
KEY_LEFT, KEY_RIGHT, KEY_UP, KEY_DOWN,
KEY_SPACE, KEY_BACKSPACE,
KEY_HOME, KEY_END, KEY_PAGE_UP, KEY_PAGE_DOWN,
KEY_CAPS_LOCK, KEY_PRINT_SCREEN, KEY_DELETE, KEY_INSERT,
KEY_NUM_LOCK,
KEY_F1, KEY_F2, KEY_F3, KEY_F4, KEY_F5, KEY_F6, KEY_F7, KEY_F8, KEY_F9,
KEY_F10, KEY_F11, KEY_F12, KEY_F13, KEY_F14, KEY_F15, KEY_F16, KEY_F17, KEY_F18, KEY_F19,
KEY_F20, KEY_F21, KEY_F22, KEY_F23, KEY_F24, KEY_F25,
KEY_TAB,
KEY_LCTRL, KEY_LSHIFT, KEY_LALT, KEY_LSUPER,
KEY_RCTRL, KEY_RSHIFT, KEY_RALT, KEY_RSUPER,
};
typedef struct
{
KeyCode key;
int pressed;
int mod;
} KeyEvent;
typedef struct
{
float x, y;
} MousePositionEvent;
typedef struct
{
Window *window;
} WindowCloseEvent;
typedef struct
{
InputEventType type;
union
{
KeyEvent keyEvent;
MousePositionEvent mousePosition;
WindowCloseEvent windowClose;
};
} InputEvent;
} // namespace mr
#endif |
lahoising/MobRend | include/mobrend/application.h | <reponame>lahoising/MobRend
#ifndef _MR_APPLICATION_H_
#define _MR_APPLICATION_H_
#include <mobrend/window.h>
#include <mobrend/renderer.h>
#include <mobrend/gui.h>
namespace mr
{
class Program
{
public:
virtual void OnStart() = 0;
virtual void OnUpdate() = 0;
virtual void OnRender(Renderer *renderer) = 0;
virtual void OnGuiRender() = 0;
virtual void OnDestroy() = 0;
};
class Application
{
public:
typedef struct
{
Program *program;
Window::CreateParams windowCreateParams;
} RunParams;
private:
typedef struct
{
Window::CreateParams windowCreateParams;
} InitParams;
public:
void Run(RunParams params);
void Close();
Window *GetMainWindow(){ return this->window; }
Renderer *GetRenderer(){ return this->renderer; }
Gui *GetGuiFramework(){ return this->gui; }
private:
Application();
~Application();
bool Init(InitParams params);
void Update();
void Render(Program *prog);
private:
bool running = false;
Window *window = nullptr;
Renderer *renderer = nullptr;
Gui *gui = nullptr;
public:
static Application &GetInstance()
{
static Application app = Application();
return app;
}
};
} // namespace mr
#endif
|
lahoising/MobRend | include/mobrend/opengl/framebuffer.h | <gh_stars>0
#ifndef _MR_GL_FRAMEBUFFER_H_
#define _MR_GL_FRAMEBUFFER_H_
#include <vector>
#include <mobrend/framebuffer.h>
#include <mobrend/opengl/texture.h>
namespace mr
{
class GlFramebuffer : public Framebuffer
{
public:
struct GlAttachment
{
union
{
unsigned int renderObjectId;
GlTexture *texture;
};
Framebuffer::AttachmentType type;
bool isRenderbufferObject;
};
public:
GlFramebuffer(Framebuffer::CreateParams &createParams);
virtual ~GlFramebuffer() override;
virtual void Bind(FramebufferUsage usage) override;
virtual void Unbind(FramebufferUsage usage) override;
virtual void Clear(FramebufferUsage usage) override;
virtual Texture *GetTextureAttachment(uint32_t index) override;
private:
GlAttachment CreateAttachment(const Framebuffer::Attachment &specifications);
private:
static unsigned int GetFramebufferUsage(mr::FramebufferUsage usage);
static unsigned int GetAttachment(mr::Framebuffer::AttachmentType attachmentType);
static unsigned int GetAttachmentInternalFormat(Framebuffer::AttachmentType attachmentType);
static unsigned int GetBufferBit(Framebuffer::AttachmentType type);
private:
unsigned int framebufferId;
uint32_t width, height;
std::vector<GlAttachment> attachments;
};
} // namespace mr
#endif
|
lahoising/MobRend | include/mobrend/buffer.h | #ifndef _MR_BUFFER_H_
#define _MR_BUFFER_H_
namespace mr
{
class Buffer
{
public:
virtual ~Buffer() = 0;
virtual void Bind() const = 0;
virtual void Unbind() const = 0;
};
} // namespace mr
#endif
|
lahoising/MobRend | include/mobrend/mesh.h | <reponame>lahoising/MobRend
#ifndef _MR_MESH_H_
#define _MR_MESH_H_
#include <unordered_map>
#include <string>
#include <mobrend/buffer.h>
#include <mobrend/vertex_layout.h>
#include <mobrend/vertex_buffer.h>
#include <mobrend/index_buffer.h>
#include <mobrend/texture.h>
namespace mr
{
class Mesh
{
public:
typedef struct
{
const VertexLayout *vertexLayout;
const void *vertices;
uint32_t verticesArraySize;
const uint32_t *indices;
uint32_t indexCount;
} CreateParams;
public:
// static Mesh *Create(CreateParams ¶ms);
Mesh(CreateParams ¶ms);
~Mesh();
const VertexBuffer *GetVertexBuffer() const;
const IndexBuffer *GetIndexBuffer() const;
protected:
VertexBuffer *vertexBuffer;
IndexBuffer *indexBuffer;
};
}
#endif
|
lahoising/MobRend | include/mobrend/input.h | <reponame>lahoising/MobRend
#ifndef _MR_INPUT_H_
#define _MR_INPUT_H_
#include <glm/glm.hpp>
#include <mobrend/input_event.h>
#define INPUT_STATE_KEY_EVENT_NUM 512
namespace mr
{
typedef struct
{
WindowCloseEvent windowClose;
KeyEvent keys[INPUT_STATE_KEY_EVENT_NUM];
MousePositionEvent mousePosition;
} InputState;
class Input
{
public:
Input();
void SwapState();
void Clear();
bool WindowShouldClose();
bool IsKeyPressed(int key);
bool KeyJustPressed(int key);
bool KeyJustReleased(int key);
glm::vec2 GetMouseDelta();
void SubmitEvent(InputEvent event);
private:
InputState currentState;
InputState prevState;
};
} // namespace mr
#endif
|
lahoising/MobRend | include/mobrend/vertex_buffer.h | <gh_stars>0
#ifndef _MR_VERTEX_BUFFER_H_
#define _MR_VERTEX_BUFFER_H_
#include <cinttypes>
#include <mobrend/buffer.h>
#include <mobrend/vertex_layout.h>
namespace mr
{
class VertexBuffer : public Buffer
{
public:
typedef struct
{
const void *data;
std::size_t bufferSize;
const VertexLayout *vertexLayout;
} CreateParams;
public:
static VertexBuffer *Create(CreateParams ¶ms);
virtual ~VertexBuffer() = 0;
virtual void Bind() const = 0;
virtual void Unbind() const = 0;
};
} // namespace mr
#endif
|
lahoising/MobRend | include/mobrend/vertex_layout.h | #ifndef _MR_VERTEX_LAYOUT_H_
#define _MR_VERTEX_LAYOUT_H_
#include <inttypes.h>
#include <vector>
// #include <initializer_list>
namespace mr
{
enum AttributeType
{
ATTRIBUTE_TYPE_FLOAT
};
typedef struct
{
AttributeType type;
uint32_t count;
} Attribute;
class VertexLayout
{
public:
VertexLayout(const std::vector<Attribute> &attributes);
VertexLayout(const std::initializer_list<Attribute> attributes);
void PushAttribute(const Attribute &attribute);
uint32_t GetStride() const { return this->stride; }
const std::vector<Attribute> &GetAttributes() const { return this->attributes; }
private:
void CalculateStride();
public:
static uint32_t GetAttributeSize(const Attribute &attrib);
private:
uint32_t stride;
std::vector<Attribute> attributes;
};
} // namespace mr
#endif |
lahoising/MobRend | include/mobrend/window.h | <filename>include/mobrend/window.h
#ifndef _MR_WINDOW_H_
#define _MR_WINDOW_H_
#include <inttypes.h>
#include <unordered_map>
#include <string>
#include <mobrend/input.h>
namespace mr
{
class Window
{
public:
static constexpr int WINDOW_NAME_MAX_LEN = 64;
typedef struct
{
uint32_t width = 800;
uint32_t height = 600;
std::string windowName = "";
} CreateParams;
public:
static Window *Create(CreateParams params);
virtual ~Window() = 0;
virtual void SwapBuffers() = 0;
virtual void PollEvents() = 0;
virtual void *GetHandle() = 0;
virtual void SetCursorVisible(bool visible) = 0;
virtual uint32_t GetWidth() = 0;
virtual uint32_t GetHeight() = 0;
virtual uint32_t GetFramebufferWidth() = 0;
virtual uint32_t GetFramebufferHeight() = 0;
public:
Input input;
};
class WindowManager
{
public:
int GetWindowCount(){ return this->windowCount; }
void AddWindow(Window *window)
{
this->windowCount++;
}
void RemoveWindow(Window *window)
{
this->windowCount--;
}
public:
static WindowManager &GetInstance()
{
static WindowManager manager = WindowManager();
return manager;
}
private:
int windowCount;
WindowManager(){ this->windowCount = 0; }
};
} // namespace mr
#endif
|
lahoising/MobRend | include/mobrend/uniform_layout.h | #ifndef _MR_UNIFORM_LAYOUT_H_
#define _MR_UNIFORM_LAYOUT_H_
#include <unordered_map>
#include <string>
namespace mr {
enum UniformType
{
UNIFORM_TYPE_BOOL,
UNIFORM_TYPE_BOOL2,
UNIFORM_TYPE_BOOL3,
UNIFORM_TYPE_BOOL4,
UNIFORM_TYPE_INT,
UNIFORM_TYPE_INT2,
UNIFORM_TYPE_INT3,
UNIFORM_TYPE_INT4,
UNIFORM_TYPE_UINT,
UNIFORM_TYPE_UINT2,
UNIFORM_TYPE_UINT3,
UNIFORM_TYPE_UINT4,
UNIFORM_TYPE_FLOAT,
UNIFORM_TYPE_VEC2,
UNIFORM_TYPE_VEC3,
UNIFORM_TYPE_VEC4,
UNIFORM_TYPE_DOUBLE,
UNIFORM_TYPE_DOUBLE2,
UNIFORM_TYPE_DOUBLE3,
UNIFORM_TYPE_DOUBLE4,
UNIFORM_TYPE_MAT2X2,
UNIFORM_TYPE_MAT2X3,
UNIFORM_TYPE_MAT2X4,
UNIFORM_TYPE_MAT3X2,
UNIFORM_TYPE_MAT3X3,
UNIFORM_TYPE_MAT3X4,
UNIFORM_TYPE_MAT4X2,
UNIFORM_TYPE_MAT4X3,
UNIFORM_TYPE_MAT4X4,
UNIFORM_TYPE_TEX1D,
UNIFORM_TYPE_TEX2D,
UNIFORM_TYPE_TEX3D,
UNIFORM_TYPE_UDSTRUCT, // user defined struct
};
typedef struct
{
UniformType type;
unsigned int count;
} UniformValue;
typedef std::unordered_map<std::string,UniformValue> UniformLayout;
UniformLayout GetUniformLayout(const char *source);
} // namespace mr
#endif
|
lahoising/MobRend | include/mobrend/opengl/shader.h | #ifndef _MR_GL_SHADER_H_
#define _MR_GL_SHADER_H_
#include <unordered_map>
#include <vector>
#include <inttypes.h>
#include <mobrend/shader.h>
namespace mr
{
class GlShader : public Shader
{
public:
GlShader(Shader::CreateParams params);
virtual ~GlShader() override;
virtual void Bind() override;
virtual void Unbind() override;
virtual void UploadMat3(const char *uniformName,const glm::mat3 &matrix) override;
virtual void UploadMat4(const char *uniformName,const glm::mat4 &matrix) override;
virtual void UploadFloat(const char *uniformName, float val) override;
virtual void UploadVec3(const char *uniformName,const glm::vec3 &vec) override;
virtual void UploadVec4(const char *uniformName,const glm::vec4 &vec) override;
virtual void UploadInt(const char *uniformName, int32_t i) override;
virtual void UploadBool(const char *uniformName, bool val) override;
virtual void UploadTexture(const char *uniformName, Texture *texture) override;
virtual void UploadUniformBuffer(const char *uniformBufferName, UniformBuffer *ubo) override;
private:
std::string CompileFromSpirV(const std::vector<uint32_t> &source);
void CompileShader(unsigned int shaderId, const char *shaderSource);
private:
unsigned int programId;
unsigned int textureSlotsCount;
std::unordered_map<unsigned int, unsigned int> textureLocationToTextureSlot;
std::unordered_map<std::string,unsigned int> uniformLocations;
};
} // namespace mr
#endif
|
tenzen-y/intel-extension-for-pytorch | torch_ipex/csrc/cpu/dbl/RNN.h | <reponame>tenzen-y/intel-extension-for-pytorch
#pragma once
#include <ATen/Tensor.h>
#include "cpu/dil/dil.hpp"
#include <vector>
namespace torch_ipex {
namespace cpu {
namespace dbl {
namespace rnn {
std::vector<at::Tensor> mkldnn_rnn_layer(const at::Tensor& input, const at::Tensor& w1, const at::Tensor& w2,
const at::Tensor& w3, const at::Tensor& w4, const at::Tensor& hx_, const at::Tensor& cx_, bool reverse, int64_t mode,
int64_t hidden_size, int64_t num_layers, bool has_biases, bool train, bool bidirectional, at::IntArrayRef batch_sizes,
const std::vector<float>& scales_from_json, const std::vector<int32_t>& shift_from_json, bool quantized);
std::vector<at::Tensor> mkldnn_rnn_layer_backward(const at::Tensor& input, const at::Tensor& w1, const at::Tensor& w2,
const at::Tensor& w3, const at::Tensor& w4, const at::Tensor& hx_, const at::Tensor& cx_, const at::Tensor& output, const at::Tensor& hy_,
const at::Tensor& cy_, const at::Tensor& grad_output, const at::Tensor& grad_hy_, const at::Tensor& grad_cy_, bool reverse, int64_t mode,
int64_t hidden_size, int64_t num_layers, bool has_biases, bool train, bool bidirectional, at::IntArrayRef batch_sizes);
} // namespace rnn
} // namespace dbl
} // namespace cpu
} // namespace torch_ipex
|
tenzen-y/intel-extension-for-pytorch | torch_ipex/csrc/cpu/CustomOPs.h | #pragma once
#include "DevOPs.h"
#include "aten/aten.hpp"
#include "dbl/Common.h"
#include "dil/dil.hpp"
#include "torch_ipex/csrc/aten_ipex_bridge.h"
#include "torch_ipex/csrc/utils.h"
#include "ShadeDataContext.h"
#include <ATen/Tensor.h>
#include <c10/util/Optional.h>
#include <torch/csrc/autograd/custom_function.h>
#include <torch/csrc/autograd/function.h>
#include <torch/csrc/autograd/variable.h>
#include <torch/script.h>
class NewLinearOp : public torch::autograd::Function<NewLinearOp> {
public:
static at::Tensor _forward(at::Tensor input, at::Tensor weight,
at::Tensor bias = at::Tensor()) {
#if defined(IPEX_PROFILE_OP)
RECORD_FUNCTION("IPEXLinearOp::_forward", std::vector<c10::IValue>({}));
#endif
try {
if (torch_ipex::check_auto_dnnl() &&
input.device().type() == c10::DeviceType::XPU) {
return torch_ipex::cpu::AtenIpexCPUDev::dil_linear(input, weight, bias);
}
} catch (std::exception &e) {
#if defined(_DEBUG)
TORCH_WARN(e.what());
#endif
}
if (input.device().type() == c10::DeviceType::XPU) {
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(input.layout() == c10::kStrided);
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(weight.layout() == c10::kStrided);
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(bias.layout() == c10::kStrided);
auto &&_ipex_input =
torch_ipex::bridge::shallowFallbackToCPUTensor(input);
auto &&_ipex_weight =
torch_ipex::bridge::shallowFallbackToCPUTensor(weight);
auto &&_ipex_bias = torch_ipex::bridge::shallowFallbackToCPUTensor(bias);
auto &&_ipex_result = at::linear(_ipex_input, _ipex_weight, _ipex_bias);
static_cast<void>(_ipex_result); // Avoid warnings in case not used
return torch_ipex::bridge::shallowUpgradeToDPCPPTensor(_ipex_result);
} else {
return at::linear(input, weight, bias);
}
}
static at::Tensor forward(torch::autograd::AutogradContext *ctx,
at::Tensor input, at::Tensor weight,
at::Tensor bias = at::Tensor()) {
#if defined(IPEX_PROFILE_OP)
RECORD_FUNCTION("IPEXLinearOp::forward", std::vector<c10::IValue>({}));
#endif
at::AutoNonVariableTypeMode g;
ctx->save_for_backward({input, weight, bias});
return _forward(input, weight, bias);
}
static torch::autograd::tensor_list
backward(torch::autograd::AutogradContext *ctx,
torch::autograd::tensor_list grad_outputs) {
#if defined(IPEX_PROFILE_OP)
RECORD_FUNCTION("IPEXLinearOp::backward", std::vector<c10::IValue>({}));
#endif
auto saved = ctx->get_saved_variables();
at::Tensor input = saved[0];
at::Tensor weight = saved[1];
at::Tensor bias = saved[2];
at::Tensor grad_output = grad_outputs[0];
at::Tensor grad_input, grad_weight;
at::Tensor grad_bias = torch::Tensor();
try {
if (torch_ipex::check_auto_dnnl() &&
input.device().type() == c10::DeviceType::XPU) {
grad_input = torch_ipex::cpu::AtenIpexCPUDev::dil_linear_backward_input(
input.sizes(),
grad_output.is_contiguous() ? grad_output
: grad_output.contiguous(),
weight.is_contiguous() ? weight : weight.contiguous());
std::tie(grad_weight, grad_bias) =
torch_ipex::cpu::AtenIpexCPUDev::dil_linear_backward_weights(
grad_output.is_contiguous() ? grad_output
: grad_output.contiguous(),
input.is_contiguous() ? input : input.contiguous(),
weight.is_contiguous() ? weight : weight.contiguous(),
bias.defined());
return {grad_input, grad_weight, grad_bias};
}
} catch (std::exception &e) {
#if defined(_DEBUG)
TORCH_WARN(e.what());
#endif
}
if (input.dim() == 1) {
grad_output = grad_output.unsqueeze(0);
input = input.unsqueeze(0);
} else if (input.dim() > 2) {
std::vector<int64_t> mm_output_size;
mm_output_size.push_back(-1);
mm_output_size.push_back(weight.sizes()[0]);
grad_output = grad_output.reshape(mm_output_size);
}
if (input.device().type() == c10::DeviceType::XPU) {
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(input.layout() == c10::kStrided);
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(weight.layout() == c10::kStrided);
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(grad_output.layout() == c10::kStrided);
auto &&_ipex_input =
torch_ipex::bridge::shallowFallbackToCPUTensor(input);
auto &&_ipex_weight =
torch_ipex::bridge::shallowFallbackToCPUTensor(weight);
auto &&_ipex_grad_output =
torch_ipex::bridge::shallowFallbackToCPUTensor(grad_output);
if (input.dim() <= 2) {
grad_input = _ipex_grad_output.mm(_ipex_weight);
if (input.dim() == 1)
grad_input = grad_input.squeeze_(0);
grad_weight = _ipex_grad_output.t().mm(_ipex_input);
} else { // input.dim() > 2
grad_input = _ipex_grad_output.mm(_ipex_weight).reshape(input.sizes());
grad_weight = _ipex_grad_output.t().mm(
_ipex_input.view({-1, input.sizes()[input.dim() - 1]}));
}
if (bias.defined()) {
grad_bias = _ipex_grad_output.sum(0);
}
static_cast<void>(grad_input);
static_cast<void>(grad_weight);
static_cast<void>(grad_bias);
return {torch_ipex::bridge::shallowUpgradeToDPCPPTensor(grad_input),
torch_ipex::bridge::shallowUpgradeToDPCPPTensor(grad_weight),
torch_ipex::bridge::shallowUpgradeToDPCPPTensor(grad_bias)};
} else {
if (input.dim() <= 2) {
grad_input = grad_output.mm(weight);
if (input.dim() == 1)
grad_input = grad_input.squeeze_(0);
grad_weight = grad_output.t().mm(input);
} else if (input.dim() > 2) {
grad_input = grad_output.mm(weight).reshape(input.sizes());
grad_weight = grad_output.t().mm(
input.view({-1, input.sizes()[input.dim() - 1]}));
}
if (bias.defined()) {
grad_bias = grad_output.sum(0);
}
return {grad_input, grad_weight, grad_bias};
}
}
};
class NewMaxPool2dOp : public torch::autograd::Function<NewMaxPool2dOp> {
public:
static std::tuple<at::Tensor, at::Tensor>
_forward(at::Tensor input, at::IntArrayRef kernel_size,
at::IntArrayRef stride, at::IntArrayRef padding,
at::IntArrayRef dilation, bool ceil_mode) {
#if defined(IPEX_PROFILE_OP)
RECORD_FUNCTION("IPEXMaxPool2dOp::_forward", std::vector<c10::IValue>({}));
#endif
try {
if (torch_ipex::check_auto_dnnl() &&
input.device().type() == c10::DeviceType::XPU) {
auto src_dil_type =
torch_ipex::cpu::dbl::comm::try_gen_dil_tensor(input)
.get_data_type();
auto input_temp =
(src_dil_type == dil::data_type::u8 ||
src_dil_type == dil::data_type::s8 || input.is_contiguous())
? input
: input.contiguous();
at::Tensor output = torch_ipex::cpu::AtenIpexCPUDev::dil_max_pooling(
input_temp, kernel_size, stride, padding, dilation, ceil_mode);
return std::tuple<at::Tensor, at::Tensor>(output, output);
}
} catch (std::exception &e) {
#if defined(_DEBUG)
TORCH_WARN(e.what());
#endif
}
at::Tensor output, indices;
if (input.device().type() == c10::DeviceType::XPU) {
auto &&_ipex_input =
torch_ipex::bridge::shallowFallbackToCPUTensor(input);
auto &&_ipex_result = at::max_pool2d_with_indices(
_ipex_input, kernel_size, stride, padding, dilation, ceil_mode);
static_cast<void>(_ipex_result);
std::tie(output, indices) = std::tuple<at::Tensor, at::Tensor>(
torch_ipex::bridge::shallowUpgradeToDPCPPTensor(
std::get<0>(_ipex_result)),
torch_ipex::bridge::shallowUpgradeToDPCPPTensor(
std::get<1>(_ipex_result)));
} else {
std::tie(output, indices) = at::max_pool2d_with_indices(
input, kernel_size, stride, padding, dilation, ceil_mode);
}
return std::tuple<at::Tensor, at::Tensor>(output, indices);
}
static at::Tensor forward(torch::autograd::AutogradContext *ctx,
at::Tensor input, at::IntArrayRef kernel_size,
at::IntArrayRef stride, at::IntArrayRef padding,
at::IntArrayRef dilation, bool ceil_mode) {
#if defined(IPEX_PROFILE_OP)
RECORD_FUNCTION("IPEXMaxPool2dOp::forward", std::vector<c10::IValue>({}));
#endif
ctx->saved_data["kernel_size"] = kernel_size;
ctx->saved_data["stride"] = stride;
ctx->saved_data["padding"] = padding;
ctx->saved_data["dilation"] = dilation;
ctx->saved_data["ceil_mode"] = ceil_mode;
at::Tensor output, indices;
std::tie(output, indices) =
_forward(input, kernel_size, stride, padding, dilation, ceil_mode);
ctx->save_for_backward({input, indices});
return output;
}
static torch::autograd::tensor_list
backward(torch::autograd::AutogradContext *ctx,
torch::autograd::tensor_list grad_outputs) {
#if defined(IPEX_PROFILE_OP)
RECORD_FUNCTION("IPEXMaxPool2dOp::backward", std::vector<c10::IValue>({}));
#endif
auto saved = ctx->get_saved_variables();
at::Tensor input = saved[0];
at::Tensor indices = saved[1];
at::Tensor grad_output = grad_outputs[0];
at::Tensor grad_input;
std::vector<int64_t> kernel_size =
ctx->saved_data["kernel_size"].toIntVector();
std::vector<int64_t> stride = ctx->saved_data["stride"].toIntVector();
std::vector<int64_t> padding = ctx->saved_data["padding"].toIntVector();
std::vector<int64_t> dilation = ctx->saved_data["dilation"].toIntVector();
bool ceil_mode = ctx->saved_data["ceil_mode"].toBool();
try {
if (torch_ipex::check_auto_dnnl() &&
input.device().type() == c10::DeviceType::XPU) {
grad_input = torch_ipex::cpu::AtenIpexCPUDev::dil_max_pooling_backward(
grad_output.is_contiguous() ? grad_output
: grad_output.contiguous(),
indices.is_contiguous() ? indices : indices.contiguous(),
input.is_contiguous() ? input : input.contiguous(), kernel_size,
stride, padding, dilation, ceil_mode);
return {grad_input, at::Tensor(), at::Tensor(),
at::Tensor(), at::Tensor(), at::Tensor()};
}
} catch (std::exception &e) {
#if defined(_DEBUG)
TORCH_WARN(e.what());
#endif
}
if (input.device().type() == c10::DeviceType::XPU) {
auto &&_ipex_grad_output =
torch_ipex::bridge::shallowFallbackToCPUTensor(grad_output);
auto &&_ipex_input =
torch_ipex::bridge::shallowFallbackToCPUTensor(input);
auto &&_ipex_indices =
torch_ipex::bridge::shallowFallbackToCPUTensor(indices);
auto &&_ipex_grad_input = at::max_pool2d_with_indices_backward(
_ipex_grad_output, _ipex_input, kernel_size, stride, padding,
dilation, ceil_mode, _ipex_indices);
static_cast<void>(_ipex_grad_input);
grad_input =
torch_ipex::bridge::shallowUpgradeToDPCPPTensor(_ipex_grad_input);
} else {
grad_input = at::max_pool2d_with_indices_backward(
grad_output, input, kernel_size, stride, padding, dilation, ceil_mode,
indices);
}
return {grad_input, at::Tensor(), at::Tensor(),
at::Tensor(), at::Tensor(), at::Tensor()};
}
};
class NewMaxPool3dOp : public torch::autograd::Function<NewMaxPool3dOp> {
public:
static std::tuple<at::Tensor, at::Tensor>
_forward(at::Tensor input, at::IntArrayRef kernel_size,
at::IntArrayRef stride, at::IntArrayRef padding,
at::IntArrayRef dilation, bool ceil_mode) {
#if defined(IPEX_PROFILE_OP)
RECORD_FUNCTION("IPEXMaxPool3dOp::_forward", std::vector<c10::IValue>({}));
#endif
try {
if (torch_ipex::check_auto_dnnl() &&
input.device().type() == c10::DeviceType::XPU) {
at::Tensor output = torch_ipex::cpu::AtenIpexCPUDev::dil_max_pooling(
input.is_contiguous() ? input : input.contiguous(), kernel_size,
stride, padding, dilation, ceil_mode);
return std::tuple<at::Tensor, at::Tensor>(output, output);
}
} catch (std::exception &e) {
#if defined(_DEBUG)
TORCH_WARN(e.what());
#endif
}
at::Tensor output, indices;
if (input.device().type() == c10::DeviceType::XPU) {
auto &&_ipex_input =
torch_ipex::bridge::shallowFallbackToCPUTensor(input);
auto &&_ipex_result = at::max_pool3d_with_indices(
_ipex_input, kernel_size, stride, padding, dilation, ceil_mode);
static_cast<void>(_ipex_result);
std::tie(output, indices) = std::tuple<at::Tensor, at::Tensor>(
torch_ipex::bridge::shallowUpgradeToDPCPPTensor(
std::get<0>(_ipex_result)),
torch_ipex::bridge::shallowUpgradeToDPCPPTensor(
std::get<1>(_ipex_result)));
} else {
std::tie(output, indices) = at::max_pool3d_with_indices(
input, kernel_size, stride, padding, dilation, ceil_mode);
}
return std::tuple<at::Tensor, at::Tensor>(output, indices);
}
static at::Tensor forward(torch::autograd::AutogradContext *ctx,
at::Tensor input, at::IntArrayRef kernel_size,
at::IntArrayRef stride, at::IntArrayRef padding,
at::IntArrayRef dilation, bool ceil_mode) {
#if defined(IPEX_PROFILE_OP)
RECORD_FUNCTION("IPEXMaxPool3dOp::forward", std::vector<c10::IValue>({}));
#endif
ctx->saved_data["kernel_size"] = kernel_size;
ctx->saved_data["stride"] = stride;
ctx->saved_data["padding"] = padding;
ctx->saved_data["dilation"] = dilation;
ctx->saved_data["ceil_mode"] = ceil_mode;
at::Tensor output, indices;
std::tie(output, indices) =
_forward(input, kernel_size, stride, padding, dilation, ceil_mode);
ctx->save_for_backward({input, indices});
return output;
}
static torch::autograd::tensor_list
backward(torch::autograd::AutogradContext *ctx,
torch::autograd::tensor_list grad_outputs) {
#if defined(IPEX_PROFILE_OP)
RECORD_FUNCTION("IPEXMaxPool3dOp::backward", std::vector<c10::IValue>({}));
#endif
auto saved = ctx->get_saved_variables();
at::Tensor input = saved[0];
at::Tensor indices = saved[1];
at::Tensor grad_output = grad_outputs[0];
at::Tensor grad_input;
std::vector<int64_t> kernel_size =
ctx->saved_data["kernel_size"].toIntVector();
std::vector<int64_t> stride = ctx->saved_data["stride"].toIntVector();
std::vector<int64_t> padding = ctx->saved_data["padding"].toIntVector();
std::vector<int64_t> dilation = ctx->saved_data["dilation"].toIntVector();
bool ceil_mode = ctx->saved_data["ceil_mode"].toBool();
try {
if (torch_ipex::check_auto_dnnl() &&
input.device().type() == c10::DeviceType::XPU) {
grad_input = torch_ipex::cpu::AtenIpexCPUDev::dil_max_pooling_backward(
grad_output.is_contiguous() ? grad_output
: grad_output.contiguous(),
indices.is_contiguous() ? indices : indices.contiguous(),
input.is_contiguous() ? input : input.contiguous(), kernel_size,
stride, padding, dilation, ceil_mode);
return {grad_input, at::Tensor(), at::Tensor(),
at::Tensor(), at::Tensor(), at::Tensor()};
}
} catch (std::exception &e) {
#if defined(_DEBUG)
TORCH_WARN(e.what());
#endif
}
if (input.device().type() == c10::DeviceType::XPU) {
auto &&_ipex_grad_output =
torch_ipex::bridge::shallowFallbackToCPUTensor(grad_output);
auto &&_ipex_input =
torch_ipex::bridge::shallowFallbackToCPUTensor(input);
auto &&_ipex_indices =
torch_ipex::bridge::shallowFallbackToCPUTensor(indices);
auto &&_ipex_grad_input = at::max_pool3d_with_indices_backward(
_ipex_grad_output, _ipex_input, kernel_size, stride, padding,
dilation, ceil_mode, _ipex_indices);
static_cast<void>(_ipex_grad_input);
grad_input =
torch_ipex::bridge::shallowUpgradeToDPCPPTensor(_ipex_grad_input);
} else {
grad_input = at::max_pool3d_with_indices_backward(
grad_output, input, kernel_size, stride, padding, dilation, ceil_mode,
indices);
}
return {grad_input, at::Tensor(), at::Tensor(),
at::Tensor(), at::Tensor(), at::Tensor()};
}
};
class NewApaptiveAvgPoolingOp
: public torch::autograd::Function<NewApaptiveAvgPoolingOp> {
public:
static at::Tensor _forward(at::Tensor input, at::IntArrayRef output_size) {
#if defined(IPEX_PROFILE_OP)
RECORD_FUNCTION("IPEXApaptiveAvgPoolingOp::_forward", std::vector<c10::IValue>({}));
#endif
try {
if (torch_ipex::check_auto_dnnl() &&
input.device().type() == c10::DeviceType::XPU) {
auto src_dil_type =
torch_ipex::cpu::dbl::comm::try_gen_dil_tensor(input)
.get_data_type();
auto input_temp =
(src_dil_type == dil::data_type::u8 ||
src_dil_type == dil::data_type::s8 || input.is_contiguous())
? input
: input.contiguous();
return torch_ipex::cpu::AtenIpexCPUDev::dil_adaptive_avg_pool2d(
input_temp, output_size);
}
} catch (std::exception &e) {
#if defined(_DEBUG)
TORCH_WARN(e.what());
#endif
}
if (input.device().type() == c10::DeviceType::XPU) {
auto &&_ipex_input =
torch_ipex::bridge::shallowFallbackToCPUTensor(input);
auto &&_ipex_result = at::_adaptive_avg_pool2d(_ipex_input, output_size);
static_cast<void>(_ipex_result); // Avoid warnings in case not used
return torch_ipex::bridge::shallowUpgradeToDPCPPTensor(_ipex_result);
} else {
return at::_adaptive_avg_pool2d(input, output_size);
}
}
static at::Tensor forward(torch::autograd::AutogradContext *ctx,
at::Tensor input, at::IntArrayRef output_size) {
#if defined(IPEX_PROFILE_OP)
RECORD_FUNCTION("IPEXApaptiveAvgPoolingOp::forward", std::vector<c10::IValue>({}));
#endif
ctx->save_for_backward({input});
return _forward(input, output_size);
}
static torch::autograd::tensor_list
backward(torch::autograd::AutogradContext *ctx,
torch::autograd::tensor_list grad_outputs) {
#if defined(IPEX_PROFILE_OP)
RECORD_FUNCTION("IPEXApaptiveAvgPoolingOp::backward", std::vector<c10::IValue>({}));
#endif
auto saved = ctx->get_saved_variables();
at::Tensor input = saved[0];
at::Tensor grad_output = grad_outputs[0];
at::Tensor grad_input;
try {
if (torch_ipex::check_auto_dnnl() &&
input.device().type() == c10::DeviceType::XPU) {
grad_input =
torch_ipex::cpu::AtenIpexCPUDev::dil_adaptive_avg_pool2d_backward(
grad_output.is_contiguous() ? grad_output
: grad_output.contiguous(),
input.is_contiguous() ? input : input.contiguous());
return {grad_input, at::Tensor()};
}
} catch (std::exception &e) {
#if defined(_DEBUG)
TORCH_WARN(e.what());
#endif
}
if (input.device().type() == c10::DeviceType::XPU) {
auto &&_ipex_grad_output =
torch_ipex::bridge::shallowFallbackToCPUTensor(grad_output);
auto &&_ipex_input =
torch_ipex::bridge::shallowFallbackToCPUTensor(input);
auto &&_ipex_result =
at::_adaptive_avg_pool2d_backward(_ipex_grad_output, _ipex_input);
static_cast<void>(_ipex_result); // Avoid warnings in case not used
grad_input =
torch_ipex::bridge::shallowUpgradeToDPCPPTensor(_ipex_result);
} else {
grad_input = at::_adaptive_avg_pool2d_backward(grad_output, input);
}
return {grad_input, at::Tensor()};
}
};
class NewEmbeddingBagOp : public torch::autograd::Function<NewEmbeddingBagOp> {
public:
static std::vector<at::Tensor>
_forward(const at::Tensor &weight, const at::Tensor &indices,
const at::Tensor &offsets, bool scale_grad_by_freq, int64_t mode,
bool sparse, bool include_last_offset,
const at::Tensor per_sample_weights = at::Tensor()) {
#if defined(IPEX_PROFILE_OP)
RECORD_FUNCTION("IPEXEmbeddingBagOp::_forward", std::vector<c10::IValue>({}));
#endif
try {
if (torch_ipex::check_auto_dnnl() &&
torch_ipex::cpu::aten::embedding_bag::embedding_bag_fast_path_sum(
weight, per_sample_weights, mode) &&
weight.device().type() == c10::DeviceType::XPU &&
indices.device().type() == c10::DeviceType::XPU &&
offsets.device().type() == c10::DeviceType::XPU) {
auto ret = torch_ipex::cpu::aten::embedding_bag::embedding_bag_impl(
weight, indices, offsets, scale_grad_by_freq, mode, sparse,
per_sample_weights, include_last_offset);
return {ret};
}
} catch (std::exception &e) {
#if defined(_DEBUG)
TORCH_WARN(e.what());
#endif
}
if (torch_ipex::check_auto_dnnl() &&
weight.device().type() == c10::DeviceType::XPU &&
indices.device().type() == c10::DeviceType::XPU &&
offsets.device().type() == c10::DeviceType::XPU) {
auto &&_ipex_weight =
torch_ipex::bridge::shallowFallbackToCPUTensor(weight);
auto &&_ipex_indices =
torch_ipex::bridge::shallowFallbackToCPUTensor(indices);
auto &&_ipex_offsets =
torch_ipex::bridge::shallowFallbackToCPUTensor(offsets);
auto &&_ipex_per_sample_weights =
torch_ipex::bridge::shallowFallbackToCPUTensor(per_sample_weights);
auto &&_ipex_result = at::embedding_bag(
_ipex_weight, _ipex_indices, _ipex_offsets, scale_grad_by_freq, mode,
sparse, _ipex_per_sample_weights, include_last_offset);
static_cast<void>(_ipex_result); // Avoid warnings in case not used
return {
torch_ipex::bridge::shallowUpgradeToDPCPPTensor(
std::get<0>(_ipex_result)),
torch_ipex::bridge::shallowUpgradeToDPCPPTensor(
std::get<1>(_ipex_result)),
torch_ipex::bridge::shallowUpgradeToDPCPPTensor(
std::get<2>(_ipex_result)),
torch_ipex::bridge::shallowUpgradeToDPCPPTensor(
std::get<3>(_ipex_result))};
} else {
auto ret =
at::embedding_bag(weight, indices, offsets, scale_grad_by_freq, mode,
sparse, per_sample_weights, include_last_offset);
return {std::get<0>(ret), std::get<1>(ret), std::get<2>(ret),std::get<3>(ret)};
}
}
static std::vector<at::Tensor>
forward(torch::autograd::AutogradContext *ctx, const at::Tensor &weight,
const at::Tensor &indices, const at::Tensor &offsets,
bool scale_grad_by_freq, int64_t mode, bool sparse,
bool include_last_offset,
const at::Tensor per_sample_weights = at::Tensor()) {
#if defined(IPEX_PROFILE_OP)
RECORD_FUNCTION("IPEXEmbeddingBagOp::forward", std::vector<c10::IValue>({}));
#endif
at::AutoNonVariableTypeMode g;
ctx->saved_data["num_weights"] = weight.size(0);
ctx->saved_data["scale_grad_by_freq"] = scale_grad_by_freq;
ctx->saved_data["mode"] = mode;
ctx->saved_data["sparse"] = sparse;
ctx->saved_data["include_last_offset"] = include_last_offset;
auto ret = _forward(weight, indices, offsets, scale_grad_by_freq, mode,
sparse, include_last_offset, per_sample_weights);
if (ret.size() != 1)
ctx->save_for_backward({weight, indices, offsets, per_sample_weights,
ret[1], ret[2],
ret[3]});
else
ctx->save_for_backward({weight, indices, offsets, per_sample_weights,
at::empty({0}, offsets.options()), at::Tensor(),
at::Tensor()});
return ret;
}
static torch::autograd::tensor_list
backward(torch::autograd::AutogradContext *ctx,
torch::autograd::tensor_list grad_outputs) {
#if defined(IPEX_PROFILE_OP)
RECORD_FUNCTION("IPEXEmbeddingBagOp::backward", std::vector<c10::IValue>({}));
#endif
at::AutoNonVariableTypeMode g;
auto saved = ctx->get_saved_variables();
at::Tensor weight = saved[0];
at::Tensor indices = saved[1];
at::Tensor offsets = saved[2];
at::Tensor per_sample_weights = saved[3];
at::Tensor offset2bag = saved[4];
at::Tensor bag_size = saved[5];
at::Tensor maximum_indices = saved[6];
int64_t num_weights = ctx->saved_data["num_weights"].toInt();
bool scale_grad_by_freq = ctx->saved_data["scale_grad_by_freq"].toBool();
int64_t mode = ctx->saved_data["mode"].toInt();
bool sparse = ctx->saved_data["sparse"].toBool();
bool include_last_offset = ctx->saved_data["include_last_offset"].toBool();
at::Tensor grad = grad_outputs[0];
if (!sparse)
grad = grad.contiguous();
try {
if (torch_ipex::check_auto_dnnl() &&
(torch_ipex::cpu::aten::embedding_bag::
embedding_bag_backward_fast_path_sum(
grad, indices, offset2bag, per_sample_weights,
scale_grad_by_freq, mode)) &&
weight.device().type() == c10::DeviceType::XPU &&
indices.device().type() == c10::DeviceType::XPU &&
offsets.device().type() == c10::DeviceType::XPU) {
return {
torch_ipex::cpu::aten::embedding_bag::embedding_bag_backward_impl(
grad, indices, offsets, offset2bag, bag_size, maximum_indices,
num_weights, scale_grad_by_freq, mode, sparse,
per_sample_weights),
at::Tensor(),
at::Tensor(),
at::Tensor(),
at::Tensor(),
at::Tensor(),
at::Tensor()};
}
} catch (std::exception &e) {
#if defined(_DEBUG)
TORCH_WARN(e.what());
#endif
}
bool compute_per_sample_weights_grad =
per_sample_weights.defined() && per_sample_weights.requires_grad();
at::Tensor offset2bag_ =
torch_ipex::cpu::aten::embedding_bag::embedding_bag_get_offset2bag(
indices, offsets, offset2bag);
if (torch_ipex::check_auto_dnnl() &&
grad.device().type() == c10::DeviceType::XPU &&
indices.device().type() == c10::DeviceType::XPU &&
offsets.device().type() == c10::DeviceType::XPU &&
(!per_sample_weights.defined() ||
per_sample_weights.device().type() == c10::DeviceType::XPU)) {
auto &&_ipex_grad = torch_ipex::bridge::shallowFallbackToCPUTensor(grad);
auto &&_ipex_weight =
torch_ipex::bridge::shallowFallbackToCPUTensor(weight);
auto &&_ipex_indices =
torch_ipex::bridge::shallowFallbackToCPUTensor(indices);
auto &&_ipex_offsets =
torch_ipex::bridge::shallowFallbackToCPUTensor(offsets);
auto &&_ipex_offset2bag_ =
torch_ipex::bridge::shallowFallbackToCPUTensor(offset2bag_);
auto &&_ipex_bag_size =
torch_ipex::bridge::shallowFallbackToCPUTensor(bag_size);
auto &&_ipex_maximum_indices =
torch_ipex::bridge::shallowFallbackToCPUTensor(maximum_indices);
auto &&_ipex_per_sample_weights =
torch_ipex::bridge::shallowFallbackToCPUTensor(per_sample_weights);
auto &&_ipex_weight_grad =
sparse
? at::_embedding_bag_sparse_backward(
_ipex_grad, _ipex_indices, _ipex_offsets, _ipex_offset2bag_,
_ipex_bag_size, num_weights, scale_grad_by_freq, mode,
_ipex_per_sample_weights)
: at::_embedding_bag_dense_backward(
_ipex_grad, _ipex_indices, _ipex_offsets, _ipex_offset2bag_,
_ipex_bag_size, _ipex_maximum_indices, num_weights,
scale_grad_by_freq, mode, _ipex_per_sample_weights);
auto &&_ipex_per_sample_weights_grad =
compute_per_sample_weights_grad
? at::_embedding_bag_per_sample_weights_backward(
_ipex_grad, _ipex_weight, _ipex_indices, _ipex_offsets,
_ipex_offset2bag_, mode)
: at::Tensor();
auto per_sample_weights_grad =
torch_ipex::bridge::shallowUpgradeToDPCPPTensor(
_ipex_per_sample_weights_grad);
return {
torch_ipex::bridge::shallowUpgradeToDPCPPTensor(_ipex_weight_grad),
at::Tensor(),
at::Tensor(),
at::Tensor(),
at::Tensor(),
at::Tensor(),
at::Tensor(),
per_sample_weights_grad};
} else {
auto weight_grad =
sparse
? at::_embedding_bag_sparse_backward(
grad, indices, offsets, offset2bag_, bag_size, num_weights,
scale_grad_by_freq, mode, per_sample_weights)
: at::_embedding_bag_dense_backward(
grad, indices, offsets, offset2bag_, bag_size,
maximum_indices, num_weights, scale_grad_by_freq, mode,
per_sample_weights);
auto per_sample_weights_grad =
compute_per_sample_weights_grad
? at::_embedding_bag_per_sample_weights_backward(
grad, grad, indices, offsets, offset2bag_, mode)
: at::Tensor();
return {weight_grad, per_sample_weights_grad,
at::Tensor(), at::Tensor(),
at::Tensor(), at::Tensor(),
at::Tensor(), at::Tensor()};
}
}
};
class NewRNNLayerOp : public torch::autograd::Function<NewRNNLayerOp> {
public:
static std::vector<at::Tensor> _forward(const at::Tensor& input, const at::Tensor& w1, const at::Tensor& w2,
const at::Tensor& w3, const at::Tensor& w4, const at::Tensor& hx, const at::Tensor& cx, bool reverse, int64_t mode,
int64_t hidden_size, int64_t num_layers, bool has_biases, bool train, bool bidirectional, at::IntArrayRef batch_sizes,
const std::vector<float>& scales = {}, const std::vector<int32_t>& shift = {}, bool quantized = false) {
#if defined(IPEX_PROFILE_OP)
RECORD_FUNCTION("NewRNNLayerOp::_forward", std::vector<c10::IValue>({}));
#endif
try {
if (torch_ipex::check_auto_dnnl() &&
input.device().type() == c10::DeviceType::XPU) {
return torch_ipex::cpu::AtenIpexCPUDev::dil_rnn_layer(
input, w1, w2, w3, w4, hx, cx, reverse, mode, hidden_size, num_layers, has_biases, train, bidirectional, batch_sizes, scales, shift, quantized);
}
} catch (std::exception &e) {
#if defined(_DEBUG)
TORCH_WARN(e.what());
#endif
}
IPEX_CHECK(false, "RNN forward not support fallback path now");
}
static std::vector<at::Tensor> forward(torch::autograd::AutogradContext *ctx, const at::Tensor& input, const at::Tensor& w1,
const at::Tensor& w2, const at::Tensor& w3, const at::Tensor& w4, const at::Tensor& hx, const at::Tensor& cx, bool reverse,
int64_t mode, int64_t hidden_size, int64_t num_layers, bool has_biases, bool train, bool bidirectional, at::IntArrayRef batch_sizes) {
ctx->saved_data["reverse"] = reverse;
ctx->saved_data["mode"] = mode;
ctx->saved_data["hidden_size"] = hidden_size;
ctx->saved_data["num_layers"] = num_layers;
ctx->saved_data["has_biases"] = has_biases;
ctx->saved_data["train"] = train;
ctx->saved_data["bidirectional"] = bidirectional;
auto outputs = _forward(input, w1, w2, w3, w4, hx, cx, reverse, mode, hidden_size, num_layers, has_biases, train, bidirectional, batch_sizes);
ctx->save_for_backward({input, w1, w2, w3, w4, hx, cx, outputs[0], outputs[1], outputs[2]});
return outputs;
}
static torch::autograd::tensor_list
backward(torch::autograd::AutogradContext *ctx,
torch::autograd::tensor_list grad_outputs) {
#if defined(IPEX_PROFILE_OP)
RECORD_FUNCTION("NewRNNLayerOp::backward", std::vector<c10::IValue>({}));
#endif
auto saved = ctx->get_saved_variables();
at::Tensor input = saved[0];
at::Tensor w1 = saved[1];
at::Tensor w2 = saved[2];
at::Tensor w3 = saved[3];
at::Tensor w4 = saved[4];
at::Tensor hx = saved[5];
at::Tensor cx = saved[6];
at::Tensor output = saved[7];
at::Tensor hy = saved[8];
at::Tensor cy = saved[9];
bool reverse = ctx->saved_data["reverse"].toBool();
int64_t mode = ctx->saved_data["mode"].toInt();
int64_t hidden_size = ctx->saved_data["hidden_size"].toInt();
int64_t num_layers = ctx->saved_data["num_layers"].toInt();
bool has_biases = ctx->saved_data["has_biases"].toBool();
bool train = ctx->saved_data["train"].toBool();
bool bidirectional = ctx->saved_data["bidirectional"].toBool();
at::Tensor grad_output = grad_outputs[0].contiguous();
at::Tensor grad_hy = grad_outputs[1].contiguous();
at::Tensor grad_cy = grad_outputs[2].contiguous();
try {
if (torch_ipex::check_auto_dnnl() &&
input.device().type() == c10::DeviceType::XPU) {
auto grad_inputs = torch_ipex::cpu::AtenIpexCPUDev::dil_rnn_layer_backward(input, w1, w2, w3, w4, hx, cx, output, hy, cy, grad_output, grad_hy, grad_cy, reverse, mode, hidden_size, num_layers, has_biases, train, bidirectional, /*batch_sizes*/{});
return {grad_inputs[0], grad_inputs[1], grad_inputs[2],
grad_inputs[3], grad_inputs[4], grad_inputs[5],
grad_inputs[6], at::Tensor(), at::Tensor(),
at::Tensor(), at::Tensor(), at::Tensor(),
at::Tensor(), at::Tensor(), at::Tensor(),
at::Tensor(), at::Tensor(), at::Tensor()};
}
} catch (std::exception &e) {
#if defined(_DEBUG)
TORCH_WARN(e.what());
#endif
}
IPEX_CHECK(false, "RNN backward not support fallback path now");
}
};
class FrozenBatchNormOp : public torch::autograd::Function<FrozenBatchNormOp> {
public:
static at::Tensor _forward(const at::Tensor& input, const at::Tensor& weight, const at::Tensor& bias, const at::Tensor& running_mean, const at::Tensor& running_var) {
#if defined(IPEX_PROFILE_OP)
RECORD_FUNCTION("FrozenBatchNormOp::_forward", std::vector<c10::IValue>({}));
#endif
return torch_ipex::cpu::AtenIpexCPUDev::dil_frozen_batch_norm(input, weight, bias, running_mean, running_var, 0);
}
static at::Tensor forward(torch::autograd::AutogradContext *ctx,
const at::Tensor& input, const at::Tensor& weight, const at::Tensor& bias, const at::Tensor& running_mean, const at::Tensor& running_var) {
#if defined(IPEX_PROFILE_OP)
RECORD_FUNCTION("FrozenBatchNormOp::forward", std::vector<c10::IValue>({}));
#endif
ctx->save_for_backward({input, weight, running_mean, running_var});
return torch_ipex::cpu::AtenIpexCPUDev::dil_frozen_batch_norm(input, weight, bias, running_mean, running_var, 0);
}
static torch::autograd::tensor_list
backward(torch::autograd::AutogradContext *ctx,
torch::autograd::tensor_list grad_outputs) {
#if defined(IPEX_PROFILE_OP)
RECORD_FUNCTION("FrozenBatchNormOp::backward", std::vector<c10::IValue>({}));
#endif
auto saved = ctx->get_saved_variables();
at::Tensor input = saved[0];
at::Tensor weight = saved[1];
at::Tensor running_mean = saved[2];
at::Tensor running_var = saved[3];
at::Tensor grad_output = grad_outputs[0].contiguous();
auto output = torch_ipex::cpu::AtenIpexCPUDev::dil_frozen_batch_norm_backward(grad_output, input, weight, running_mean, running_var, 0);
return {output, at::Tensor(), at::Tensor(), at::Tensor(), at::Tensor()};
}
};
|
tenzen-y/intel-extension-for-pytorch | torch_ipex/csrc/ipex_tensor_impl.h | <gh_stars>0
#pragma once
#include <ATen/Tensor.h>
#include <ATen/TensorUtils.h>
#include <c10/core/Storage.h>
#include <c10/core/TensorImpl.h>
#include <memory>
namespace torch_ipex {
class IPEXTensorImpl : public c10::TensorImpl {
public:
explicit IPEXTensorImpl(at::Storage storage, at::DispatchKey type_id, at::ScalarType dtype);
explicit IPEXTensorImpl(at::DispatchKeySet type_set, const caffe2::TypeMeta& data_type, c10::optional<c10::Device> device_opt);
~IPEXTensorImpl() {
static_cast<void>(0);
}
void copy_auto_grad(c10::TensorImpl *);
void copy_meta_info(const c10::TensorImpl *, bool keep_dtype = false);
void set_storage_data_ptr(c10::DataPtr);
void set_strided(at::IntArrayRef size, at::IntArrayRef stride, int64_t storage_offset, at::ScalarType dtype, int64_t padding_size = 0);
void reset_data_type(at::ScalarType dst_type);
c10::Storage& get_storage() {
return this->storage_;
}
static c10::Device GetCurrentAtenDevice();
static c10::Device SetCurrentAtenDevice(c10::Device);
static void CopyMetadata(c10::TensorImpl *, const c10::TensorImpl *);
static void CopySizeStridesAndOffset(c10::TensorImpl *, const c10::TensorImpl *);
};
} // namespace torch_ipex
|
genichin/esp-idf_for_ebell | components/efuse/include/esp_efuse.h | // Copyright 2017-2018 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include "esp_err.h"
#include "esp_log.h"
#include "sdkconfig.h"
#if CONFIG_IDF_TARGET_ESP32
#include "esp32/esp_efuse.h"
#elif CONFIG_IDF_TARGET_ESP32S2BETA
#include "esp32s2beta/esp_efuse.h"
#endif
#define ESP_ERR_EFUSE 0x1600 /*!< Base error code for efuse api. */
#define ESP_OK_EFUSE_CNT (ESP_ERR_EFUSE + 0x01) /*!< OK the required number of bits is set. */
#define ESP_ERR_EFUSE_CNT_IS_FULL (ESP_ERR_EFUSE + 0x02) /*!< Error field is full. */
#define ESP_ERR_EFUSE_REPEATED_PROG (ESP_ERR_EFUSE + 0x03) /*!< Error repeated programming of programmed bits is strictly forbidden. */
#define ESP_ERR_CODING (ESP_ERR_EFUSE + 0x04) /*!< Error while a encoding operation. */
/**
* @brief Structure eFuse field
*/
typedef struct {
esp_efuse_block_t efuse_block: 8; /**< Block of eFuse */
uint8_t bit_start; /**< Start bit [0..255] */
uint16_t bit_count; /**< Length of bit field [1..-]*/
} esp_efuse_desc_t;
/**
* @brief Reads bits from EFUSE field and writes it into an array.
*
* The number of read bits will be limited to the minimum value
* from the description of the bits in "field" structure or "dst_size_bits" required size.
* Use "esp_efuse_get_field_size()" function to determine the length of the field.
* @param[in] field A pointer to the structure describing the fields of efuse.
* @param[out] dst A pointer to array that will contain the result of reading.
* @param[in] dst_size_bits The number of bits required to read.
* If the requested number of bits is greater than the field,
* the number will be limited to the field size.
*
* @return
* - ESP_OK: The operation was successfully completed.
* - ESP_ERR_INVALID_ARG: Error in the passed arguments.
*/
esp_err_t esp_efuse_read_field_blob(const esp_efuse_desc_t* field[], void* dst, size_t dst_size_bits);
/**
* @brief Reads bits from EFUSE field and returns number of bits programmed as "1".
*
* If the bits are set not sequentially, they will still be counted.
* @param[in] field A pointer to the structure describing the fields of efuse.
* @param[out] out_cnt A pointer that will contain the number of programmed as "1" bits.
*
* @return
* - ESP_OK: The operation was successfully completed.
* - ESP_ERR_INVALID_ARG: Error in the passed arguments.
*/
esp_err_t esp_efuse_read_field_cnt(const esp_efuse_desc_t* field[], size_t* out_cnt);
/**
* @brief Writes array to EFUSE field.
*
* The number of write bits will be limited to the minimum value
* from the description of the bits in "field" structure or "src_size_bits" required size.
* Use "esp_efuse_get_field_size()" function to determine the length of the field.
* After the function is completed, the writing registers are cleared.
* @param[in] field A pointer to the structure describing the fields of efuse.
* @param[in] src A pointer to array that contains the data for writing.
* @param[in] src_size_bits The number of bits required to write.
*
* @return
* - ESP_OK: The operation was successfully completed.
* - ESP_ERR_INVALID_ARG: Error in the passed arguments.
* - ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden.
* - ESP_ERR_CODING: Error range of data does not match the coding scheme.
*/
esp_err_t esp_efuse_write_field_blob(const esp_efuse_desc_t* field[], const void* src, size_t src_size_bits);
/**
* @brief Writes a required count of bits as "1" to EFUSE field.
*
* If there are no free bits in the field to set the required number of bits to "1",
* ESP_ERR_EFUSE_CNT_IS_FULL error is returned, the field will not be partially recorded.
* After the function is completed, the writing registers are cleared.
* @param[in] field A pointer to the structure describing the fields of efuse.
* @param[in] cnt Required number of programmed as "1" bits.
*
* @return
* - ESP_OK: The operation was successfully completed.
* - ESP_ERR_INVALID_ARG: Error in the passed arguments.
* - ESP_ERR_EFUSE_CNT_IS_FULL: Not all requested cnt bits is set.
*/
esp_err_t esp_efuse_write_field_cnt(const esp_efuse_desc_t* field[], size_t cnt);
/**
* @brief Sets a write protection for the whole block.
*
* After that, it is impossible to write to this block.
* The write protection does not apply to block 0.
* @param[in] blk Block number of eFuse. (EFUSE_BLK1, EFUSE_BLK2 and EFUSE_BLK3)
*
* @return
* - ESP_OK: The operation was successfully completed.
* - ESP_ERR_INVALID_ARG: Error in the passed arguments.
* - ESP_ERR_EFUSE_CNT_IS_FULL: Not all requested cnt bits is set.
* - ESP_ERR_NOT_SUPPORTED: The block does not support this command.
*/
esp_err_t esp_efuse_set_write_protect(esp_efuse_block_t blk);
/**
* @brief Sets a read protection for the whole block.
*
* After that, it is impossible to read from this block.
* The read protection does not apply to block 0.
* @param[in] blk Block number of eFuse. (EFUSE_BLK1, EFUSE_BLK2 and EFUSE_BLK3)
*
* @return
* - ESP_OK: The operation was successfully completed.
* - ESP_ERR_INVALID_ARG: Error in the passed arguments.
* - ESP_ERR_EFUSE_CNT_IS_FULL: Not all requested cnt bits is set.
* - ESP_ERR_NOT_SUPPORTED: The block does not support this command.
*/
esp_err_t esp_efuse_set_read_protect(esp_efuse_block_t blk);
/**
* @brief Returns the number of bits used by field.
*
* @param[in] field A pointer to the structure describing the fields of efuse.
*
* @return Returns the number of bits used by field.
*/
int esp_efuse_get_field_size(const esp_efuse_desc_t* field[]);
/**
* @brief Returns value of efuse register.
*
* This is a thread-safe implementation.
* Example: EFUSE_BLK2_RDATA3_REG where (blk=2, num_reg=3)
* @param[in] blk Block number of eFuse.
* @param[in] num_reg The register number in the block.
*
* @return Value of register
*/
uint32_t esp_efuse_read_reg(esp_efuse_block_t blk, unsigned int num_reg);
/**
* @brief Write value to efuse register.
*
* Apply a coding scheme if necessary.
* This is a thread-safe implementation.
* Example: EFUSE_BLK3_WDATA0_REG where (blk=3, num_reg=0)
* @param[in] blk Block number of eFuse.
* @param[in] num_reg The register number in the block.
* @param[in] val Value to write.
*
* @return
* - ESP_OK: The operation was successfully completed.
* - ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden.
*/
esp_err_t esp_efuse_write_reg(esp_efuse_block_t blk, unsigned int num_reg, uint32_t val);
/**
* @brief Return efuse coding scheme for blocks.
*
* Note: The coding scheme is applicable only to 1, 2 and 3 blocks. For 0 block, the coding scheme is always ``NONE``.
*
* @param[in] blk Block number of eFuse.
* @return Return efuse coding scheme for blocks
*/
esp_efuse_coding_scheme_t esp_efuse_get_coding_scheme(esp_efuse_block_t blk);
/**
* @brief Read key to efuse block starting at the offset and the required size.
*
* @param[in] blk Block number of eFuse.
* @param[in] dst_key A pointer to array that will contain the result of reading.
* @param[in] offset_in_bits Start bit in block.
* @param[in] size_bits The number of bits required to read.
*
* @return
* - ESP_OK: The operation was successfully completed.
* - ESP_ERR_INVALID_ARG: Error in the passed arguments.
* - ESP_ERR_CODING: Error range of data does not match the coding scheme.
*/
esp_err_t esp_efuse_read_block(esp_efuse_block_t blk, void* dst_key, size_t offset_in_bits, size_t size_bits);
/**
* @brief Write key to efuse block starting at the offset and the required size.
*
* @param[in] blk Block number of eFuse.
* @param[in] src_key A pointer to array that contains the key for writing.
* @param[in] offset_in_bits Start bit in block.
* @param[in] size_bits The number of bits required to write.
*
* @return
* - ESP_OK: The operation was successfully completed.
* - ESP_ERR_INVALID_ARG: Error in the passed arguments.
* - ESP_ERR_CODING: Error range of data does not match the coding scheme.
* - ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits
*/
esp_err_t esp_efuse_write_block(esp_efuse_block_t blk, const void* src_key, size_t offset_in_bits, size_t size_bits);
/**
* @brief Returns chip version from efuse
*
* @return chip version
*/
uint8_t esp_efuse_get_chip_ver(void);
/**
* @brief Returns chip package from efuse
*
* @return chip package
*/
uint32_t esp_efuse_get_pkg_ver(void);
/* @brief Permanently update values written to the efuse write registers
*
* After updating EFUSE_BLKx_WDATAx_REG registers with new values to
* write, call this function to permanently write them to efuse.
*
* @note Setting bits in efuse is permanent, they cannot be unset.
*
* @note Due to this restriction you don't need to copy values to
* Efuse write registers from the matching read registers, bits which
* are set in the read register but unset in the matching write
* register will be unchanged when new values are burned.
*
* @note This function is not threadsafe, if calling code updates
* efuse values from multiple tasks then this is caller's
* responsibility to serialise.
*
* After burning new efuses, the read registers are updated to match
* the new efuse values.
*/
void esp_efuse_burn_new_values(void);
/* @brief Reset efuse write registers
*
* Efuse write registers are written to zero, to negate
* any changes that have been staged here.
*
* @note This function is not threadsafe, if calling code updates
* efuse values from multiple tasks then this is caller's
* responsibility to serialise.
*/
void esp_efuse_reset(void);
/* @brief Disable BASIC ROM Console via efuse
*
* By default, if booting from flash fails the ESP32 will boot a
* BASIC console in ROM.
*
* Call this function (from bootloader or app) to permanently
* disable the console on this chip.
*/
void esp_efuse_disable_basic_rom_console(void);
/* @brief Write random data to efuse key block write registers
*
* @note Caller is responsible for ensuring efuse
* block is empty and not write protected, before calling.
*
* @note Behaviour depends on coding scheme: a 256-bit key is
* generated and written for Coding Scheme "None", a 192-bit key
* is generated, extended to 256-bits by the Coding Scheme,
* and then writtten for 3/4 Coding Scheme.
*
* @note This function does not burn the new values, caller should
* call esp_efuse_burn_new_values() when ready to do this.
*
* @param blk_wdata0_reg Address of the first data write register
* in the block
*/
void esp_efuse_write_random_key(uint32_t blk_wdata0_reg);
/* @brief Return secure_version from efuse field.
* @return Secure version from efuse field
*/
uint32_t esp_efuse_read_secure_version(void);
/* @brief Check secure_version from app and secure_version and from efuse field.
*
* @param secure_version Secure version from app.
* @return
* - True: If version of app is equal or more then secure_version from efuse.
*/
bool esp_efuse_check_secure_version(uint32_t secure_version);
/* @brief Write efuse field by secure_version value.
*
* Update the secure_version value is available if the coding scheme is None.
* Note: Do not use this function in your applications. This function is called as part of the other API.
*
* @param[in] secure_version Secure version from app.
* @return
* - ESP_OK: Successful.
* - ESP_FAIL: secure version of app cannot be set to efuse field.
* - ESP_ERR_NOT_SUPPORTED: Anti rollback is not supported with the 3/4 and Repeat coding scheme.
*/
esp_err_t esp_efuse_update_secure_version(uint32_t secure_version);
/* @brief Initializes variables: offset and size to simulate the work of an eFuse.
*
* Note: To simulate the work of an eFuse need to set CONFIG_BOOTLOADER_EFUSE_SECURE_VERSION_EMULATE option
* and to add in the partition.csv file a line `efuse_em, data, efuse, , 0x2000,`.
*
* @param[in] offset The starting address of the partition where the eFuse data will be located.
* @param[in] size The size of the partition.
*/
void esp_efuse_init(uint32_t offset, uint32_t size);
/* @brief Set the batch mode of writing fields.
*
* This mode allows you to write the fields in the batch mode.
* If this mode is enabled, esp_efuse_batch_write_commit() must be called
* to actually burn any written efuses.
* In this mode, reading efuse is not possible.
* This mode should be used when burning several efuses at one time.
*
* \code{c}
* // Example of using the batch writing mode.
*
* // set the batch writing mode
* esp_efuse_batch_write_begin();
*
* // use any writing functions as usual
* esp_efuse_write_field_blob(ESP_EFUSE_...);
* esp_efuse_write_field_cnt(ESP_EFUSE_...);
* esp_efuse_set_write_protect(EFUSE_BLKx);
* esp_efuse_write_reg(EFUSE_BLKx, ...);
* esp_efuse_write_block(EFUSE_BLKx, ...);
* ...
*
* // Write all of these fields to the efuse registers
* esp_efuse_batch_write_commit();
*
* \endcode
*
* @return
* - ESP_OK: Successful.
*/
esp_err_t esp_efuse_batch_write_begin(void);
/* @brief Reset the batch mode of writing fields.
*
* It will reset the batch writing mode and any written changes.
*
* @return
* - ESP_OK: Successful.
* - ESP_ERR_INVALID_STATE: Tha batch mode was not set.
*/
esp_err_t esp_efuse_batch_write_cancel(void);
/* @brief Writes all prepared data for the batch mode.
*
* Must be called to ensure changes are written to the efuse registers.
* After this the batch writing mode will be reset.
*
* @return
* - ESP_OK: Successful.
* - ESP_ERR_INVALID_STATE: The deferred writing mode was not set.
*/
esp_err_t esp_efuse_batch_write_commit(void);
inline static bool soc_has_cache_lock_bug(void)
{
return (esp_efuse_get_chip_ver() == 3);
}
#ifdef __cplusplus
}
#endif
|
genichin/esp-idf_for_ebell | components/esp_wifi/include/esp_private/wifi_os_adapter.h | // Copyright 2018 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef ESP_WIFI_OS_ADAPTER_H_
#define ESP_WIFI_OS_ADAPTER_H_
#include <stdarg.h>
#ifdef __cplusplus
extern "C" {
#endif
#define ESP_WIFI_OS_ADAPTER_VERSION 0x00000004
#define ESP_WIFI_OS_ADAPTER_MAGIC 0xDEADBEAF
#define OSI_FUNCS_TIME_BLOCKING 0xffffffff
#define OSI_QUEUE_SEND_FRONT 0
#define OSI_QUEUE_SEND_BACK 1
#define OSI_QUEUE_SEND_OVERWRITE 2
typedef struct {
int32_t _version;
void (*_set_isr)(int32_t n, void *f, void *arg);
void (*_ints_on)(uint32_t mask);
void (*_ints_off)(uint32_t mask);
void *(* _spin_lock_create)(void);
void (* _spin_lock_delete)(void *lock);
uint32_t (*_wifi_int_disable)(void *wifi_int_mux);
void (*_wifi_int_restore)(void *wifi_int_mux, uint32_t tmp);
void (*_task_yield_from_isr)(void);
void *(*_semphr_create)(uint32_t max, uint32_t init);
void (*_semphr_delete)(void *semphr);
int32_t (*_semphr_take)(void *semphr, uint32_t block_time_tick);
int32_t (*_semphr_give)(void *semphr);
void *(*_wifi_thread_semphr_get)(void);
void *(*_mutex_create)(void);
void *(*_recursive_mutex_create)(void);
void (*_mutex_delete)(void *mutex);
int32_t (*_mutex_lock)(void *mutex);
int32_t (*_mutex_unlock)(void *mutex);
void *(* _queue_create)(uint32_t queue_len, uint32_t item_size);
void (* _queue_delete)(void *queue);
int32_t (* _queue_send)(void *queue, void *item, uint32_t block_time_tick);
int32_t (* _queue_send_from_isr)(void *queue, void *item, void *hptw);
int32_t (* _queue_send_to_back)(void *queue, void *item, uint32_t block_time_tick);
int32_t (* _queue_send_to_front)(void *queue, void *item, uint32_t block_time_tick);
int32_t (* _queue_recv)(void *queue, void *item, uint32_t block_time_tick);
uint32_t (* _queue_msg_waiting)(void *queue);
void *(* _event_group_create)(void);
void (* _event_group_delete)(void *event);
uint32_t (* _event_group_set_bits)(void *event, uint32_t bits);
uint32_t (* _event_group_clear_bits)(void *event, uint32_t bits);
uint32_t (* _event_group_wait_bits)(void *event, uint32_t bits_to_wait_for, int32_t clear_on_exit, int32_t wait_for_all_bits, uint32_t block_time_tick);
int32_t (* _task_create_pinned_to_core)(void *task_func, const char *name, uint32_t stack_depth, void *param, uint32_t prio, void *task_handle, uint32_t core_id);
int32_t (* _task_create)(void *task_func, const char *name, uint32_t stack_depth, void *param, uint32_t prio, void *task_handle);
void (* _task_delete)(void *task_handle);
void (* _task_delay)(uint32_t tick);
int32_t (* _task_ms_to_tick)(uint32_t ms);
void *(* _task_get_current_task)(void);
int32_t (* _task_get_max_priority)(void);
void *(* _malloc)(uint32_t size);
void (* _free)(void *p);
int32_t (* _event_post)(const char* event_base, int32_t event_id, void* event_data, size_t event_data_size, uint32_t ticks_to_wait);
uint32_t (* _get_free_heap_size)(void);
uint32_t (* _rand)(void);
void (* _dport_access_stall_other_cpu_start_wrap)(void);
void (* _dport_access_stall_other_cpu_end_wrap)(void);
int32_t (* _phy_rf_deinit)(uint32_t module);
void (* _phy_load_cal_and_init)(uint32_t module);
#if CONFIG_IDF_TARGET_ESP32
void (* _phy_common_clock_enable)(void);
void (* _phy_common_clock_disable)(void);
#endif
int32_t (* _read_mac)(uint8_t* mac, uint32_t type);
void (* _timer_arm)(void *timer, uint32_t tmout, bool repeat);
void (* _timer_disarm)(void *timer);
void (* _timer_done)(void *ptimer);
void (* _timer_setfn)(void *ptimer, void *pfunction, void *parg);
void (* _timer_arm_us)(void *ptimer, uint32_t us, bool repeat);
void (* _periph_module_enable)(uint32_t periph);
void (* _periph_module_disable)(uint32_t periph);
int64_t (* _esp_timer_get_time)(void);
int32_t (* _nvs_set_i8)(uint32_t handle, const char* key, int8_t value);
int32_t (* _nvs_get_i8)(uint32_t handle, const char* key, int8_t* out_value);
int32_t (* _nvs_set_u8)(uint32_t handle, const char* key, uint8_t value);
int32_t (* _nvs_get_u8)(uint32_t handle, const char* key, uint8_t* out_value);
int32_t (* _nvs_set_u16)(uint32_t handle, const char* key, uint16_t value);
int32_t (* _nvs_get_u16)(uint32_t handle, const char* key, uint16_t* out_value);
int32_t (* _nvs_open)(const char* name, uint32_t open_mode, uint32_t *out_handle);
void (* _nvs_close)(uint32_t handle);
int32_t (* _nvs_commit)(uint32_t handle);
int32_t (* _nvs_set_blob)(uint32_t handle, const char* key, const void* value, size_t length);
int32_t (* _nvs_get_blob)(uint32_t handle, const char* key, void* out_value, size_t* length);
int32_t (* _nvs_erase_key)(uint32_t handle, const char* key);
int32_t (* _get_random)(uint8_t *buf, size_t len);
int32_t (* _get_time)(void *t);
unsigned long (* _random)(void);
#if CONFIG_IDF_TARGET_ESP32S2BETA
uint32_t (* _slowclk_cal_get)(void);
#endif
void (* _log_write)(uint32_t level, const char* tag, const char* format, ...);
void (* _log_writev)(uint32_t level, const char* tag, const char* format, va_list args);
uint32_t (* _log_timestamp)(void);
void * (* _malloc_internal)(size_t size);
void * (* _realloc_internal)(void *ptr, size_t size);
void * (* _calloc_internal)(size_t n, size_t size);
void * (* _zalloc_internal)(size_t size);
void * (* _wifi_malloc)(size_t size);
void * (* _wifi_realloc)(void *ptr, size_t size);
void * (* _wifi_calloc)(size_t n, size_t size);
void * (* _wifi_zalloc)(size_t size);
void * (* _wifi_create_queue)(int32_t queue_len, int32_t item_size);
void (* _wifi_delete_queue)(void * queue);
int32_t (* _modem_sleep_enter)(uint32_t module);
int32_t (* _modem_sleep_exit)(uint32_t module);
int32_t (* _modem_sleep_register)(uint32_t module);
int32_t (* _modem_sleep_deregister)(uint32_t module);
uint32_t (* _coex_status_get)(void);
void (* _coex_condition_set)(uint32_t type, bool dissatisfy);
int32_t (* _coex_wifi_request)(uint32_t event, uint32_t latency, uint32_t duration);
int32_t (* _coex_wifi_release)(uint32_t event);
int32_t _magic;
} wifi_osi_funcs_t;
extern wifi_osi_funcs_t g_wifi_osi_funcs;
#ifdef __cplusplus
}
#endif
#endif /* ESP_WIFI_OS_ADAPTER_H_ */
|
magic-mouse/NavComData | NavComData.h | <reponame>magic-mouse/NavComData
/*
NavComData - Library for controlling information
for flight simulation navigation and communication.
Created by <NAME>, December, 2019
Released into the public domain.
*/
#ifndef Morse_h
#define Morse_h
#include "Arduino.h"
class NavComData
{
public:
NavComData(String id);
void setMhz(short mhz);
void stepUpMhz();
void stepDownMhz();
void setKhz(short khz);
void stepUpKhz();
void stepDownKhz();
unsigned short getKhz();
unsigned short getMhz();
private:
unsigned short _mhz;
unsigned short _khz;
String _name;
};
#endif
|
Legendexo/Control-car | rf.h | <reponame>Legendexo/Control-car
#pragma once
#define DEFAULT_FREQ 40684300
#define DEFAULT_SAMPLE_RATE 2000000
#define DEFAULT_SYMBOL_RATE 2018
struct global_args_t {
int FREQ;
int SAMPLE_RATE;
int SYMBOL_RATE;
};
extern struct global_args_t rf_global_args;
enum Direction
{
fwd, fwd_left, fwd_right, back, back_left, back_right, left, right, none
};
struct direction_map_t {
/* order is critical here */
Direction fwd_left, fwd, fwd_right, left, none, right, back_left, back, back_right;
};
void set_direction_map(struct direction_map_t *map, bool invert_steering, bool invert_throttle, bool swap_axes);
bool init_rf();
void state_change(Direction dir, int gain_tx);
void close_rf();
|
anilallewar/iOS9-Swift2-Uber-Clone | Uber-Bridging-Header.h | <gh_stars>10-100
//
// Uber-Bridging-Header.h
// Uber
//
// Created by <NAME> on 12/16/15.
// Copyright © 2015 Parse. All rights reserved.
//
#ifndef Uber_Bridging_Header_h
#define Uber_Bridging_Header_h
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <ParseFacebookUtilsV4/PFFacebookUtils.h>
#endif /* Uber_Bridging_Header_h */
|
ctuu/rxcpp | include/rx.h | <gh_stars>1-10
#ifndef CTUU_RX_H_
#define CTUU_RX_H_
#include "async_subject.h"
#include "replay_subject.h"
#include "behavior_subject.h"
#include "subject.h"
#include "observable.h"
#include "subscriber.h"
#include "functor.h"
#include "of.h"
namespace rx
{
} // namespace rx
#endif |
ctuu/rxcpp | src/subject.h | <reponame>ctuu/rxcpp
#ifndef CTUU_RX_SUBJECT_H_
#define CTUU_RX_SUBJECT_H_
#include <any>
#include <list>
#include <memory>
#include "observable.h"
namespace rx
{
using subscri_list = std::list<subscriber>;
template <typename T>
class subject : public observable
{
private:
protected:
std::any thrown_error = NULL;
std::unique_ptr<subscri_list> subscribers;
virtual void _subscribe(const subscriber &subscriber)
{
if (closed)
throw std::runtime_error("UnsubscribedError");
else if (is_stopped)
subscriber.complete();
else if (has_error)
subscriber.error(thrown_error);
else
subscribers->emplace_back(subscriber);
}
public:
bool closed = false;
bool has_error = false;
bool is_stopped = false;
subject()
{
subscribers = std::make_unique<subscri_list>();
}
virtual void next(const T &value)
{
if (closed)
throw std::runtime_error("UnsubscribedError");
if (!is_stopped)
{
for (auto e : *subscribers)
e.next(value);
}
}
virtual void error(const std::any &err)
{
if (closed)
throw std::runtime_error("UnsubscribedError");
has_error = true;
thrown_error = err;
is_stopped = true;
for (auto e : *subscribers)
e.error(err);
subscribers->clear();
}
virtual void complete()
{
if (closed)
throw std::runtime_error("UnsubscribedError");
is_stopped = true;
for (auto e : *subscribers)
e.complete();
subscribers->clear();
}
virtual void unsubscribe()
{
is_stopped = true;
closed = true;
subscribers = nullptr;
}
};
} // namespace rx
#endif |
ctuu/rxcpp | src/replay_subject.h | <filename>src/replay_subject.h<gh_stars>1-10
#ifndef CTUU_RX_REPLAY_SUBJECT_H_
#define CTUU_RX_REPLAY_SUBJECT_H_
#include <list>
#include "subject.h"
namespace rx
{
template <typename T>
class replay_subject : public subject<T>
{
protected:
int buffer_size;
std::list<T> events;
void _subscribe(const subscriber &subscriber)
{
if (this->closed)
throw std::runtime_error("UnsubscribedError");
else if (!this->is_stopped && !this->has_error)
this->subscribers->emplace_back(subscriber);
for (auto i : events)
subscriber.next(i);
if (this->has_error)
subscriber.error(this->thrown_error);
else if (this->is_stopped)
subscriber.complete();
}
void trim_buffer()
{
int len = events.size();
while(len > buffer_size)
{
events.pop_front();
--len;
}
}
public:
replay_subject(const int &_buffer_size) : subject<T>()
{
buffer_size = _buffer_size < 1 ? 1 : _buffer_size;
}
virtual void next(const T &value)
{
events.emplace_back(value);
trim_buffer();
subject<T>::next(value);
}
};
} // namespace rx
#endif |
ctuu/rxcpp | src/subscriber.h | <reponame>ctuu/rxcpp
#ifndef CTUU_RX_SUBSCRIBER_H_
#define CTUU_RX_SUBSCRIBER_H_
#include "functor.h"
namespace rx
{
class subscriber
{
functor _next, _error, _complete;
public:
template <typename A, typename B = std::nullptr_t, typename C = std::nullptr_t>
subscriber(A _next, B _error = nullptr, C _complete = nullptr) : _next(_next), _error(_error), _complete(_complete){};
template <typename... Args>
void next(Args... args) const
{
_next(args...);
}
template <typename... Args>
void error(Args... args) const
{
_error(args...);
}
void complete() const;
};
} // namespace rx
#endif |
ctuu/rxcpp | src/of.h | #ifndef CTUU_RX_OF_H_
#define CTUU_RX_OF_H_
#include <initializer_list>
#include "observable.h"
namespace rx
{
template <typename T>
observable of(std::initializer_list<T> &&list)
{
return observable([list](auto &subscriber) {
for (auto i : list)
subscriber.next(i);
subscriber.complete();
});
}
} // namespace rx
#endif |
ctuu/rxcpp | src/async_subject.h | <gh_stars>1-10
#ifndef CTUU_RX_ASYNC_SUBJECT_H_
#define CTUU_RX_ASYNC_SUBJECT_H_
#include <list>
#include "subject.h"
namespace rx
{
template <typename T>
class async_subject : public subject<T>
{
protected:
T value;
void _subscribe(const subscriber &subscriber)
{
if (this->has_error)
subscriber.error(this->thrown_error);
else if (has_completed && has_next)
{
subscriber.next(value);
subscriber.complete();
}
else
subject<T>::_subscribe(subscriber);
}
public:
bool has_next = false;
bool has_completed = false;
virtual void next(const T &value)
{
if (!has_completed)
{
this->value = value;
has_next = true;
}
}
virtual void error(const std::any &err)
{
if (!has_completed)
subject<T>::error(err);
}
virtual void complete()
{
has_completed = true;
if (has_next)
subject<T>::next(value);
subject<T>::complete();
}
};
} // namespace rx
#endif |
ctuu/rxcpp | src/functor.h | <reponame>ctuu/rxcpp<gh_stars>1-10
#ifndef CTUU_RX_FUNCTOR_H_
#define CTUU_RX_FUNCTOR_H_
#include <any>
#include <functional>
#include <type_traits>
namespace rx::detail
{
template <typename T>
struct deduce_type;
template <typename RETURN_TYPE, typename CLASS_TYPE, typename... Args>
struct deduce_type<RETURN_TYPE (CLASS_TYPE::*)(Args...) const>
{
using type = std::function<RETURN_TYPE(Args...)>;
};
} // namespace rx::detail
namespace rx
{
class functor
{
private:
std::any func;
static std::nullptr_t wrap(const std::nullptr_t &fn);
template <typename RETURN_TYPE, typename... Args> // std::function
static auto wrap(const std::function<RETURN_TYPE(Args...)> &fn)
{
return fn;
}
template <typename RETURN_TYPE, typename... Args> // function pointer
static auto wrap(RETURN_TYPE (*fn)(Args...))
{
return std::function<RETURN_TYPE(Args...)>(fn);
}
template <typename CLOSURE>
static auto wrap(const CLOSURE &fn) // lambda expression
{
return typename detail::deduce_type<decltype(&CLOSURE::operator())>::type(fn);
} // from http://www.cplusplus.com/forum/general/223816/ @JLBorges
public:
bool is_null = true;
template <typename T>
functor(const T &_func)
{
is_null = std::is_same<T, std::nullptr_t>::value;
func = wrap(_func);
}
template <typename T>
functor &operator=(const T &_func)
{
is_null = std::is_same<T, std::nullptr_t>::value;
func = wrap(_func);
return *this;
}
template <typename RETURN_TYPE = void, typename... Args>
typename std::enable_if<std::is_void<RETURN_TYPE>::value, RETURN_TYPE>::type operator()(Args... args) const
{
if (!is_null)
std::invoke(std::any_cast<std::function<RETURN_TYPE(Args...)>>(func), args...);
}
template <typename RETURN_TYPE = void, typename... Args>
typename std::enable_if<!std::is_void<RETURN_TYPE>::value, RETURN_TYPE>::type operator()(Args... args) const
{
return std::invoke(std::any_cast<std::function<RETURN_TYPE(Args...)>>(func), args...);
}
template <typename RETURN_TYPE = void, typename... Args>
typename std::enable_if<std::is_void<RETURN_TYPE>::value, RETURN_TYPE>::type invoke(Args... args) const
{
if (!is_null)
std::invoke(std::any_cast<std::function<RETURN_TYPE(Args...)>>(func), args...);
}
template <typename RETURN_TYPE = void, typename... Args>
typename std::enable_if<!std::is_void<RETURN_TYPE>::value, RETURN_TYPE>::type invoke(Args... args) const
{
return std::invoke(std::any_cast<std::function<RETURN_TYPE(Args...)>>(func), args...);
}
};
} // namespace rx
#endif |
ctuu/rxcpp | src/observable.h | <reponame>ctuu/rxcpp
#ifndef CTUU_RX_OBSERVABLE_H_
#define CTUU_RX_OBSERVABLE_H_
#include <functional>
#include "subscriber.h"
namespace rx
{
using subscriber_function = std::function<void(const subscriber &)>;
class observable
{
private:
subscriber_function __subscribe;
protected:
virtual void _subscribe(const subscriber &);
public:
observable() = default;
observable(const subscriber_function &subscriber);
void subscribe(const subscriber &);
template <typename A, typename B = std::nullptr_t, typename C = std::nullptr_t>
void subscribe(const A &_next = nullptr, const B &_error = nullptr, const C &_complete = nullptr)
{
auto e = subscriber(_next, _error, _complete);
this->subscribe(e);
}
};
} // namespace rx
#endif |
ctuu/rxcpp | src/behavior_subject.h | #ifndef CTUU_RX_BEHAVIOR_SUBJECT_H_
#define CTUU_RX_BEHAVIOR_SUBJECT_H_
#include "subject.h"
namespace rx
{
template <typename T>
class behavior_subject : public subject<T>
{
protected:
T prev_value;
void _subscribe(const subscriber &subscriber)
{
subject<T>::_subscribe(subscriber);
subscriber.next(prev_value);
}
public:
behavior_subject(const T &value) : prev_value(value), subject<T>() {}
T get_value()
{
if (this->closed)
throw std::runtime_error("UnsubscribedError");
else
return prev_value;
}
virtual void next(const T &value)
{
subject<T>::next(prev_value = value);
}
};
} // namespace rx
#endif |
jtenner/lucet | lucet-runtime/tests/c_api.c | #include <stdbool.h>
#include <stdio.h>
#include "lucet.h"
bool lucet_runtime_test_expand_heap(struct lucet_dl_module *mod)
{
struct lucet_region * region;
struct lucet_alloc_limits limits = {
.heap_memory_size = 4 * 1024 * 1024,
.heap_address_space_size = 8 * 1024 * 1024,
.stack_size = 64 * 1024,
.globals_size = 4096,
};
enum lucet_error err;
err = lucet_mmap_region_create(1, &limits, ®ion);
if (err != lucet_error_ok) {
fprintf(stderr, "failed to create region\n");
goto fail1;
}
struct lucet_instance *inst;
err = lucet_region_new_instance(region, mod, &inst);
if (err != lucet_error_ok) {
fprintf(stderr, "failed to create instance\n");
goto fail2;
}
uint32_t newpage_start;
err = lucet_instance_grow_heap(inst, 1, &newpage_start);
if (err != lucet_error_ok) {
fprintf(stderr, "failed to grow memory\n");
goto fail3;
}
lucet_region_release(region);
lucet_dl_module_release(mod);
return true;
fail3:
lucet_instance_release(inst);
fail2:
lucet_region_release(region);
fail1:
lucet_dl_module_release(mod);
return false;
}
|
jtenner/lucet | lucet-idl/tests/example_driver.c | #include <stdlib.h>
#include <assert.h>
#include "example.h"
int main (int argc, char *argv[]) {
enum color c1 = COLOR_RED;
colour c2 = COLOR_BLUE;
col c3 = COLOR_GREEN;
struct st s = {
.a = 0,
.b = 123,
.c = COLOR_RED,
};
return 0;
}
|
swig-fortran/flibcpp | test/fassert.h | <filename>test/fassert.h
#define ASSERT(COND) \
if(.not.(COND))then;print*,"Failure:",__LINE__;stop 1;end if
|
LiuShulong/sltlocaltools | test/fixtures/find/ViewController.h |
##define name1 @"我是接口d"; |
eda-ricercatore/scafati-presentazioni | ieee-amp/simple-simon/src/memory_game_code.c | #define PLAYER_WAIT_TIME 2000 // The time allowed between button presses - 2s
byte sequence[100]; // Storage for the light sequence
byte curLen = 0; // Current length of the sequence
byte inputCount = 0; // The number of times that the player has pressed a (correct) button in a given turn
byte lastInput = 0; // Last input from the player
byte expRd = 0; // The LED that's suppose to be lit by the player
bool btnDwn = false; // Used to check if a button is pressed
bool wait = false; // Is the program waiting for the user to press a button
bool resetFlag = false; // Used to indicate to the program that once the player lost
byte soundPin = 5; // Speaker output
byte noPins = 4; // Number of buttons/LEDs (While working on this, I was using only 2 LEDs)
// You could make the game harder by adding an additional LED/button/resistors combination.
byte pins[] = {2, 13, 10, 8}; // Button input pins and LED ouput pins - change these vaules if you wwant to connect your buttons to other pins
// The number of elements must match noPins below
long inputTime = 0; // Timer variable for the delay between user inputs
void setup() {
delay(3000); // This is to give me time to breathe after connection the arduino - can be removed if you want
Serial.begin(9600); // Start Serial monitor. This can be removed too as long as you remove all references to Serial below
Reset();
}
///
/// Sets all the pins as either INPUT or OUTPUT based on the value of 'dir'
///
void setPinDirection(byte dir){
for(byte i = 0; i < noPins; i++){
pinMode(pins[i], dir);
}
}
//send the same value to all the LED pins
void writeAllPins(byte val){
for(byte i = 0; i < noPins; i++){
digitalWrite(pins[i], val);
}
}
//Makes a (very annoying :) beep sound
void beep(byte freq){
analogWrite(soundPin, 2);
delay(freq);
analogWrite(soundPin, 0);
delay(freq);
}
///
/// Flashes all the LEDs together
/// freq is the blink speed - small number -> fast | big number -> slow
///
void flash(short freq){
setPinDirection(OUTPUT); /// We're activating the LEDS now
for(int i = 0; i < 5; i++){
writeAllPins(HIGH);
beep(50);
delay(freq);
writeAllPins(LOW);
delay(freq);
}
}
///
///This function resets all the game variables to their default values
///
void Reset(){
flash(500);
curLen = 0;
inputCount = 0;
lastInput = 0;
expRd = 0;
btnDwn = false;
wait = false;
resetFlag = false;
}
///
/// User lost
///
void Lose(){
flash(50);
}
///
/// The arduino shows the user what must be memorized
/// Also called after losing to show you what you last sequence was
///
void playSequence(){
//Loop through the stored sequence and light the appropriate LEDs in turn
for(int i = 0; i < curLen; i++){
Serial.print("Seq: ");
Serial.print(i);
Serial.print("Pin: ");
Serial.println(sequence[i]);
digitalWrite(sequence[i], HIGH);
delay(500);
digitalWrite(sequence[i], LOW);
delay(250);
}
}
///
/// The events that occur upon a loss
///
void DoLoseProcess(){
Lose(); // Flash all the LEDS quickly (see Lose function)
delay(1000);
playSequence(); // Shows the user the last sequence - So you can count remember your best score - Mine's 22 by the way :)
delay(1000);
Reset(); // Reset everything for a new game
}
///
/// Where the magic happens
///
void loop() {
if(!wait){
//****************//
// Arduino's turn //
//****************//
setPinDirection(OUTPUT); // We're using the LEDs
randomSeed(analogRead(A0)); // https://www.arduino.cc/en/Reference/RandomSeed
sequence[curLen] = pins[random(0,noPins)]; // Put a new random value in the next position in the sequence - https://www.arduino.cc/en/Reference/random
curLen++; // Set the new Current length of the sequence
playSequence(); // Show the sequence to the player
beep(50); // Make a beep for the player to be aware
wait = true; // Set Wait to true as it's now going to be the turn of the player
inputTime = millis(); // Store the time to measure the player's response time
}else{
//***************//
// Player's turn //
//***************//
setPinDirection(INPUT); // We're using the buttons
if(millis() - inputTime > PLAYER_WAIT_TIME){ // If the player takes more than the allowed time,
DoLoseProcess(); // All is lost :(
return;
}
if(!btnDwn){ //
expRd = sequence[inputCount]; // Find the value we expect from the player
Serial.print("Expected: "); // Serial Monitor Output - Should be removed if you removed the Serial.begin above
Serial.println(expRd); // Serial Monitor Output - Should be removed if you removed the Serial.begin above
for(int i = 0; i <= noPins; i++){ // Loop through the all the pins
if(pins[i]==expRd)
continue; // Ignore the correct pin
if(digitalRead(pins[i]) == HIGH){ // Is the buttong pressed
lastInput = pins[i];
resetFlag = true; // Set the resetFlag - this means you lost
btnDwn = true; // This will prevent the program from doing the same thing over and over again
Serial.print("Read: "); // Serial Monitor Output - Should be removed if you removed the Serial.begin above
Serial.println(lastInput); // Serial Monitor Output - Should be removed if you removed the Serial.begin above
}
}
}
if(digitalRead(expRd) == 1 && !btnDwn) // The player pressed the right button
{
inputTime = millis(); //
lastInput = expRd;
inputCount++; // The user pressed a (correct) button again
btnDwn = true; // This will prevent the program from doing the same thing over and over again
Serial.print("Read: "); // Serial Monitor Output - Should be removed if you removed the Serial.begin above
Serial.println(lastInput); // Serial Monitor Output - Should be removed if you removed the Serial.begin above
}else{
if(btnDwn && digitalRead(lastInput) == LOW){ // Check if the player released the button
btnDwn = false;
delay(20);
if(resetFlag){ // If this was set to true up above, you lost
DoLoseProcess(); // So we do the losing sequence of events
}
else{
if(inputCount == curLen){ // Has the player finished repeating the sequence
wait = false; // If so, this will make the next turn the program's turn
inputCount = 0; // Reset the number of times that the player has pressed a button
delay(1500);
}
}
}
}
}
}
|
kmongo/linked_list | algo.c | <gh_stars>0
#include <stdio.h>
#include <stdlib.h>
#define FALSE 0
#define TRUE 1
int power3(int val){
int temp = val;
while (temp%3 == 0)
temp = temp / 3;
// printf("power3=%d\n", temp);
if (temp == 1)
return TRUE;
else
return FALSE;
}
int div2(int val){
int temp = val;
while (temp%2 == 0)
temp = temp / 2;
// printf("div2=%d\n", temp);
return temp;
}
int main(){
int num,temp,result;
int count = -1;
int pos = 0;
printf("input numbers?\n");
scanf("%d",&num);
while(count < num){
pos++;
temp = div2(pos);
// printf("after div2=%d\n", temp);
result = power3(temp);
// printf("OK=%d\n", result);
if(result == TRUE)
count++;
// printf("pos=%d, count=%d\n\n", pos, count);
}
printf("answer=%d\n", pos);
}
|
kmongo/linked_list | queue_linked.c | <gh_stars>0
#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int val;
struct Node* next;
}Node;
Node *front = NULL;
Node *rear = NULL;
void enQueue(int val){
Node *temp = (Node*)malloc(sizeof(Node));
temp->val = val;
temp->next = NULL;
if(front == NULL && rear == NULL){
front = rear = temp;
return;
}
rear->next = temp;
rear = temp;
}
void PRINT(){
Node *temp = front;
while(temp != NULL){
printf("%d ",temp->val);
temp = temp->next;
}
printf("\n");
}
void deQueue(){
if(front == NULL)
return;
if(rear == front)
rear = front = NULL;
Node *temp = front;
front = front->next;
ree(temp);
}
int main(){
Node *head = NULL;
enQueue(4);
enQueue(5);
enQueue(10);
enQueue(33);
enQueue(21);
enQueue(234);
enQueue(122);
enQueue(9);
PRINT(head);
deQueue();
deQueue();
deQueue();
deQueue();
deQueue();
PRINT(head);
}
|
kmongo/linked_list | stack_linked.c | #include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int val;
struct Node *next;
}Node;
Node* Push(Node *p, int val){
Node *temp = (struct Node*)malloc(sizeof(struct Node));
temp->val = val;
temp->next = p;
p = temp;
return p;
}
Node* Pop(Node *p){
if(p == NULL)
return;
Node *temp = p;
p = p->next;
free(temp);
return p;
}
void PRINT(Node *p){
Node *temp = p;
while(temp != NULL){
printf("%d ",temp->val);
temp = temp->next;
}
printf("\n");
}
int main(){
Node *head = NULL;
head = Push(head,3);
head = Push(head,6);
head = Push(head,2);
head = Push(head,1);
head = Push(head,9);
PRINT(head);
head = Pop(head);
head = Pop(head);
head = Pop(head);
PRINT(head);
}
|
kmongo/linked_list | qsort.c | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX 10
#define SWAP(x,y) {int t; t = x; x = y; y = t;}
int partition(int[], int, int);
void quickSort(int[], int, int);
int main(void) {
srand(time(NULL));
int number[MAX] = {0};
printf("排序前:");
int i;
for(i = 0; i < MAX; i++) {
number[i] = rand() % 100;
printf("%d ", number[i]);
}
printf("\n");
quickSort(number, 0, MAX-1);
printf("\n排序後:");
for(i = 0; i < MAX; i++)
printf("%d ", number[i]);
printf("\n");
return 0;
}
int partition(int number[], int left, int right) {
int i = left - 1;
int j;
for(j = left; j < right; j++) {
if(number[j] <= number[right]) {
i++;
SWAP(number[i], number[j]);
}
}
printf("i = %d\n",i);
SWAP(number[i+1], number[right]);
printf("i = %d\n",i);
return i+1;
}
void quickSort(int *number, int left, int right) {
int i;
if(left < right) {
int q = partition(number, left, right);
for(i = 0; i < MAX; i++)
printf("%d ", number[i]);
printf("\n");
quickSort(number, left, q-1);
quickSort(number, q+1, right);
}
}
|
kmongo/linked_list | likedlist.c | <gh_stars>0
#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int val;
struct Node* next;
}Node;
Node *head = NULL;
void insertToTail(int val){
Node* temp = (Node*)malloc(sizeof(Node));
temp->val = val;
temp->next = NULL;
if(head == NULL){
temp->next = head;
head = temp;
return;
}
Node *temp2 = head;
while(temp2->next != NULL)
temp2 = temp2->next;
temp->next = NULL;
temp2->next = temp;
}
void insertToFront(int val){
Node* temp = (Node*)malloc(sizeof(Node));
temp->val = val;
temp->next = head;
head = temp;
}
void deleteN(int n){
Node *temp = head;
if(n == 1){
head = head->next;
free(temp);
return;
}
int i;
for(i = 0;i < n-2;i++){
temp = temp->next;
}
Node *temp2 = temp->next;
temp->next = temp2->next;
free(temp2);
}
void clear(){
while(head != NULL){
Node *temp = head;
head = head->next;
free(temp);
}
}
void Print(){
Node *temp = head;
if(temp == NULL){
printf("no member in this list\n");
return;
}
while(temp != NULL){
printf("%d ", temp->val);
temp = temp->next;
}
printf("\n");
}
void reverseByIter(){
Node *current,*next,*prev;
current = head;
prev = NULL;
while(current != NULL){
next = current->next;
current->next = prev;
prev = current;
current = next;
}
head = prev;
}
void reverseByRecu(Node *p){
if(p == NULL || p->next == NULL){
head = p;
return;
}
reverseByRecu(p->next);
p->next->next = p;
p->next = NULL;
}
Node *reverseByRecu_2(Node *p){
if(p == NULL || p->next == NULL){
return p;
}
Node* temp = reverseByRecu_2(p->next);
p->next->next = p;
p->next = NULL;
return temp;
}
int main(){
insertToFront(2);
insertToFront(100);
insertToFront(234);
insertToFront(32);
insertToFront(50);
insertToFront(99);
Print();
reverseByRecu(head);
Print();
reverseByRecu_2(head);
Print();
}
|
kmongo/linked_list | sqrt.c | <gh_stars>0
#include <stdio.h>
#include <stdlib.h>
int main(){
double x = 1;
double num = 121;
double y = 1.0 / 2 * (x + num/x);
while(fabs(y-x) > 1e-5){
x = y;
y = 1.0 / 2 * (x + num/x);
}
printf("%.3lf\n",y);
}
|
TokyoRobotics/choreonoid | src/BodyPlugin/KinematicBodyItemSet.h | <filename>src/BodyPlugin/KinematicBodyItemSet.h
#ifndef CNOID_BODY_PLUGIN_KINEMATIC_BODY_ITEM_SET_H
#define CNOID_BODY_PLUGIN_KINEMATIC_BODY_ITEM_SET_H
#include <cnoid/KinematicBodySet>
#include "exportdecl.h"
namespace cnoid {
class BodyItem;
class CNOID_EXPORT KinematicBodyItemSet : public KinematicBodySet
{
public:
KinematicBodyItemSet();
void setBodyItem(const GeneralId& partId, BodyItem* bodyItem);
BodyItem* bodyItem(const GeneralId& partId);
protected:
KinematicBodyItemSet(const KinematicBodyItemSet& org, CloneMap* cloneMap);
virtual Referenced* doClone(CloneMap* cloneMap) const override;
private:
void copyBodyPart(BodyPart* newBodyPart, BodyPart* orgBodyPart, CloneMap* cloneMap);
void initializeBodyPart(BodyPart* bodyPart, BodyItem* bodyItem);
};
typedef ref_ptr<KinematicBodyItemSet> KinematicBodyItemSetPtr;
}
#endif
|
TokyoRobotics/choreonoid | src/Body/KinematicBodySet.h | #ifndef CNOID_BODY_KINEMATIC_BODY_SET_H
#define CNOID_BODY_KINEMATIC_BODY_SET_H
#include "LinkKinematicsKit.h"
#include <cnoid/GeneralId>
#include <cnoid/ConnectionSet>
#include <functional>
#include "exportdecl.h"
namespace cnoid {
class CNOID_EXPORT KinematicBodySet : public ClonableReferenced
{
public:
KinematicBodySet();
KinematicBodySet(const KinematicBodySet& org, CloneMap* cloneMap);
~KinematicBodySet();
void setBodyPart(const GeneralId& partId, LinkKinematicsKit* kit);
void clear();
void clearBodyPart(const GeneralId& partId);
int numKinematicBodyParts() const;
LinkKinematicsKit* kinematicsKit(const GeneralId& partId);
void setMainBodyPartId(const GeneralId& partId);
const GeneralId& mainBodyPartId() const;
LinkKinematicsKit* mainKinematicsKit();
//! The signal is emitted when any sub kinematics kit emits the same signal.
SignalProxy<void()> sigFrameSetChange();
//! The signal is emitted when any sub kinematics kit emits the same signal.
SignalProxy<void(const Isometry3& T_frameCoordinate)> sigPositionError();
class BodyPart : public Referenced
{
LinkKinematicsKitPtr kinematicsKit;
ScopedConnectionSet connections;
friend class KinematicBodySet;
};
protected:
typedef std::function<BodyPart*()> CreateBodyPartFunc;
typedef std::function<void(BodyPart* newBodyPart, BodyPart* orgBodyPart, CloneMap* cloneMap)> CopyBodyPartFunc;
KinematicBodySet(CreateBodyPartFunc createBodyPart, CopyBodyPartFunc copyBodyPart);
virtual Referenced* doClone(CloneMap* cloneMap) const override;
void copyBodyPart(BodyPart* newBodyPart, BodyPart* orgBodyPart, CloneMap* cloneMap);
void initializeBodyPart(BodyPart* bodyPart, LinkKinematicsKit* kinematicsKit);
BodyPart* findBodyPart(const GeneralId& partId);
BodyPart* findOrCreateBodyPart(const GeneralId& partId);
private:
class Impl;
Impl* impl;
};
typedef ref_ptr<KinematicBodySet> KinematicBodySetPtr;
}
#endif
|
LEGaTO-SmartMirror/darknet-ompss | src/gettimeofday.c | <reponame>LEGaTO-SmartMirror/darknet-ompss
#ifdef _WIN32
#include "gettimeofday.h"
int gettimeofday(struct timeval* tp, struct timezone* tzp)
{
static const uint64_t EPOCH = ((uint64_t)116444736000000000ULL);
SYSTEMTIME system_time;
FILETIME file_time;
uint64_t time;
GetSystemTime(&system_time);
SystemTimeToFileTime(&system_time, &file_time);
time = ((uint64_t)file_time.dwLowDateTime);
time += ((uint64_t)file_time.dwHighDateTime) << 32;
/*converting file time to unix epoch*/
tp->tv_sec = (long)((time - EPOCH) / 10000000L);
tp->tv_usec = (long)(system_time.wMilliseconds * 1000);
return 0;
}
int clock_gettime(int dummy, struct timespec* ct)
{
LARGE_INTEGER count;
if (g_first_time) {
g_first_time = 0;
if (0 == QueryPerformanceFrequency(&g_counts_per_sec)) {
g_counts_per_sec.QuadPart = 0;
}
}
if ((NULL == ct) || (g_counts_per_sec.QuadPart <= 0) || (0 == QueryPerformanceCounter(&count))) {
return -1;
}
ct->tv_sec = count.QuadPart / g_counts_per_sec.QuadPart;
ct->tv_nsec = ((count.QuadPart % g_counts_per_sec.QuadPart) * BILLION) / g_counts_per_sec.QuadPart;
return 0;
}
#endif
|
LEGaTO-SmartMirror/darknet-ompss | src/yolo_layer.h | <reponame>LEGaTO-SmartMirror/darknet-ompss
#ifndef YOLO_LAYER_H
#define YOLO_LAYER_H
//#include "darknet.h"
#include "layer.h"
#include "network.h"
#ifdef __cplusplus
extern "C" {
#endif
layer make_yolo_layer(int batch, int w, int h, int n, int total, int *mask, int classes, int max_boxes);
void forward_yolo_layer(const layer l, network_state state);
void backward_yolo_layer(const layer l, network_state state);
void resize_yolo_layer(layer *l, int w, int h);
int yolo_num_detections(layer l, float thresh);
int get_yolo_detections(layer l, int w, int h, int netw, int neth, float thresh, int *map, int relative, detection *dets, int letter);
void correct_yolo_boxes(detection *dets, int n, int w, int h, int netw, int neth, int relative, int letter);
#ifdef GPU
void forward_yolo_layer_gpu(const layer l, network_state state);
void backward_yolo_layer_gpu(layer l, network_state state);
#endif
#ifdef __cplusplus
}
#endif
#endif
|
LEGaTO-SmartMirror/darknet-ompss | src/layer.c | <gh_stars>0
#include "layer.h"
#include "dark_cuda.h"
#include <stdlib.h>
void free_sublayer(layer *l)
{
if (l) {
free_layer(*l);
free(l);
}
}
void free_layer(layer l)
{
free_layer_custom(l, 0);
}
void free_layer_custom(layer l, int keep_cudnn_desc)
{
if (l.share_layer != NULL) return; // don't free shared layers
if (l.antialiasing) {
free_sublayer(l.input_layer);
}
if (l.type == CONV_LSTM) {
if (l.peephole) {
free_sublayer(l.vf);
free_sublayer(l.vi);
free_sublayer(l.vo);
}
else {
free(l.vf);
free(l.vi);
free(l.vo);
}
free_sublayer(l.wf);
free_sublayer(l.wi);
free_sublayer(l.wg);
free_sublayer(l.wo);
free_sublayer(l.uf);
free_sublayer(l.ui);
free_sublayer(l.ug);
free_sublayer(l.uo);
}
if (l.type == CRNN) {
free_sublayer(l.input_layer);
free_sublayer(l.self_layer);
free_sublayer(l.output_layer);
l.output = NULL;
l.delta = NULL;
#ifdef GPU
l.output_gpu = NULL;
l.delta_gpu = NULL;
#endif // GPU
}
if (l.type == DROPOUT) {
if (l.rand) free(l.rand);
#ifdef GPU
if (l.rand_gpu) cuda_free(l.rand_gpu);
#endif
return;
}
if (l.mask) free(l.mask);
if (l.classes_multipliers)free(l.classes_multipliers);
if (l.cweights) free(l.cweights);
if (l.indexes) free(l.indexes);
if (l.input_layers) free(l.input_layers);
if (l.input_sizes) free(l.input_sizes);
if (l.layers_output) free(l.layers_output);
if (l.layers_delta) free(l.layers_delta);
if (l.map) free(l.map);
if (l.rand) free(l.rand);
if (l.cost) free(l.cost);
if (l.state) free(l.state);
if (l.prev_state) free(l.prev_state);
if (l.forgot_state) free(l.forgot_state);
if (l.forgot_delta) free(l.forgot_delta);
if (l.state_delta) free(l.state_delta);
if (l.concat) free(l.concat);
if (l.concat_delta) free(l.concat_delta);
if (l.binary_weights) free(l.binary_weights);
if (l.biases) free(l.biases), l.biases = NULL;
if (l.bias_updates) free(l.bias_updates), l.bias_updates = NULL;
if (l.scales) free(l.scales), l.scales = NULL;
if (l.scale_updates) free(l.scale_updates), l.scale_updates = NULL;
if (l.weights) free(l.weights), l.weights = NULL;
if (l.weight_updates) free(l.weight_updates), l.weight_updates = NULL;
if (l.align_bit_weights) free(l.align_bit_weights);
if (l.mean_arr) free(l.mean_arr);
#ifdef GPU
if (l.delta && l.delta_pinned) {
cudaFreeHost(l.delta);
l.delta = NULL;
}
if (l.output && l.output_pinned) {
cudaFreeHost(l.output);
l.output = NULL;
}
#endif // GPU
if (l.delta) free(l.delta), l.delta = NULL;
if (l.output) free(l.output), l.output = NULL;
if (l.activation_input) free(l.activation_input), l.activation_input = NULL;
if (l.squared) free(l.squared);
if (l.norms) free(l.norms);
if (l.spatial_mean) free(l.spatial_mean);
if (l.mean) free(l.mean), l.mean = NULL;
if (l.variance) free(l.variance), l.variance = NULL;
if (l.mean_delta) free(l.mean_delta), l.mean_delta = NULL;
if (l.variance_delta) free(l.variance_delta), l.variance_delta = NULL;
if (l.rolling_mean) free(l.rolling_mean), l.rolling_mean = NULL;
if (l.rolling_variance) free(l.rolling_variance), l.rolling_variance = NULL;
if (l.x) free(l.x);
if (l.x_norm) free(l.x_norm);
if (l.m) free(l.m);
if (l.v) free(l.v);
if (l.z_cpu) free(l.z_cpu);
if (l.r_cpu) free(l.r_cpu);
if (l.binary_input) free(l.binary_input);
if (l.bin_re_packed_input) free(l.bin_re_packed_input);
if (l.t_bit_input) free(l.t_bit_input);
if (l.loss) free(l.loss);
// CONV-LSTM
if (l.f_cpu) free(l.f_cpu);
if (l.i_cpu) free(l.i_cpu);
if (l.g_cpu) free(l.g_cpu);
if (l.o_cpu) free(l.o_cpu);
if (l.c_cpu) free(l.c_cpu);
if (l.h_cpu) free(l.h_cpu);
if (l.temp_cpu) free(l.temp_cpu);
if (l.temp2_cpu) free(l.temp2_cpu);
if (l.temp3_cpu) free(l.temp3_cpu);
if (l.dc_cpu) free(l.dc_cpu);
if (l.dh_cpu) free(l.dh_cpu);
if (l.prev_state_cpu) free(l.prev_state_cpu);
if (l.prev_cell_cpu) free(l.prev_cell_cpu);
if (l.stored_c_cpu) free(l.stored_c_cpu);
if (l.stored_h_cpu) free(l.stored_h_cpu);
if (l.cell_cpu) free(l.cell_cpu);
#ifdef GPU
if (l.indexes_gpu) cuda_free((float *)l.indexes_gpu);
if (l.z_gpu) cuda_free(l.z_gpu);
if (l.r_gpu) cuda_free(l.r_gpu);
if (l.m_gpu) cuda_free(l.m_gpu);
if (l.v_gpu) cuda_free(l.v_gpu);
if (l.forgot_state_gpu) cuda_free(l.forgot_state_gpu);
if (l.forgot_delta_gpu) cuda_free(l.forgot_delta_gpu);
if (l.state_gpu) cuda_free(l.state_gpu);
if (l.state_delta_gpu) cuda_free(l.state_delta_gpu);
if (l.gate_gpu) cuda_free(l.gate_gpu);
if (l.gate_delta_gpu) cuda_free(l.gate_delta_gpu);
if (l.save_gpu) cuda_free(l.save_gpu);
if (l.save_delta_gpu) cuda_free(l.save_delta_gpu);
if (l.concat_gpu) cuda_free(l.concat_gpu);
if (l.concat_delta_gpu) cuda_free(l.concat_delta_gpu);
if (l.binary_input_gpu) cuda_free(l.binary_input_gpu);
if (l.binary_weights_gpu) cuda_free(l.binary_weights_gpu);
if (l.mean_gpu) cuda_free(l.mean_gpu), l.mean_gpu = NULL;
if (l.variance_gpu) cuda_free(l.variance_gpu), l.variance_gpu = NULL;
if (l.rolling_mean_gpu) cuda_free(l.rolling_mean_gpu), l.rolling_mean_gpu = NULL;
if (l.rolling_variance_gpu) cuda_free(l.rolling_variance_gpu), l.rolling_variance_gpu = NULL;
if (l.variance_delta_gpu) cuda_free(l.variance_delta_gpu), l.variance_delta_gpu = NULL;
if (l.mean_delta_gpu) cuda_free(l.mean_delta_gpu), l.mean_delta_gpu = NULL;
if (l.x_norm_gpu) cuda_free(l.x_norm_gpu);
// assisted excitation
if (l.gt_gpu) cuda_free(l.gt_gpu);
if (l.a_avg_gpu) cuda_free(l.a_avg_gpu);
if (l.align_bit_weights_gpu) cuda_free((float *)l.align_bit_weights_gpu);
if (l.mean_arr_gpu) cuda_free(l.mean_arr_gpu);
if (l.align_workspace_gpu) cuda_free(l.align_workspace_gpu);
if (l.transposed_align_workspace_gpu) cuda_free(l.transposed_align_workspace_gpu);
if (l.weights_gpu) cuda_free(l.weights_gpu), l.weights_gpu = NULL;
if (l.weight_updates_gpu) cuda_free(l.weight_updates_gpu), l.weight_updates_gpu = NULL;
if (l.weight_deform_gpu) cuda_free(l.weight_deform_gpu), l.weight_deform_gpu = NULL;
if (l.weights_gpu16) cuda_free(l.weights_gpu16), l.weights_gpu16 = NULL;
if (l.weight_updates_gpu16) cuda_free(l.weight_updates_gpu16), l.weight_updates_gpu16 = NULL;
if (l.biases_gpu) cuda_free(l.biases_gpu), l.biases_gpu = NULL;
if (l.bias_updates_gpu) cuda_free(l.bias_updates_gpu), l.bias_updates_gpu = NULL;
if (l.scales_gpu) cuda_free(l.scales_gpu), l.scales_gpu = NULL;
if (l.scale_updates_gpu) cuda_free(l.scale_updates_gpu), l.scale_updates_gpu = NULL;
if (l.input_antialiasing_gpu) cuda_free(l.input_antialiasing_gpu), l.input_antialiasing_gpu = NULL;
if (l.optimized_memory < 2) {
if (l.x_gpu) cuda_free(l.x_gpu); l.x_gpu = NULL;
if (l.output_gpu) cuda_free(l.output_gpu), l.output_gpu = NULL;
if (l.activation_input_gpu) cuda_free(l.activation_input_gpu), l.activation_input_gpu = NULL;
}
if (l.delta_gpu && l.keep_delta_gpu && l.optimized_memory < 3) cuda_free(l.delta_gpu), l.delta_gpu = NULL;
if (l.rand_gpu) cuda_free(l.rand_gpu);
if (l.squared_gpu) cuda_free(l.squared_gpu);
if (l.norms_gpu) cuda_free(l.norms_gpu);
if (l.input_sizes_gpu) cuda_free((float*)l.input_sizes_gpu);
if (l.layers_output_gpu) cuda_free((float*)l.layers_output_gpu);
if (l.layers_delta_gpu) cuda_free((float*)l.layers_delta_gpu);
// CONV-LSTM
if (l.f_gpu) cuda_free(l.f_gpu);
if (l.i_gpu) cuda_free(l.i_gpu);
if (l.g_gpu) cuda_free(l.g_gpu);
if (l.o_gpu) cuda_free(l.o_gpu);
if (l.c_gpu) cuda_free(l.c_gpu);
if (l.h_gpu) cuda_free(l.h_gpu);
if (l.temp_gpu) cuda_free(l.temp_gpu);
if (l.temp2_gpu) cuda_free(l.temp2_gpu);
if (l.temp3_gpu) cuda_free(l.temp3_gpu);
if (l.dc_gpu) cuda_free(l.dc_gpu);
if (l.dh_gpu) cuda_free(l.dh_gpu);
if (l.prev_state_gpu) cuda_free(l.prev_state_gpu);
if (l.prev_cell_gpu) cuda_free(l.prev_cell_gpu);
if (l.stored_c_gpu) cuda_free(l.stored_c_gpu);
if (l.stored_h_gpu) cuda_free(l.stored_h_gpu);
if (l.last_prev_state_gpu) cuda_free(l.last_prev_state_gpu);
if (l.last_prev_cell_gpu) cuda_free(l.last_prev_cell_gpu);
if (l.cell_gpu) cuda_free(l.cell_gpu);
#ifdef CUDNN // shouldn't be used for -map
if (!keep_cudnn_desc) {
if (l.srcTensorDesc) CHECK_CUDNN(cudnnDestroyTensorDescriptor(l.srcTensorDesc));
if (l.dstTensorDesc) CHECK_CUDNN(cudnnDestroyTensorDescriptor(l.dstTensorDesc));
if (l.srcTensorDesc16) CHECK_CUDNN(cudnnDestroyTensorDescriptor(l.srcTensorDesc16));
if (l.dstTensorDesc16) CHECK_CUDNN(cudnnDestroyTensorDescriptor(l.dstTensorDesc16));
if (l.dsrcTensorDesc) CHECK_CUDNN(cudnnDestroyTensorDescriptor(l.dsrcTensorDesc));
if (l.ddstTensorDesc) CHECK_CUDNN(cudnnDestroyTensorDescriptor(l.ddstTensorDesc));
if (l.dsrcTensorDesc16) CHECK_CUDNN(cudnnDestroyTensorDescriptor(l.dsrcTensorDesc16));
if (l.ddstTensorDesc16) CHECK_CUDNN(cudnnDestroyTensorDescriptor(l.ddstTensorDesc16));
if (l.normTensorDesc) CHECK_CUDNN(cudnnDestroyTensorDescriptor(l.normTensorDesc));
if (l.normDstTensorDesc) CHECK_CUDNN(cudnnDestroyTensorDescriptor(l.normDstTensorDesc));
if (l.normDstTensorDescF16) CHECK_CUDNN(cudnnDestroyTensorDescriptor(l.normDstTensorDescF16));
if (l.weightDesc) CHECK_CUDNN(cudnnDestroyFilterDescriptor(l.weightDesc));
if (l.weightDesc16) CHECK_CUDNN(cudnnDestroyFilterDescriptor(l.weightDesc16));
if (l.dweightDesc) CHECK_CUDNN(cudnnDestroyFilterDescriptor(l.dweightDesc));
if (l.dweightDesc16) CHECK_CUDNN(cudnnDestroyFilterDescriptor(l.dweightDesc16));
if (l.convDesc) CHECK_CUDNN(cudnnDestroyConvolutionDescriptor(l.convDesc));
if (l.poolingDesc) CHECK_CUDNN(cudnnDestroyPoolingDescriptor(l.poolingDesc));
//cudnnConvolutionFwdAlgo_t fw_algo, fw_algo16;
//cudnnConvolutionBwdDataAlgo_t bd_algo, bd_algo16;
//cudnnConvolutionBwdFilterAlgo_t bf_algo, bf_algo16;
}
#endif // CUDNN
#endif // GPU
}
|
LEGaTO-SmartMirror/darknet-ompss | src/gettimeofday.h | #ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <stdint.h>
#include <time.h>
#include "darknet.h"
#define CLOCK_REALTIME (1)
#define BILLION (1E9)
#ifndef timersub
#define timersub(a, b, result) \
do { \
(result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
(result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \
if ((result)->tv_usec < 0) { \
--(result)->tv_sec; \
(result)->tv_usec += 1000000; \
} \
} while (0)
#endif // timersub
#ifdef __cplusplus
extern "C" {
#endif
static unsigned char g_first_time = 1;
static LARGE_INTEGER g_counts_per_sec;
int gettimeofday(struct timeval*, struct timezone*);
int clock_gettime(int, struct timespec*);
#ifdef __cplusplus
}
#endif
#endif
|
TwoFlyLiu/ecanspy3 | ecanspy3/aboutecanspy3.h | #ifndef ABOUTECANSPY3_H
#define ABOUTECANSPY3_H
#include <QDialog>
namespace Ui {
class AboutEcanSpy3;
}
class AboutEcanSpy3Diaglog : public QDialog
{
Q_OBJECT
public:
explicit AboutEcanSpy3Diaglog(QWidget *parent = 0);
~AboutEcanSpy3Diaglog();
private slots:
void on_okPushButton_clicked();
private:
Ui::AboutEcanSpy3 *ui;
};
#endif // ABOUTECANSPY3_H
|
TwoFlyLiu/ecanspy3 | ecanspy3/status/statuswidget.h | <filename>ecanspy3/status/statuswidget.h
#ifndef STATUSWIDGET_H
#define STATUSWIDGET_H
#include <QWidget>
#include "UsbCanUtil.h"
QT_BEGIN_NAMESPACE
class QLabel;
class QCheckBox;
class QHBoxLayout;
class QVBoxLayout;
class QTimer;
QT_END_NAMESPACE
class StatusWidget : public QWidget
{
Q_OBJECT
public:
enum {
UPDATE_PERIOD_SECOND = 1,
};
explicit StatusWidget(QWidget *parent = nullptr);
void initErrorCounter(QLayout *layout);
void initCanBusStatus(QLayout *layout);
void initControlStatus(QLayout *layout);
void initUpdateTimer();
signals:
public slots:
void updateStatus();
void updateErrCnt();
void updateBusStatus();
void updateControllerStatus(ERR_INFO *err);
private:
QTimer *updateTimer;
QLabel *sendErrCnt;
QLabel *receiveErrCnt;
QCheckBox *busNormal;
QCheckBox *passiveErr;
QCheckBox *activeErr;
QCheckBox *busOff;
QCheckBox *receiveRegFull;
QCheckBox *receiveRegOv;
QCheckBox *controllerErrWarn;
QCheckBox *controllerFIFOOv;
};
#endif // STATUSWIDGET_H
|
TwoFlyLiu/ecanspy3 | ecanspy3/base/titletableviewwidget.h | <reponame>TwoFlyLiu/ecanspy3
#ifndef TITLETABLEVIEWWIDGET_H
#define TITLETABLEVIEWWIDGET_H
#include <QWidget>
#include <QLabel>
#include <QTableView>
#include <QVBoxLayout>
class TitleTableViewWidget : public QWidget
{
Q_OBJECT
public:
TitleTableViewWidget(QWidget *parent = nullptr);
void initTitle(QVBoxLayout *);
void initTableView(QVBoxLayout *);
signals:
public slots:
protected:
QLabel *title;
QTableView *tableView;
};
#endif // TITLETABLEVIEWWIDGET_H
|
TwoFlyLiu/ecanspy3 | ecanspy3/send/signaltablemodel.h | <reponame>TwoFlyLiu/ecanspy3<filename>ecanspy3/send/signaltablemodel.h
#ifndef SIGNALTABLEMODEL_H
#define SIGNALTABLEMODEL_H
#include <QList>
#include <QPair>
#include <QPushButton>
#include <QAbstractTableModel>
#include <dbc4cpp/parser.h>
#include "UsbCanUtil.h"
class SignalTableModel : public QAbstractTableModel
{
Q_OBJECT
public:
enum {COLUMN_COUNT=7};
SignalTableModel(QObject *parent = nullptr);
// QAbstractItemModel interface
public:
int rowCount(const QModelIndex &parent=QModelIndex()) const;
int columnCount(const QModelIndex &parent) const;
QVariant data(const QModelIndex &index, int role) const;
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
bool setData(const QModelIndex &index, const QVariant &value, int role);
Qt::ItemFlags flags(const QModelIndex &index) const;
void incStep(int row);
void decStep(int row);
double getPhysicalValue(int row) const;
void setPhysicalValue(int row, double value);
QString getPhysicalColumnValue(int row) const;
quint64 getRawValue(int row) const;
void setRawValue(int row, quint64 value);
Signal* getSignal(int row) const
{
return signalAt(row);
}
void setMessage(Message *msg, CAN_OBJ *obj);
Message *getMessage()
{
return this->msg;
}
protected:
Signal *signalAt(int index) const;
void setMores();
protected:
Message *msg;
CAN_OBJ *obj;
static const QString columnTitles[COLUMN_COUNT];
struct MoreInfo {
double step = 1.0;
};
QList<MoreInfo> mores;
};
#endif // SIGNALTABLEMODEL_H
|
TwoFlyLiu/ecanspy3 | ecanspy3/mainwindow.h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include "base/mainwindowbase.h"
#include "database/databasewidget.h"
#include "receive/filterwidget.h"
#include "send/sendwidget.h"
#include <dbc4cpp/parser.h>
#include "settings/themesettingdialog.h"
namespace Ui {
class MainWindow;
}
QT_BEGIN_NAMESPACE
class QTimer;
QT_END_NAMESPACE
#define UPDATE_DATAChANGED_FLAG() MainWindow::dataHasChageFlg = true
class MainWindow : public MainWindowBase
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void initDockWidgets();
void initToolBar();
void initCanMonitor();
void initDispatchSignal();
void initDataChanged();
void removeCentralWindow();
void readSettings();
void writeSettings();
void setTheme(QString themeStyleSheet);
DatabaseWidget *getDatabaseWidget();
SendWidget *getSendWidget();
protected slots:
void resetDefaultDockWidgetsLayout();
void openCan();
void closeCan();
void about();
void configCan();
void configTheme();
void triggerMsgOption();
void save();
void saveAs();
void open();
void create();
void onOpenCan();
void onCloseCan();
protected:
void resetSizePolicy();
void saveProjectFile(const QString &projectFileName);
void openProjectFile(const QString &projectFileName);
void loadLastTheme();
protected:
QDockWidget *receiveDockWidget;
QDockWidget *diagDockWidget;
QDockWidget *statusDockWidget;
QDockWidget *statisticsDockWidget;
QDockWidget *logDockWidget;
QDockWidget *sendDockWidget;
QDockWidget *databaseDockWidget;
QString currTheme; //当前主题
QString currProjectFileName; //当前项目
QTimer *uiUpdateTimer = nullptr;
private:
Ui::MainWindow *ui;
// QWidget interface
protected:
void closeEvent(QCloseEvent *);
public:
static bool dataHasChageFlg; //表示用户有过操作
};
#endif // MAINWINDOW_H
|
TwoFlyLiu/ecanspy3 | ecanspy3/base/mainwindowbase.h | <filename>ecanspy3/base/mainwindowbase.h<gh_stars>1-10
#ifndef MAINWINDOWBASE_H
#define MAINWINDOWBASE_H
#include <QMainWindow>
#include <QDockWidget>
#include <QList>
class MainWindowBase : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindowBase(QWidget *parent = nullptr);
protected:
QDockWidget *createDockWidget(const QString &title, QWidget *widget);
void showDockWidgets();
void hideDockWidgets();
signals:
public slots:
private:
QList<QDockWidget*> dockWidgets;
};
#endif // MAINWINDOWBASE_H
|
TwoFlyLiu/ecanspy3 | ecanspy3/settings/themesettingdialog.h | <filename>ecanspy3/settings/themesettingdialog.h<gh_stars>1-10
#ifndef THEMESETTINGDIALOG_H
#define THEMESETTINGDIALOG_H
#include <QDialog>
#include <QMap>
#include <QString>
#include <QRadioButton>
namespace Ui {
class ThemeSettingDialog;
}
QT_BEGIN_NAMESPACE
class QLabel;
QT_END_NAMESPACE
class ThemeSettingDialog : public QDialog
{
Q_OBJECT
public:
struct Entity
{
QString themeName;
QString themeStyleSheet;
QString themeSnapshot;
QLabel *showLabel;
QRadioButton *radioButton;
};
explicit ThemeSettingDialog(QWidget *parent = 0);
~ThemeSettingDialog();
QString getTheme() const;
void setTheme(QString themeName);
QString getThemeStyleSheet(QString themeName);
QString getCurrThemeStyleSheet();
private slots:
void on_okPushButton_clicked();
void on_cancelPushButton_clicked();
void on_defaultRadioButton_clicked(bool checked);
void on_blackRadioButton_clicked(bool checked);
private:
void initTheme(QLabel *label, QRadioButton *radio,
QString themeName, QString themeStylesheet,
QString themeSnapshot);
void updateSnapshot(QLabel *showLabel, QString themeSnapshot);
private:
Ui::ThemeSettingDialog *ui;
QMap<QString, Entity> themeMap;
QString currTheme;
};
#endif // THEMESETTINGDIALOG_H
|
TwoFlyLiu/ecanspy3 | dbc4cpp/parser.h | <reponame>TwoFlyLiu/ecanspy3
#ifndef PARSER_H
#define PARSER_H
#include "dbc4cpp_global.h"
#include "builder.h"
#include <QStringList>
#include <QTextStream>
BEGIN_DBC4CPP_NAMESPACE
/*!
* \brief Parser定义了解析接口
*/
struct Parser
{
virtual ~Parser() {}
/*!
* \brief parse 解析指定文件
* \param file 要解析的文件名称
* \param builder 用于构建最终的结果
* \retval 返回成功与否信息
*/
virtual bool parse(const QString &file, Builder &builder) = 0;
/*!
* \brief getErrMsg 获取错误消息
* \retval 返回错误消息
*/
virtual const QString &getErrMsg() const = 0;
};
class ParserBase : public Parser
{
public:
ParserBase();
const QString &getErrMsg() const;
bool parse(const QString &file, Builder &builder);
protected:
virtual bool onParse(Builder &Builder) = 0;
virtual QString getCodec() const = 0;
QChar getChar();
void putChar();
bool isEnd();
protected:
Context context;
QString content;
qint32 cursor;
};
class DBCParser : public ParserBase
{
public:
typedef bool (DBCParser::*ParseMethod)(Builder &Builder);
typedef QMap<QString, ParseMethod> ParseMethodMap;
bool onParse(Builder &builder);
DBCParser();
protected:
QString getCodec() const
{
return "gbk";
}
/*!
* \brief parseVersion 解析版本号
* \param builder 构建器
* \retval 解析成功与否
*/
bool parseVersion(Builder &builder);
/*!
* \brief parseNewSymbol 解析新标签
* \param builder 构建器
* \retval 解析成功与否
*/
bool parseNewSymbol(Builder &builder);
/*!
* \brief parseBitSetting 解析位设置
* \param builder 构建器
* \retval 解析成功与否
*/
bool parseBitSetting(Builder &builder);
/*!
* \brief parseNode 解析节点
* \param builder 构建器
* \retval 解析成功与否
*/
bool parseNode(Builder &builder);
/*!
* \brief parseMessage 解析报文
* \param builder 构建器
* \retval 解析成功与否
*/
bool parseMessage(Builder &builder);
/*!
* \brief parseSignal 解析信号
* \param builder 构建器
* \retval 解析成功与否
*/
bool parseSignal(Builder &builder);
/*!
* \brief parseValueTable 解析值表
* \param builder 构建器
* \retval 解析成功与否
*/
bool parseValueTable(Builder &builder);
/*!
* \brief parseAttrDefine 解析属性定义
* \param builder 构建器
* \retval 解析成功与否
*/
bool parseAttrDefine(Builder &builder);
/*!
* \brief parseAttrDefaultDefine 解析属性默认值定义
* \param builder 构建器
* \retval 解析成功与否
*/
bool parseAttrDefaultDefine(Builder &builder);
/*!
* \brief parseAttrValue 解析属性值
* \param builder 构建器
* \retval 解析成功与否
*/
bool parseAttrValue(Builder &builder);
/*!
* \brief parseValue 解析值描述
* \param builder 构建器
* \retval 解析成功与否
*/
bool parseValue(Builder &builder);
/*!
* \brief parseBoTxBu 解析单报文多发送节点
* \param builder 构建器
* \return 解析成功与否
*/
bool parseBoTxBu(Builder &builder);
/*!
* \brief parseComment 解析注释
* \param builder 构建器
* \return 构建成功与否
*/
bool parseComment(Builder &builder);
/*!
* \brief doParseValueDesc 进行解析值描述
* \param [out] valueDesc 接收解析后的结果
* \retval 解析成功与否
*/
bool doParseValueDesc(QList<Builder::ValueTableEntry> &valueDesc);
private:
/*!
* \brief getNextIdentifier 获取下一个标识符
* \param [out] nextIdentifier 接收下一个标识符
* \param [in] eol true - 检测到行尾则终止, false - 只有检测到eof才终止
* \retval 是否接收到
*/
bool getNextIdentifier(QString &nextIdentifier, bool eol=true);
/*!
* \brief getNextString 获取下一个字符串
* \param [out] nextString 接收下一个字符串
* \retval 是否接收到
*/
bool getNextString(QString &nextString);
/*!
* \brief getNextSemicolon 获取一个封号';'
* \retval 是否接收到
*/
bool getNextSemicolon();
/*!
* \brief getNextColon 获取下一个冒号':'
* \retval 是否接收到
*/
bool getNextColon();
/*!
* \brief getNextComma 获取下一个逗号','
* \retval 是否接收到
*/
bool getNextComma();
/*!
* \brief getNextInt 获取下一个整数
* \param [out] intVal 接收下一个整数
* \param [out] eol true - 检测到行尾自动终止,false - 扫描到行尾没有扫描到,则换行扫描
* \retval 是否接收到
*/
bool getNextInt(qint32 &intVal, bool eol=true);
/*!
* \brief getNextUnsignedInt 获取下一个无符号整数
* \param [out] uintVal 接收下一个无符号整数
* \param [out] eol true - 检测到行尾自动终止,false - 扫描到行尾没有扫描到,则换行扫描
* \retval 是否接收到
*/
bool getNextUnsignedInt(quint32 &uintVal, bool eol=true);
/*!
* \brief getNextDouble 获取下一个小数值
* \param [out] doubleVal 接收下一个小数值
* \param [out] eol true - 检测到行尾自动终止,false - 扫描到行尾没有扫描到,则换行扫描
* \return 是否接收到
*/
bool getNextDouble(double &doubleVal, bool eol=true);
/*!
* \brief getNextNewSymbol 获取下一个New Symbol
* \param [out] newSymbol 接收下一个New Symbol
* \retval 是否接收到
*/
bool getNextNewSymbol(QString &newSymbol);
/*!
* \brief getNextChar 获取下一个字符
* \param ch 要获取的字符
* \param desc 描述信息
* \param eol 以换行符作为终止字符
* \retval 是否接收到
*/
bool getNextChar(QChar ch, QString desc, bool eol=true);
/*!
* \brief getNextChar 获取下一个在集合中中的字符
* \param set 集合
* \param desc 描述
* \param [out] out 接收收到的字符
* \param eol 以换行符作为终止字符
* \retval 是否接收到
*/
bool getNextChar(const QString set, const QString &desc, QChar &out, bool eol=true);
/*!
* \brief getNextValue 获取下一个值
* \param [out] iret true - 则说明返回值是ival
* \param [out] ival 接收读到的整数值
* \param [out] dret true - 则说明返回值是dval
* \param [out] dval 接收读到的小数值
* \param [out] sret true - 则说明返回值是sval
* \param [out] sval 接收读到的字符串值
* \return 是否接收到
*/
bool getNextValue(bool &iret, qint32 &ival, bool &dret, double &dval,
bool &sret, QString &sval);
private:
ParseMethodMap parseMethodMap;
};
END_DBC4CPP_NAMESPACE
#endif // PARSER_H
|
TwoFlyLiu/ecanspy3 | ecanspy3/send/sendmessagewidget.h | #ifndef SENDMESSAGEWIDGET_H
#define SENDMESSAGEWIDGET_H
#include "base/titletableviewwidget.h"
#include "send/txmessagetablemodel.h"
#include "send/checkedbuttondelegate.h"
#include <dbc4cpp/parser.h>
#include <QPushButton>
#include <QList>
#include <QComboBox>
#include <QLineEdit>
#include <QSortFilterProxyModel>
#define SEND_MESSAGE_TABLE_VIEW_FILTER_ENABLED 1
class SendMessageWidget : public TitleTableViewWidget
{
Q_OBJECT
public:
explicit SendMessageWidget(QWidget *parent = nullptr);
~SendMessageWidget();
void resetSizePolicy();
public slots:
void resetContent(Document *doc, QList<Message*> msgList);
void sendButtonClicked(int row, int col);
void currentChanged(const QModelIndex ¤t, const QModelIndex &previous);
void updateMessageData(Message *msg);
void onToggleAllCyclicButton(bool checked);
#if SEND_MESSAGE_TABLE_VIEW_FILTER_ENABLED
void filterTextChanged(QString text);
void filterColumnChanged(int index);
#endif
signals:
void refreshCurrMessage(Message *msg, CAN_OBJ *obj);
protected:
void initTitle();
void initModel();
void initTableView();
void initCan();
void initToolButtons();
#if SEND_MESSAGE_TABLE_VIEW_FILTER_ENABLED
void initFilter(QHBoxLayout *toolButtonsLayout);
#endif
private:
void enableSendMessage(int msgId, bool enabled);
int maxWidth = -1;
protected:
TxMessageTableModel *model = nullptr;
QPushButton *enableAllCyclicButton;
#if SEND_MESSAGE_TABLE_VIEW_FILTER_ENABLED
QComboBox *filterColumnCombo = nullptr;
QLineEdit *filterTextEdit = nullptr;
QSortFilterProxyModel *proxyModel = nullptr;
#endif
CheckedButtonDelegate *checkedItemDelegate;
QPushButton *resizeColumnsButton;
};
#endif // SENDMESSAGEWIDGET_H
|
TwoFlyLiu/ecanspy3 | ecanspy3/receive/filterwidget.h | <reponame>TwoFlyLiu/ecanspy3<filename>ecanspy3/receive/filterwidget.h
#ifndef FILTERWIDGET_H
#define FILTERWIDGET_H
#include "base/titletableviewwidget.h"
#include "receive/filtertablemodel.h"
#include <dbc4cpp/parser.h>
#include <QPushButton>
#include <QVBoxLayout>
#include <QCheckBox>
#define SYNC_DOCUMENT_MESSAGE_ID_FILTER_ENABLED (0)
class FilterWidget : public TitleTableViewWidget
{
Q_OBJECT
public:
enum {
DEFUALT_FILTER_COUNT = 18
};
FilterWidget(QWidget *parent);
void initButtons(QVBoxLayout *layout);
void initModel();
void initFilters();
void clear();
CanObjFilter* getCanObjFilter()
{
return model->getCanObjFilter();
}
QList<FilterTableModel::Entity>* getFilterList();
FilterTableModel *getFilterTableModel()
{
return this->model;
}
void addFilter(UINT idStart, UINT idEnd, bool checked);
public slots:
void addFilter();
void removeFilter();
void onCheckboxClicked(bool enabled);
void onToggleAllCheckbox(bool enabled);
void setFilterList(Document *doc);
void loadFilterEntList(QList<FilterTableModel::Entity> entList);
protected:
void initTitle();
protected:
QPushButton *addButton;
QPushButton *removeButton;
QPushButton *toggleAllCheckButton;
FilterTableModel *model;
QList<QCheckBox*> checkBoxList;
Document *oldDoc = nullptr;
};
#endif // FILTERWIDGET_H
|
TwoFlyLiu/ecanspy3 | ecanspy3/settings/projectfile.h | <reponame>TwoFlyLiu/ecanspy3
#ifndef PROJECTFILE_H
#define PROJECTFILE_H
#include "database/dbctablemodel.h"
#include "receive/filtertablemodel.h"
#include <QObject>
#include <QtXml>
#include <dbc4cpp/parser.h>
#define DBC_MODEL_NAME_TRANSMIT "transmit"
#define DBC_MODEL_NAME_RECEIVE "receive"
#define DBC_MODEL_NAME_DATABASE "database"
class ProjectFile : public QObject
{
Q_OBJECT
public:
enum ErrorCode {
ERROR_CODE_SUCCESS = 0,
ERROR_CODE_FILE_NOT_EXIST,
ERROR_CODE_FILE_CREATE_FAILED,
ERROR_CODE_PARSE_ERROR
};
explicit ProjectFile(QObject *parent = nullptr);
/*!
* \brief save 保存当前项目数据
*
* 保存数据时候,需要设置号相应的Model
*
* \param projectFile 要加的文件文件所在路径
* \retval 返回错误码, 如果返回ERROR_CODE_SUCCESS,则说明保存成功
*/
ErrorCode save(const QString &projectFile);
/*!
* \brief load 加载当前项目数据
* \param projectFile 要加的文件文件所在路径
* \retval 返回错误码, 如果返回ERROR_CODE_SUCCESS,则说明保存成功
*/
ErrorCode load(const QString &projectFile);
void setDBCFile(QString dbcFile)
{
this->dbcFile = dbcFile;
}
QString getDBCFile() const
{
return this->dbcFile;
}
void setTransmitTableModel(DBCTableModel *transmitTableModel)
{
this->transmitTableModel = transmitTableModel;
}
void setReceiveTableModel(DBCTableModel *receiveTableModel)
{
this->receiveTableModel = receiveTableModel;
}
void setDatabaseTableModel(DBCTableModel *databaseTableModel)
{
this->databaseTableModel = databaseTableModel;
}
void setFilterTableModel(FilterTableModel *filterTableModel)
{
this->filterTableModel = filterTableModel;
}
void setCurrDatabasePageIndex(int currDatabasePageIndex)
{
this->currDatabasePageIndex = currDatabasePageIndex;
}
int getCurrDatabasePageIndex()
{
return this->currDatabasePageIndex;
}
QList<int> getTransmitMsgIdList()
{
return transmitMsgIdList;
}
QList<int> getReceiveMsgIdList()
{
return receiveMsgIdList;
}
QList<int> getDatabaseMsgIdList()
{
return databaseMsgIdList;
}
QList<FilterTableModel::Entity> getFilterEntList()
{
return this->filterEntList;
}
QString getBaurate() const
{
return this->baurate;
}
void setBaurate(QString baurate)
{
this->baurate = baurate;
}
signals:
public slots:
private:
QDomElement createDatabaseElement(QDomDocument &doc);
QDomElement createTextElement(QDomDocument &doc, const QString &tagName, const QString &innerText);
QDomElement createDBCTableModel(QDomDocument &doc, const QString &name, DBCTableModel *model);
QDomElement createFilterElement(QDomDocument &doc);
QDomElement createFilterTableModelElement(QDomDocument &doc, FilterTableModel *model);
QDomElement createCanElement(QDomDocument &doc);
QDomElement createCanBaurateElement(QDomDocument &doc);
ErrorCode doParseDatabase(QDomElement databaseElem);
ErrorCode doParseFilter(QDomElement filterElem);
ErrorCode doParseCan(QDomElement canElem);
private:
// Database相关配置
QString dbcFile; //!< 当前DBC文件名称
DBCTableModel *transmitTableModel = nullptr; //!< 发送Database模型
DBCTableModel *receiveTableModel = nullptr; //!< 接收Database模型
DBCTableModel *databaseTableModel = nullptr; //!< Database模型
FilterTableModel *filterTableModel = nullptr; //!< 过滤TableModel
QList<int> transmitMsgIdList;
QList<int> receiveMsgIdList;
QList<int> databaseMsgIdList;
QList<FilterTableModel::Entity> filterEntList;
int currDatabasePageIndex = 2; //!< Database DockWidget当前页面索引
QString baurate;
};
#endif // PROJECTFILE_H
|
TwoFlyLiu/ecanspy3 | ecanspy3/database/databasewidget.h | #ifndef DATABASEWIDGET_H
#define DATABASEWIDGET_H
#include <QWidget>
#include <QTableView>
#include <QAction>
#include <QMenu>
#include <QPushButton>
#include <QVBoxLayout>
#include <QButtonGroup>
#include <dbc4cpp/parser.h>
#include "dbctablemodel.h"
class DatabaseWidget : public QWidget
{
Q_OBJECT
public:
enum {
PAGE_INDEX_TRANSMIT = 0,
PAGE_INDEX_RECEIVE,
PAGE_INDEX_DATABASE
};
explicit DatabaseWidget(QWidget *parent = nullptr);
~DatabaseWidget();
void initTableView(QVBoxLayout *layout);
void intiContextMenu();
void initAllButtons(QVBoxLayout *layout);
void resetSizePolicy();
DBCTableModel *getTransmitTableModel()
{
return this->transmitTableModel;
}
DBCTableModel *getReceiveTableModel()
{
return this->receiveTableModel;
}
DBCTableModel *getDatabaseTableModel()
{
return this->databaseTableModel;
}
int getCurrPageIndex()
{
return this->currPageIndex;
}
void setCurrPageIndex(int currPageIndex);
QString getCurrDBCFileName()
{
return currDBCFileName;
}
void clear();
signals:
// 刷新发送报文
void refreshSendMessage(Document *doc, const QList<Message*> &);
void refreshDocument(Document *doc);
public slots:
void copyToTransmit();
void copyToReceive();
void copyTo(DBCTableModel *model);
void deleteCurr();
void switchToTransmit();
void switchToReceive();
void switchToDatabase();
void buttonGroupClicked(QAbstractButton *button);
void loadDBC();
void loadDBC(const QString &dbcFile);
void loadDocument(Document *doc);
void loadTransmitMsgIdList(QList<int> transmitMsgIdList);
void loadReceiveMsgIdList(QList<int> receiveMsgIdList);
void loadDatabaseMsgIdList(QList<int> databaseMsgIdList);
void loadMsgIdList(QList<int> msgIdList, DBCTableModel &model);
void loadCurrentPageIndex(int currPageIndex);
void onContextMenu(const QPoint &pos);
void onOpenCan();
void onCloseCan();
void onContextMenuAboutToShow();
private:
QTableView *tableView;
Document *doc;
DBCTableModel *transmitTableModel;
DBCTableModel *receiveTableModel;
DBCTableModel *databaseTableModel;
QMenu *contextMenu;
QAction *copyToTransmitAction;
QAction *copyToReceiveAction;
QAction *deleteCurrAction;
QPushButton *transmitButton;
QPushButton *receiveButton;
QPushButton *databaseButton;
QButtonGroup *buttonGroup;
QPushButton *loadDBCButton;
QSizePolicy oldSizePolicy;
int currPageIndex = -1;
QString currDBCFileName;
};
#endif // DATABASEWIDGET_H
|
TwoFlyLiu/ecanspy3 | ecanspy3/receive/receivemessagetreemodel.h | <reponame>TwoFlyLiu/ecanspy3<filename>ecanspy3/receive/receivemessagetreemodel.h
#ifndef RECEIVEMESSAGETABLEMODEL_H
#define RECEIVEMESSAGETABLEMODEL_H
#include <QAbstractItemModel>
#include <dbc4cpp/parser.h>
#include "UsbCanUtil.h"
#include "filtertablemodel.h"
#include <QList>
#include <QTime>
#include <QMap>
#include <QPair>
#include <deque>
#include <QTimer>
#include <QTreeView>
class ReceiveMessageTreeModel : public QAbstractItemModel
{
Q_OBJECT
public:
enum {
COLUMN_COUNT = 9,
MAX_MESSAGE_COUNT_UNRESTRICTED = -1, //!< 内存没有限制
MAX_MESSAGE_COUNT = 350000, //!< 内存中最多只存5000行
DEFAULT_REFRESH_PREIOD_MS = 250, //!< 默认刷新周期,单位:毫秒
SIGNAL_LEVEL = -1,
DEFAULT_SCROLL_UPDATE = 0, //!< 默认的滚动更新,1表示滚动更新,0表示不进行滚动更新
};
enum UpdateMode {
UPDATE_MODE_NONE = 0,
UPDATE_MODE_INSERT, //插入若干数据
UPDATE_MODE_UPDATE //数据更新,长度未变
};
struct Entity {
CAN_OBJ obj;
DWORD periodUs;
DWORD serialCount;
};
ReceiveMessageTreeModel(QObject *parent=NULL);
// QAbstractItemModel interface
public:
QModelIndex index(int row, int column, const QModelIndex &parent=QModelIndex()) const;
QModelIndex parent(const QModelIndex &child) const;
int rowCount(const QModelIndex &parent) const;
int columnCount(const QModelIndex &parent) const;
QVariant data(const QModelIndex &index, int role) const;
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
QVariant messageColumnData(const Entity &entity, int column, int role) const;
Signal *getSignal(int msgId, int index) const;
void setDocument(Document *doc);
Entity* addCanObj(CAN_OBJ &obj);
void stopReceive();
void startReceive();
int signalCount(int msgRow) const;
QString msgName(int msgID) const;
void setTreeView(QTreeView *treeView)
{
this->treeView = treeView;
}
void setCanObjFilter(CanObjFilter *filter)
{
this->filter = filter;
}
const std::deque<Entity>& getObjList() const
{
return objList;
}
bool isScrollUpdate() const
{
return this->scrollUpdateFlag;
}
private:
int mostTopRowCount() const;
const Entity &entity(int row) const;
public slots:
void refresh();
void forceUpdate();
void clear();
void setScroll(bool scroll);
protected:
QVariant messageData(const QModelIndex &index, int role) const;
QVariant signalData(const QModelIndex &index, int role) const;
void initRefreshTimer();
protected:
Document *doc = nullptr;
static QString columnTitles[COLUMN_COUNT];
std::deque<Entity> objList;
QMap<UINT, Entity> newestObjMap;
QMap<UINT, QPair<UINT, UINT> > msgTimeStampMap;
QMap<UINT, QString> msgNameMap; //内部缓存,报文id和报文名称关系
QTimer *timer; //刷新数据定时器
UpdateMode updateMode = UPDATE_MODE_NONE; //数据变化标识
bool stopReceiveFlag = false;
bool scrollUpdateFlag = DEFAULT_SCROLL_UPDATE;
std::size_t oldSize = 0;
QTreeView *treeView = nullptr;
UINT serialCount = 0;
CanObjFilter* filter = nullptr;
inline int encodeSignal(int rowParent) const
{
return SIGNAL_LEVEL - rowParent;
}
inline int decodeSignal(int internData) const
{
return SIGNAL_LEVEL - internData;
}
};
#endif // RECEIVEMESSAGETABLEMODEL_H
|
TwoFlyLiu/ecanspy3 | ecanspy3/utils/signalaccesstest.h | #ifndef SIGNALACCESSTEST_H
#define SIGNALACCESSTEST_H
#define SIGNAL_ACCESS_TEST_ENABLED (0)
#if SIGNAL_ACCESS_TEST_ENABLED
int signalAccessorTest(void);
#endif //SIGNAL_ACCESS_ENABLED
#endif // SIGNALACCESSTEST_H
|
TwoFlyLiu/ecanspy3 | ecanspy3/utils/signalaccessor.h | #ifndef SIGNALACCESSOR_H
#define SIGNALACCESSOR_H
#include "dbc4cpp/parser.h"
#include "UsbCanUtil.h"
#include <stdint.h>
namespace SignalAccessor
{
quint64 getSignalValue(const CAN_OBJ *obj, const Signal *signal);
void setSignalValue(CAN_OBJ *obj, Signal *signal, quint64 value);
QString getSignalPhysicalValue(const CAN_OBJ *obj, Signal *signal);
}
#endif // SIGNALACCESSOR_H
|
TwoFlyLiu/ecanspy3 | dbc4cpp/dbc4cpp_config.h | #ifndef DBC4CPP_CONFIG_H
#define DBC4CPP_CONFIG_H
#ifdef USE_DBC4CPP_NAMESPACE
#define BEGIN_DBC4CPP_NAMESPACE namespace {
#define END_DBC4CPP_NAMESPACE }
#else
#define BEGIN_DBC4CPP_NAMESPACE
#define END_DBC4CPP_NAMESPACE
#endif
#endif // DBC4CPP_CONFIG_H
|
TwoFlyLiu/ecanspy3 | ecanspy3/receive/filtertablemodel.h | #ifndef FILTERTABLEMODEL_H
#define FILTERTABLEMODEL_H
#include <QAbstractTableModel>
#include <QStringList>
#include "UsbCanUtil.h"
struct CanObjFilter
{
virtual ~CanObjFilter() {}
virtual bool filterCanObj(const CAN_OBJ &canObj) = 0;
};
class FilterTableModel : public QAbstractTableModel, public CanObjFilter
{
Q_OBJECT
public:
struct Entity {
UINT idStart;
UINT idEnd;
bool enabled;
Entity() : idStart(0), idEnd(0), enabled(false) {}
};
enum {COLUMN_COUNT=3};
FilterTableModel(QObject *parent=nullptr);
void setChecked(int row, bool enabled);
QList<Entity> *getFilterList();
signals:
void updateFilter();
// QAbstractItemModel interface
public:
int rowCount(const QModelIndex &parent=QModelIndex()) const;
int columnCount(const QModelIndex &parent) const;
QVariant data(const QModelIndex &index, int role) const;
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
bool insertRows(int row, int count, const QModelIndex &parent);
bool removeRows(int row, int count, const QModelIndex &parent);
bool setData(const QModelIndex &index, const QVariant &value, int role);
Qt::ItemFlags flags(const QModelIndex &index) const;
CanObjFilter* getCanObjFilter()
{
return this;
}
bool filterCanObj(const CAN_OBJ &canObj);
void clear()
{
beginResetModel();
filterList.clear();
endResetModel();
}
void setFilterEntList(QList<Entity> filterList)
{
beginResetModel();
this->filterList = filterList;
endResetModel();
}
protected:
QList<Entity> filterList;
static QString columnTitles[COLUMN_COUNT];
};
#endif // FILTERTABLEMODEL_H
|
TwoFlyLiu/ecanspy3 | dbc4cpp/dbc4cpp_global.h | <reponame>TwoFlyLiu/ecanspy3
#ifndef DBC4CPP_GLOBAL_H
#define DBC4CPP_GLOBAL_H
#include <QtCore/qglobal.h>
#if defined(DBC4CPP_LIBRARY)
# define DBC4CPPSHARED_EXPORT Q_DECL_EXPORT
#else
# define DBC4CPPSHARED_EXPORT Q_DECL_IMPORT
#endif
#include "dbc4cpp_config.h"
#endif // DBC4CPP_GLOBAL_H
|
TwoFlyLiu/ecanspy3 | ecanspy3/base/titletreeviewwidget.h | <reponame>TwoFlyLiu/ecanspy3
#ifndef TITLETREEVIEWWIDGET_H
#define TITLETREEVIEWWIDGET_H
#include <QWidget>
#include <QLabel>
#include <QTreeView>
#include <QVBoxLayout>
class TitleTreeViewWidget : public QWidget
{
Q_OBJECT
public:
explicit TitleTreeViewWidget(QWidget *parent = nullptr);
void initTitle(QVBoxLayout *);
void initTreeView(QVBoxLayout *);
signals:
public slots:
protected:
QLabel *title;
QTreeView *treeView;
};
#endif // TITLETREEVIEWWIDGET_H
|
TwoFlyLiu/ecanspy3 | ecanspy3/database/dbctablemodel.h | #ifndef DBCMESSAGETABLEMODEL_H
#define DBCMESSAGETABLEMODEL_H
#include <QAbstractTableModel>
#include <QString>
#include <dbc4cpp/parser.h>
#define SEND_MESSAGE_UNIQUE_ENABLED (1)
class DBCTableModel : public QAbstractTableModel
{
Q_OBJECT
public:
enum {
COLUMN_COUNT = 6
};
DBCTableModel(QObject *parent = 0);
~DBCTableModel();
// QAbstractItemModel interface
public:
int rowCount(const QModelIndex &parent) const;
int columnCount(const QModelIndex &parent) const;
QVariant data(const QModelIndex &index, int role) const;
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
Qt::ItemFlags flags(const QModelIndex &index) const;
bool removeRows(int row, int count, const QModelIndex &parent);
bool removeRows(const QModelIndexList &list);
const QList<Message*> &getMsgList() const;
void setMsgList(const QList<Message*> &lst, Document *doc);
void setMsgIdList(QList<int> msgIdList, Document *doc);
void clear();
void setDocument(Document *doc);
void addMsg(Message *msg);
Message *getMsg(qint32 index) const;
protected:
Document *doc;
QList<Message*> msgList;
static QString columnTitle[COLUMN_COUNT];
};
#endif // DBCMESSAGETABLEMODEL_H
|
TwoFlyLiu/ecanspy3 | ecanspy3/receive/receivewidget.h | <reponame>TwoFlyLiu/ecanspy3
#ifndef RECEIVEWIDGET_H
#define RECEIVEWIDGET_H
#include <QWidget>
#include <QSplitter>
#include "filterwidget.h"
#include "receivemessagewidget.h"
class ReceiveWidget : public QWidget
{
Q_OBJECT
public:
explicit ReceiveWidget(QWidget *parent = nullptr);
void initFilterWidget(QSplitter &splitter);
void initReceiveMessageWidget(QSplitter &splitter);
void initDispatchSignal();
ReceiveMessageWidget *getReceiveMessageWidget();
FilterWidget *getFilterWidget();
signals:
public slots:
protected:
FilterWidget *filterWidget;
ReceiveMessageWidget *receiveMessageWidget;
};
#endif // RECEIVEWIDGET_H
|
TwoFlyLiu/ecanspy3 | ecanspy3/settings/canconfigdialog.h | <gh_stars>1-10
#ifndef CANCONFIGDIALOG_H
#define CANCONFIGDIALOG_H
#include <QDialog>
namespace Ui {
class CanConfigDialog;
}
class CanConfigDialog : public QDialog
{
Q_OBJECT
public:
explicit CanConfigDialog(QWidget *parent = 0);
~CanConfigDialog();
QString getBaurate();
private slots:
void on_okPushButton_clicked();
private:
void initBaurateCombo();
private:
Ui::CanConfigDialog *ui;
};
#endif // CANCONFIGDIALOG_H
|
TwoFlyLiu/ecanspy3 | dbc4cpp/dbc4cpp.h | <reponame>TwoFlyLiu/ecanspy3
#ifndef DBC4CPP_H
#define DBC4CPP_H
#include "dbc4cpp_global.h"
#include "parser.h"
#endif // DBC4CPP_H
|
TwoFlyLiu/ecanspy3 | ecanspy3/utils/mmtimer.h | #ifndef MMTIMER_H
#define MMTIMER_H
#include <windows.h>
#include <mmsystem.h>
#include <QObject>
class MMTimer : public QObject
{
Q_OBJECT
public:
friend void WINAPI CALLBACK mmtimer_proc(uint, uint, DWORD_PTR user, DWORD_PTR, DWORD_PTR);
explicit MMTimer(int interval, QObject *parent=nullptr);
signals:
void timeout();
public slots:
void start();
void stop();
private:
int interval;
int id;
};
#endif // MMTIMER_H
|
TwoFlyLiu/ecanspy3 | dbc4cpp/context.h | <reponame>TwoFlyLiu/ecanspy3<gh_stars>1-10
#ifndef CONTEXT_H
#define CONTEXT_H
#include "dbc4cpp_global.h"
#include <QString>
BEGIN_DBC4CPP_NAMESPACE
/*!
* \brief Context类保存解析过程中的上下文
*/
class Context
{
public:
enum State{
STATE_OK = 0, //!< 当内部解析都正确的时候,为此状态
STATE_ERR //!< 当内部解析出错的时候,为此状态
};
/*!
* \brief Context 默认构造器
*/
Context();
/*!
* \brief getDBCFileName 获取当前解析的DBC文件名称
*
* 当解析出错的时候,可以调用此方法来获取温习出错的DBC文件名称
*
* \retval 当前解析的DBC文件名称
*/
const QString& getDBCFileName();
/*!
* \brief setDBCFileName 设置当前解析的DBC文件名称
* \param dbcFileName 要设置的DBC文件名称
*/
void setDBCFileName(const QString &dbcFileName);
/*!
* \brief getCurLineNo 获取当前正在解析的行号
*
* 当解析出错的时候,可以调用此方法来获取解析出错的行号
*
* \retval 当前正在解析的行号
*/
int getCurLineNo() const;
/*!
* \brief setCurLineNo 设置当前正在解析的行号
* \param curLineNo 要设置的当前正在解析的行号
*/
void setCurLineNo(int curLineNo);
/*!
* \brief getCurColNo 获取当前列号
* \retval 当前列号
*/
int getCurColNo() const;
/*!
* \brief setCurColNo 设置当前列号
* \param curColNo 当前列号
*/
void setCurColNo(int curColNo);
/*!
* \brief operator bool 检测当前是否解析出错
* \retval 如果没有出错,则返回true, 否则返回false
*/
operator bool() const;
/*!
* \brief getErrMsg 获取解析出错的消息
* \retval 解析出错的消息
*/
const QString &getErrMsg() const;
/*!
* \brief setErrMsg 设置错误消息
* \param errMsg 要设置的错误消息
*/
void setErrMsg(const QString &errMsg);
/*!
* \brief clrErrMsg 清除消息
*/
void clrErrMsg();
/*!
* \brief getCurLine 获取当前行
* \retval 当前行
*/
const QString &getCurLine() const;
/*!
* \brief setCurLine 设置当前行
* \param newCurLine 新的当前行
*/
void setCurLine(const QString newCurLine);
/*!
* \brief moveNextLine 移到下一行
*/
void moveNextLine();
/*!
* \brief movePrevLineLastPos 移动前一行的最后一个位置
*/
void movePrevLineLastPos();
/*!
* \brief movePrevCol 移动到前一列
*/
void movePrevCol();
/*!
* \brief moveNextCol 移动到下一列
*/
void moveNextCol();
private:
QString dbcFileName; //!< 解析DBC文件名称
int curLineNo; //!< 当前报文行号
int curColNo; //!< 当前列号
int preColNo; //!< 之前的列好
QString curLine; //!< 当前行内容
State state; //!< 当前状态
QString errMsg; //!< 当包状态为出错的时候,保存出错消息
};
END_DBC4CPP_NAMESPACE
#endif // CONTEXT_H
|
TwoFlyLiu/ecanspy3 | ecanspy3/send/sendwidget.h | #ifndef SENDWIDGET_H
#define SENDWIDGET_H
#include <QWidget>
#include <QSplitter>
#include <QTableView>
#include "sendmessagewidget.h"
#include "signalwidget.h"
class SendWidget : public QWidget
{
Q_OBJECT
public:
explicit SendWidget(QWidget *parent = nullptr);
void initMessageTableView(QSplitter *splitter);
void initSignalTableView(QSplitter *splitter);
SendMessageWidget *getSendMessageWidget();
SignalWidget *getSignalWidget();
void resetSizePolicy();
signals:
public slots:
private:
SendMessageWidget *sendMessageWidget;
SignalWidget *signalWidget;
int defaultMaxHeight;
};
#endif // SENDWIDGET_H
|
TwoFlyLiu/ecanspy3 | ecanspy3/send/txmessagetablemodel.h | <gh_stars>1-10
#ifndef TXMESSAGETABLEMODEL_H
#define TXMESSAGETABLEMODEL_H
#include <QAbstractTableModel>
#include <can/ECanVci.H>
#include <QList>
#include <QString>
#include <dbc4cpp/parser.h>
#define TX_MESSAGE_TABLE_VIEW_COLUMN_INDEX_NAME (0)
#define TX_MESSAGE_TABLE_VIEW_TX_EN (1)
#define TX_MESSAGE_TABLE_VIEW_MESSAGE_TYPE (2)
#define TX_MESSAGE_TABLE_VIEW_COLUMN_INDEX_ID (4)
class TxMessageTableModel : public QAbstractTableModel
{
Q_OBJECT
public:
enum {
COLUMN_COUNT = 15
};
/*!
* \brief MoreInfo 存放报文附加信息
*/
struct MoreInfo{
QString name;
bool tx;
QString type;
qint32 period;
};
TxMessageTableModel(Document *doc = NULL, QObject *parent=NULL);
// QAbstractItemModel interface
public:
int rowCount(const QModelIndex &parent) const;
int columnCount(const QModelIndex &parent) const;
QVariant data(const QModelIndex &index, int role) const;
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
Qt::ItemFlags flags(const QModelIndex &index) const;
bool setData(const QModelIndex &index, const QVariant &value, int role);
void reset();
void appendRow(CAN_OBJ &obj, const MoreInfo &more);
void setDocument(Document *doc);
Message *getMessage(QModelIndex index);
CAN_OBJ *getCanObj(QModelIndex index);
void refreshMessageData(Message *msg);
void beginResetModel()
{
QAbstractTableModel::beginResetModel();
}
void endResetModel()
{
QAbstractTableModel::endResetModel();
}
QList<CAN_OBJ*> objs; //!< 存放要发送的数据信号
QList<MoreInfo> mores; //!< 存放附加信息
Document *doc;
private:
static QString columnTitles[COLUMN_COUNT];
// QAbstractItemModel interface
public:
};
#endif // TXMESSAGETABLEMODEL_H
|
TwoFlyLiu/ecanspy3 | ecanspy3/receive/receivemessagewidget.h | #ifndef RECEIVEMESSAGEWIDGET_H
#define RECEIVEMESSAGEWIDGET_H
#include "base/titletreeviewwidget.h"
#include "receive/receivemessagetreemodel.h"
#include "receive/receivemessagefilterproxymodel.h"
#include "utils/scrollingfile.h"
#include <QTimer>
#include <QPushButton>
#define RECEIVE_FILTER_PROXY_ENABLED (0)
QT_BEGIN_NAMESPACE
class QTextStream;
QT_END_NAMESPACE
class ReceiveMessageWidget : public TitleTreeViewWidget
{
Q_OBJECT
public:
enum {
RECEIVE_INTERVAL_MS = 10,
RECEIVE_BUFFER_SIZE = 100,
};
ReceiveMessageWidget(QWidget *parent = nullptr);
~ReceiveMessageWidget();
void setFilterList(QList<FilterTableModel::Entity> *filterList);
void setCanObjFilter(CanObjFilter *filter);
QList<int> getColumnWidthList() const;
void setColumnWidthList(QList<int> widthList);
protected:
void initTitle();
void initModel();
void initTimer();
void initToolButtons();
void initColumnsWidth();
int getTextWidth(QChar ch);
void doRealTimeSave(const ReceiveMessageTreeModel::Entity &ent);
void doSave(QTextStream &stream, const ReceiveMessageTreeModel::Entity &ent);
public slots:
void refreshDocument(Document *doc);
void updateFilter();
void onTimer();
void onStartReceive(bool checked);
void onSave();
void onRealTimeSave(bool checked);
void onResizeColumns();
private:
ReceiveMessageTreeModel *model = nullptr;
#if RECEIVE_FILTER_PROXY_ENABLED
ReceiveMessageFilterProxyModel *proxyModel = nullptr;
#endif
QTimer *timer = nullptr;
QPushButton *stopShowButton = nullptr;
QPushButton *clearButton = nullptr;
QPushButton *scrollButton = nullptr;
QPushButton *saveButton = nullptr;
QPushButton *realTimeSaveButton = nullptr;
QPushButton *resizeColumns = nullptr;
ScrollingFile *scrollingFile = nullptr;
};
#endif // RECEIVEMESSAGEWIDGET_H
|
TwoFlyLiu/ecanspy3 | ecanspy3/statistic/statisticswidget.h | <reponame>TwoFlyLiu/ecanspy3<filename>ecanspy3/statistic/statisticswidget.h
#ifndef STATISTICSWIDGET_H
#define STATISTICSWIDGET_H
#include <QWidget>
class StatisticsWidget : public QWidget
{
Q_OBJECT
public:
explicit StatisticsWidget(QWidget *parent = nullptr);
signals:
public slots:
};
#endif // STATISTICSWIDGET_H |
TwoFlyLiu/ecanspy3 | ecanspy3/send/checkedbuttondelegate.h | <reponame>TwoFlyLiu/ecanspy3<gh_stars>1-10
#ifndef CHECKEDBUTTONDELEGATE_H
#define CHECKEDBUTTONDELEGATE_H
#include <QStyledItemDelegate>
class CheckedButtonDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
explicit CheckedButtonDelegate(QObject *parent = nullptr);
void setCheckedButotnColumn(int column)
{
checkedButtonColumn = column;
}
signals:
void checkedButtonClicked(int row, int col);
public slots:
// QAbstractItemDelegate interface
public:
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index);
private:
int checkedButtonColumn = -1;
};
#endif // CHECKEDBUTTONDELEGATE_H
|
TwoFlyLiu/ecanspy3 | ecanspy3/log/logwidget.h | #ifndef LOGWIDGET_H
#define LOGWIDGET_H
#include <QWidget>
class LogWidget : public QWidget
{
Q_OBJECT
public:
explicit LogWidget(QWidget *parent = nullptr);
signals:
public slots:
};
#endif // LOGWIDGET_H |
TwoFlyLiu/ecanspy3 | dbc4cpp/builder.h | #ifndef BUILDER_H
#define BUILDER_H
#include "dbc4cpp_global.h"
#include <QString>
#include <QList>
#include "entities.h"
#include "context.h"
BEGIN_DBC4CPP_NAMESPACE
struct Builder {
struct ValueTableEntry
{
qint32 value;
QString desc;
};
virtual ~Builder() {}
virtual void onVersion(const Context &context, const QString &version) = 0;
virtual void onNewSymbol(const Context &context, const QString &newSymbol) = 0;
virtual void onBS(const Context &context, quint32 baurate, quint32 btr1, quint32 btr2) = 0;
virtual void onBU(const Context &context, const QString &nodeName) = 0;
virtual void onValTable(const Context &context, const QString &valTableName, const QList<ValueTableEntry> &list) = 0;
virtual void onBO(const Context &context, qint32 msgId, const QString &name, qint32 size, const QString transmitter) = 0;
virtual void onSG(const Context &context, const QString &signalName,
Signal::MultiplexerIndType mpIndicatorType, quint32 multiplexerSwithValue,
qint32 startBit, qint32 signalSize, Signal::ByteOrderType byteOrder,
Signal::ValueType valueType, double factor, double offset,
double minimum, double maximum, const QString &unit, const QList<QString> receivers) = 0;
virtual void onBoTxBu(const Context &context, qint32 msgId, const QList<QString> transmitters) = 0;
virtual void onSigVal(const Context &context, qint32 msgId, const QString &signalName, const QList<ValueTableEntry> &list) = 0;
virtual void onEnvVal(const Context &context, const QString &envName, const QList<ValueTableEntry> &list) = 0;
virtual void onEv(const Context &context, const QString &envVarName, EV::EnvVarType envVarType,
double minimum, double maximum, const QString &unit,
double initValue, quint32 evId, EV::AccessType accessType,
const QList<QString> &accessNodeList) = 0;
virtual void onEvData(const Context &context, const QString envVarName, quint32 dataSize) = 0;
//CM_
virtual void onCm(const Context &context, const QString &globalComment) = 0;
virtual void onBUCM(const Context &context, const QString &nodeName, const QString &comment) = 0;
virtual void onBOCM(const Context &context, qint32 msgId, const QString &comment) = 0;
virtual void onSGCM(const Context &context, qint32 msgId, const QString &sigName, const QString &comment) = 0;
virtual void onEVCM(const Context &context, const QString &envVarName, const QString &comment) = 0;
//BA_DEF_
virtual void onIntAttrDef(const Context &context, Document::ObjectType objectType, const QString &attrName,
qint32 minimum, qint32 maximum) = 0;
virtual void onHexAttrDef(const Context &context, Document::ObjectType objectType, const QString &attrName,
qint32 minimum, qint32 maximum) = 0;
virtual void onFloatAttrDef(const Context &context, Document::ObjectType objectType, const QString &attrName,
double minimum, double maximum) = 0;
virtual void onStringAttrDef(const Context &context, Document::ObjectType objectType, const QString &attrName) = 0;
virtual void onEnumAttrDef(const Context &context, Document::ObjectType objectType, const QString &attrName,
QList<QString> attrValues) = 0;
//BA_DEF_DEF_
virtual void onIntAttrDefaultDef(const Context &context, const QString &attrName, qint32 value) = 0;
virtual void onHexAttrDefaultDef(const Context &context, const QString &attrName, qint32 value) = 0;
virtual void onFloatAttrDefaultDef(const Context &context, const QString &attrName, double value) = 0;
virtual void onStringAttrDefaultDef(const Context &context, const QString &attrName, const QString &value) = 0;
virtual void onEnumAttrDefaultDef(const Context &context, const QString &attrName, const QString &value) = 0;
//BA_
virtual void onBUAttributeValue(const Context &context, const QString &nodeName, const QString &attrName, qint32 value) = 0;
virtual void onBUAttributeValue(const Context &context, const QString &nodeName, const QString &attrName, double value) = 0;
virtual void onBUAttributeValue(const Context &context, const QString &nodeName, const QString &attrName, const QString &value) = 0;
virtual void onBOAttributeValue(const Context &context, qint32 msgId, const QString &attrName, qint32 value) = 0;
virtual void onBOAttributeValue(const Context &context, qint32 msgId, const QString &attrName, double value) = 0;
virtual void onBOAttributeValue(const Context &context, qint32 msgId, const QString &attrName, const QString &value) = 0;
virtual void onSGAttributeValue(const Context &context, qint32 msgId, const QString &sigName, const QString &attrName, qint32 value) = 0;
virtual void onSGAttributeValue(const Context &context, qint32 msgId, const QString &sigName, const QString &attrName, double value) = 0;
virtual void onSGAttributeValue(const Context &context, qint32 msgId, const QString &sigName, const QString &attrName, const QString &value) = 0;
virtual void onEvAttributeValue(const Context &context, const QString &varName, const QString &attrName, qint32 value) = 0;
virtual void onEvAttributeValue(const Context &context, const QString &varName, const QString &attrName, double value) = 0;
virtual void onEvAttributeValue(const Context &context, const QString &varName, const QString &attrName, const QString &value) = 0;
virtual void onGblAttributeValue(const Context &context, const QString &attrName, qint32 value) = 0;
virtual void onGblAttributeValue(const Context &context, const QString &attrName, double value) = 0;
virtual void onGblAttributeValue(const Context &context, const QString &attrName, const QString &value) = 0;
virtual void onDone(const Context &context) = 0;
};
class DocumentBuilder : public Builder
{
// Builder interface
public:
void onVersion(const Context &context, const QString &version);
void onNewSymbol(const Context &context, const QString &newSymbol);
void onBS(const Context &context, quint32 baurate, quint32 btr1, quint32 btr2);
void onBU(const Context &context, const QString &nodeName);
void onValTable(const Context &context, const QString &valTableName, const QList<ValueTableEntry> &list);
void onBO(const Context &context, qint32 msgId, const QString &name, qint32 size, const QString transmitter);
void onSG(const Context &context, const QString &signalName, Signal::MultiplexerIndType mpIndicatorType, quint32 multiplexerSwithValue, qint32 startBit, qint32 signalSize, Signal::ByteOrderType byteOrder, Signal::ValueType valueType, double factor, double offset, double minimum, double maximum, const QString &unit, const QList<QString> receivers);
void onBoTxBu(const Context &context, qint32 msgId, const QList<QString> transmitters);
void onSigVal(const Context &context, qint32 msgId, const QString &signalName, const QList<ValueTableEntry> &list);
void onEnvVal(const Context &context, const QString &envName, const QList<ValueTableEntry> &list);
void onEv(const Context &context, const QString &envVarName, EV::EnvVarType envVarType, double minimum, double maximum, const QString &unit, double initValue, quint32 evId, EV::AccessType accessType, const QList<QString> &accessNodeList);
void onEvData(const Context &context, const QString envVarName, quint32 dataSize);
void onCm(const Context &context, const QString &globalComment);
void onBUCM(const Context &context, const QString &nodeName, const QString &comment);
void onBOCM(const Context &context, qint32 msgId, const QString &comment);
void onSGCM(const Context &context, qint32 msgId, const QString &sigName, const QString &comment);
void onEVCM(const Context &context, const QString &envVarName, const QString &comment);
void onIntAttrDef(const Context &context, Document::ObjectType objectType, const QString &attrName, qint32 minimum, qint32 maximum);
void onHexAttrDef(const Context &context, Document::ObjectType objectType, const QString &attrName, qint32 minimum, qint32 maximum);
void onFloatAttrDef(const Context &context, Document::ObjectType objectType, const QString &attrName, double minimum, double maximum);
void onStringAttrDef(const Context &context, Document::ObjectType objectType, const QString &attrName);
void onEnumAttrDef(const Context &context, Document::ObjectType objectType, const QString &attrName, QList<QString> attrValues);
void onIntAttrDefaultDef(const Context &context, const QString &attrName, qint32 value);
void onHexAttrDefaultDef(const Context &context, const QString &attrName, qint32 value);
void onFloatAttrDefaultDef(const Context &context, const QString &attrName, double value);
void onStringAttrDefaultDef(const Context &context, const QString &attrName, const QString &value);
void onEnumAttrDefaultDef(const Context &context, const QString &attrName, const QString &value);
void onBUAttributeValue(const Context &context, const QString &nodeName, const QString &attrName, qint32 value);
void onBUAttributeValue(const Context &context, const QString &nodeName, const QString &attrName, double value);
void onBUAttributeValue(const Context &context, const QString &nodeName, const QString &attrName, const QString &value);
void onBOAttributeValue(const Context &context, qint32 msgId, const QString &attrName, qint32 value);
void onBOAttributeValue(const Context &context, qint32 msgId, const QString &attrName, double value);
void onBOAttributeValue(const Context &context, qint32 msgId, const QString &attrName, const QString &value);
void onSGAttributeValue(const Context &context, qint32 msgId, const QString &sigName, const QString &attrName, qint32 value);
void onSGAttributeValue(const Context &context, qint32 msgId, const QString &sigName, const QString &attrName, double value);
void onSGAttributeValue(const Context &context, qint32 msgId, const QString &sigName, const QString &attrName, const QString &value);
void onEvAttributeValue(const Context &context, const QString &varName, const QString &attrName, qint32 value);
void onEvAttributeValue(const Context &context, const QString &varName, const QString &attrName, double value);
void onEvAttributeValue(const Context &context, const QString &varName, const QString &attrName, const QString &value);
void onGblAttributeValue(const Context &context, const QString &attrName, qint32 value);
void onGblAttributeValue(const Context &context, const QString &attrName, double value);
void onGblAttributeValue(const Context &context, const QString &attrName, const QString &value);
void onDone(const Context &context);
public:
DocumentBuilder();
Document *getDocument();
protected:
Document *doc;
Message *curMsg;
};
END_DBC4CPP_NAMESPACE
#endif // BUILDER_H
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.