This commit is contained in:
Evgeny Zinoviev 2018-09-05 21:46:55 +03:00
commit 9fcc074af3
23 changed files with 1658 additions and 0 deletions

15
build-linux.sh Executable file
View File

@ -0,0 +1,15 @@
#!/bin/bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
g++ ./spinning_cube.c ./hello.cc \
-shared -o libppapi_hello.so \
-I$DIR/nacl_sdk/pepper_49/include \
-L$DIR/nacl_sdk/pepper_49/lib/linux_host/Release \
-lppapi_cpp \
-lppapi \
-lppapi_simple \
-lpthread \
-lm \
-lppapi_gles2 \
-Wall -fPIC

15
build-macos.sh Executable file
View File

@ -0,0 +1,15 @@
#!/bin/bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
g++ ./spinning_cube.c ./hello.cc \
-shared -o libppapi_hello.so \
-I$DIR/nacl_sdk/pepper_49/include \
-L$DIR/nacl_sdk/pepper_49/lib/mac_host/Release \
-lppapi_cpp \
-lppapi \
-lppapi_simple \
-lpthread \
-lm \
-lppapi_gles2 \
-Wall -fPIC

18
build-win.sh Executable file
View File

@ -0,0 +1,18 @@
#!/bin/bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
CC=$DIR/nacl_sdk/pepper_49/toolchain/win_x86_glibc/bin/x86_64-nacl-g++.exe
cd $DIR
$CC spinning_cube.c hello.cc \
-shared -o libppapi_hello.ldd \
-I$DIR/nacl_sdk/pepper_49/include \
-L$DIR/nacl_sdk/pepper_49/lib/win_x86_64_host/Release \
-lppapi_cpp \
-lppapi \
-lppapi_simple \
-lpthread \
-lm \
-lppapi_gles2 \
-Wall -fPIC

143
hello.cc Normal file
View File

@ -0,0 +1,143 @@
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ppapi/c/pp_errors.h"
#include "ppapi/cpp/core.h"
#include "ppapi/cpp/graphics_3d.h"
#include "ppapi/cpp/graphics_3d_client.h"
#include "ppapi/cpp/input_event.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/rect.h"
#include "spinning_cube.h"
#include "ppapi/lib/gl/gles2/gl2ext_ppapi.h"
#include "ppapi/utility/completion_callback_factory.h"
// Use assert as a makeshift CHECK, even in non-debug mode.
// Since <assert.h> redefines assert on every inclusion (it doesn't use
// include-guards), make sure this is the last file #include'd in this file.
#undef NDEBUG
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
namespace {
class DemoInstance : public pp::Instance, public pp::Graphics3DClient {
public:
DemoInstance(PP_Instance instance);
virtual ~DemoInstance();
// pp::Instance implementation (see PPP_Instance).
virtual bool Init(uint32_t argc, const char* argn[], const char* argv[]);
virtual void DidChangeView(const pp::Rect& position,
const pp::Rect& clip);
virtual bool HandleInputEvent(const pp::InputEvent& event) {
// TODO(yzshen): Handle input events.
return true;
}
// pp::Graphics3DClient implementation.
virtual void Graphics3DContextLost();
private:
// GL-related functions.
void InitGL(int32_t result);
void Paint(int32_t result);
pp::Size plugin_size_;
pp::CompletionCallbackFactory<DemoInstance> callback_factory_;
// Owned data.
pp::Graphics3D* context_;
SpinningCube cube_;
};
DemoInstance::DemoInstance(PP_Instance instance)
: pp::Instance(instance),
pp::Graphics3DClient(this),
callback_factory_(this),
context_(NULL) {}
DemoInstance::~DemoInstance() {
assert(glTerminatePPAPI());
delete context_;
}
bool DemoInstance::Init(uint32_t /*argc*/,
const char* /*argn*/[],
const char* /*argv*/[]) {
RequestInputEvents(PP_INPUTEVENT_CLASS_MOUSE);
return !!glInitializePPAPI(pp::Module::Get()->get_browser_interface());
}
void DemoInstance::DidChangeView(
const pp::Rect& position, const pp::Rect& /*clip*/) {
if (position.width() == 0 || position.height() == 0)
return;
plugin_size_ = position.size();
// Initialize graphics.
InitGL(0);
}
void DemoInstance::Graphics3DContextLost() {
delete context_;
context_ = NULL;
pp::CompletionCallback cb = callback_factory_.NewCallback(
&DemoInstance::InitGL);
pp::Module::Get()->core()->CallOnMainThread(0, cb, 0);
}
void DemoInstance::InitGL(int32_t /*result*/) {
assert(plugin_size_.width() && plugin_size_.height());
if (context_) {
context_->ResizeBuffers(plugin_size_.width(), plugin_size_.height());
return;
}
int32_t context_attributes[] = {
PP_GRAPHICS3DATTRIB_ALPHA_SIZE, 8,
PP_GRAPHICS3DATTRIB_BLUE_SIZE, 8,
PP_GRAPHICS3DATTRIB_GREEN_SIZE, 8,
PP_GRAPHICS3DATTRIB_RED_SIZE, 8,
PP_GRAPHICS3DATTRIB_DEPTH_SIZE, 0,
PP_GRAPHICS3DATTRIB_STENCIL_SIZE, 0,
PP_GRAPHICS3DATTRIB_SAMPLES, 0,
PP_GRAPHICS3DATTRIB_SAMPLE_BUFFERS, 0,
PP_GRAPHICS3DATTRIB_WIDTH, plugin_size_.width(),
PP_GRAPHICS3DATTRIB_HEIGHT, plugin_size_.height(),
PP_GRAPHICS3DATTRIB_NONE,
};
context_ = new pp::Graphics3D(this, context_attributes);
assert(!context_->is_null());
assert(BindGraphics(*context_));
glSetCurrentContextPPAPI(context_->pp_resource());
cube_.Init(plugin_size_.width(), plugin_size_.height());
Paint(PP_OK);
}
void DemoInstance::Paint(int32_t result) {
if (result != PP_OK || !context_)
return;
cube_.UpdateForTimeDelta(0.02f);
cube_.Draw();
context_->SwapBuffers(callback_factory_.NewCallback(&DemoInstance::Paint));
}
// This object is the global object representing this plugin library as long
// as it is loaded.
class DemoModule : public pp::Module {
public:
DemoModule() : Module() {}
virtual ~DemoModule() {}
virtual pp::Instance* CreateInstance(PP_Instance instance) {
return new DemoInstance(instance);
}
};
}
// anonymous namespace
namespace pp {
// Factory function for your specialization of the Module object.
Module* CreateModule() {
return new DemoModule();
}
} // namespace pp

View File

@ -0,0 +1,28 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Express 14 for Windows Desktop
VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libppapi_hello", "libppapi_hello\libppapi_hello.vcxproj", "{4EEEC1D7-306E-4847-86BB-F534BB291427}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4EEEC1D7-306E-4847-86BB-F534BB291427}.Debug|x64.ActiveCfg = Debug|x64
{4EEEC1D7-306E-4847-86BB-F534BB291427}.Debug|x64.Build.0 = Debug|x64
{4EEEC1D7-306E-4847-86BB-F534BB291427}.Debug|x86.ActiveCfg = Debug|Win32
{4EEEC1D7-306E-4847-86BB-F534BB291427}.Debug|x86.Build.0 = Debug|Win32
{4EEEC1D7-306E-4847-86BB-F534BB291427}.Release|x64.ActiveCfg = Release|x64
{4EEEC1D7-306E-4847-86BB-F534BB291427}.Release|x64.Build.0 = Release|x64
{4EEEC1D7-306E-4847-86BB-F534BB291427}.Release|x86.ActiveCfg = Release|Win32
{4EEEC1D7-306E-4847-86BB-F534BB291427}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,152 @@
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ppapi/c/pp_errors.h"
#include "ppapi/cpp/core.h"
#include "ppapi/cpp/graphics_3d.h"
#include "ppapi/cpp/graphics_3d_client.h"
#include "ppapi/cpp/input_event.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/rect.h"
#include "spinning_cube.hpp"
#include "ppapi/lib/gl/gles2/gl2ext_ppapi.h"
#include "ppapi/utility/completion_callback_factory.h"
// Use assert as a makeshift CHECK, even in non-debug mode.
// Since <assert.h> redefines assert on every inclusion (it doesn't use
// include-guards), make sure this is the last file #include'd in this file.
#undef NDEBUG
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
namespace {
class DemoInstance : public pp::Instance, public pp::Graphics3DClient {
public:
DemoInstance(PP_Instance instance);
virtual ~DemoInstance();
// pp::Instance implementation (see PPP_Instance).
virtual bool Init(uint32_t argc, const char* argn[], const char* argv[]);
virtual void DidChangeView(const pp::Rect& position,
const pp::Rect& clip);
virtual bool HandleInputEvent(const pp::InputEvent& event) {
// TODO(yzshen): Handle input events.
return true;
}
// pp::Graphics3DClient implementation.
virtual void Graphics3DContextLost();
private:
// GL-related functions.
void InitGL(int32_t result);
void Paint(int32_t result);
pp::Size plugin_size_;
pp::CompletionCallbackFactory<DemoInstance> callback_factory_;
// Owned data.
pp::Graphics3D* context_;
SpinningCube cube_;
};
DemoInstance::DemoInstance(PP_Instance instance)
: pp::Instance(instance),
pp::Graphics3DClient(this),
callback_factory_(this),
context_(NULL) {
printf("DemoInstance created\n");
}
DemoInstance::~DemoInstance() {
assert(glTerminatePPAPI());
delete context_;
printf("DemoInstance destroyed\n");
}
bool DemoInstance::Init(uint32_t /*argc*/,
const char* /*argn*/[],
const char* /*argv*/[]) {
printf("Init\n");
RequestInputEvents(PP_INPUTEVENT_CLASS_MOUSE);
return !!glInitializePPAPI(pp::Module::Get()->get_browser_interface());
}
void DemoInstance::DidChangeView(
const pp::Rect& position, const pp::Rect& /*clip*/) {
printf("didchangeview\n");
if (position.width() == 0 || position.height() == 0)
return;
plugin_size_ = position.size();
// Initialize graphics.
InitGL(0);
}
void DemoInstance::Graphics3DContextLost() {
printf("Graphics3dcontextlost\n");
delete context_;
context_ = NULL;
pp::CompletionCallback cb = callback_factory_.NewCallback(
&DemoInstance::InitGL);
pp::Module::Get()->core()->CallOnMainThread(0, cb, 0);
}
void DemoInstance::InitGL(int32_t /*result*/) {
printf("InitGL\n");
assert(plugin_size_.width() && plugin_size_.height());
if (context_) {
context_->ResizeBuffers(plugin_size_.width(), plugin_size_.height());
return;
}
int32_t context_attributes[] = {
PP_GRAPHICS3DATTRIB_ALPHA_SIZE, 8,
PP_GRAPHICS3DATTRIB_BLUE_SIZE, 8,
PP_GRAPHICS3DATTRIB_GREEN_SIZE, 8,
PP_GRAPHICS3DATTRIB_RED_SIZE, 8,
PP_GRAPHICS3DATTRIB_DEPTH_SIZE, 0,
PP_GRAPHICS3DATTRIB_STENCIL_SIZE, 0,
PP_GRAPHICS3DATTRIB_SAMPLES, 0,
PP_GRAPHICS3DATTRIB_SAMPLE_BUFFERS, 0,
PP_GRAPHICS3DATTRIB_WIDTH, plugin_size_.width(),
PP_GRAPHICS3DATTRIB_HEIGHT, plugin_size_.height(),
PP_GRAPHICS3DATTRIB_NONE,
};
context_ = new pp::Graphics3D(this, context_attributes);
assert(!context_->is_null());
assert(BindGraphics(*context_));
glSetCurrentContextPPAPI(context_->pp_resource());
cube_.Init(plugin_size_.width(), plugin_size_.height());
Paint(PP_OK);
}
void DemoInstance::Paint(int32_t result) {
printf("Paint\n");
if (result != PP_OK || !context_)
return;
cube_.UpdateForTimeDelta(0.02f);
cube_.Draw();
context_->SwapBuffers(callback_factory_.NewCallback(&DemoInstance::Paint));
}
// This object is the global object representing this plugin library as long
// as it is loaded.
class DemoModule : public pp::Module {
public:
DemoModule() : Module() {}
virtual ~DemoModule() {}
virtual pp::Instance* CreateInstance(PP_Instance instance) {
printf("DemoModule\n");
return new DemoInstance(instance);
}
};
}
// anonymous namespace
namespace pp {
// Factory function for your specialization of the Module object.
Module* CreateModule() {
printf("CreateModule\n");
return new DemoModule();
}
} // namespace pp

View File

@ -0,0 +1,174 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{4EEEC1D7-306E-4847-86BB-F534BB291427}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>libppapi_hello</RootNamespace>
<WindowsTargetPlatformVersion>10.0.17134.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
<IncludePath>C:\Users\evgeny\VKMessenger\ppapi\nacl_sdk\pepper_49\include;$(IncludePath)</IncludePath>
<LibraryPath>C:\Users\evgeny\VKMessenger\ppapi\nacl_sdk\pepper_49\lib\win_x86_64_host\Release;$(LibraryPath)</LibraryPath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
<IncludePath>C:\Users\evgeny\VKMessenger\ppapi\nacl_sdk\pepper_49\include;$(IncludePath)</IncludePath>
<LibraryPath>C:\Users\evgeny\VKMessenger\ppapi\nacl_sdk\pepper_49\lib\win_x86_32_host\Release;$(LibraryPath)</LibraryPath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
<IncludePath>C:\Users\evgeny\VKMessenger\ppapi\nacl_sdk\pepper_49\include;C:\Users\evgeny\VKMessenger\ppapi\nacl_sdk\pepper_49\include\win;$(IncludePath)</IncludePath>
<LibraryPath>C:\Users\evgeny\VKMessenger\ppapi\nacl_sdk\pepper_49\lib\win_x86_64_host\Release;$(LibraryPath)</LibraryPath>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;LIBPPAPI_HELLO_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>pthread.lib;ppapi_gles2.lib;ppapi_cpp.lib;ppapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>_DEBUG;_WINDOWS;_USRDLL;LIBPPAPI_HELLO_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;LIBPPAPI_HELLO_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>ppapi_cpp.lib;ppapi_gles2.lib;ppapi.lib;pthread.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>NDEBUG;_WINDOWS;_USRDLL;LIBPPAPI_HELLO_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>ppapi_gles2.lib;ppapi.lib;ppapi_cpp.lib;pthread.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<Text Include="ReadMe.txt" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="spinning_cube.hpp" />
<ClInclude Include="stdafx.h" />
<ClInclude Include="targetver.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="libppapi_hello.cpp" />
<ClCompile Include="spinning_cube.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,39 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<Text Include="ReadMe.txt" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="stdafx.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="targetver.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="spinning_cube.hpp">
<Filter>Source Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="libppapi_hello.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="spinning_cube.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
</Project>

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup />
</Project>

View File

@ -0,0 +1,403 @@
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This example program is based on Simple_VertexShader.c from:
//
// Book: OpenGL(R) ES 2.0 Programming Guide
// Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner
// ISBN-10: 0321502795
// ISBN-13: 9780321502797
// Publisher: Addison-Wesley Professional
// URLs: http://safari.informit.com/9780321563835
// http://www.opengles-book.com
//
#include "spinning_cube.hpp"
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include "GLES2/gl2.h"
namespace {
const float kPi = 3.14159265359f;
int GenerateCube(GLuint *vbo_vertices, GLuint *vbo_indices) {
const int num_indices = 36;
const GLfloat cube_vertices[] = {
-0.5f, -0.5f, -0.5f,
-0.5f, -0.5f, 0.5f,
0.5f, -0.5f, 0.5f,
0.5f, -0.5f, -0.5f,
-0.5f, 0.5f, -0.5f,
-0.5f, 0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
0.5f, 0.5f, -0.5f,
-0.5f, -0.5f, -0.5f,
-0.5f, 0.5f, -0.5f,
0.5f, 0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
-0.5f, -0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
0.5f, -0.5f, 0.5f,
-0.5f, -0.5f, -0.5f,
-0.5f, -0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
-0.5f, 0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
0.5f, -0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
0.5f, 0.5f, -0.5f,
};
const GLushort cube_indices[] = {
0, 2, 1,
0, 3, 2,
4, 5, 6,
4, 6, 7,
8, 9, 10,
8, 10, 11,
12, 15, 14,
12, 14, 13,
16, 17, 18,
16, 18, 19,
20, 23, 22,
20, 22, 21
};
if (vbo_vertices) {
glGenBuffers(1, vbo_vertices);
glBindBuffer(GL_ARRAY_BUFFER, *vbo_vertices);
glBufferData(GL_ARRAY_BUFFER,
sizeof(cube_vertices),
cube_vertices,
GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
if (vbo_indices) {
glGenBuffers(1, vbo_indices);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, *vbo_indices);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,
sizeof(cube_indices),
cube_indices,
GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
return num_indices;
}
GLuint LoadShader(GLenum type, const char* shader_source) {
GLuint shader = glCreateShader(type);
glShaderSource(shader, 1, &shader_source, NULL);
glCompileShader(shader);
GLint compiled = 0;
glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
if (!compiled) {
glDeleteShader(shader);
return 0;
}
return shader;
}
GLuint LoadProgram(const char* vertext_shader_source, const char* fragment_shader_source) {
GLuint vertex_shader = LoadShader(GL_VERTEX_SHADER,
vertext_shader_source);
if (!vertex_shader)
return 0;
GLuint fragment_shader = LoadShader(GL_FRAGMENT_SHADER,
fragment_shader_source);
if (!fragment_shader) {
glDeleteShader(vertex_shader);
return 0;
}
GLuint program_object = glCreateProgram();
glAttachShader(program_object, vertex_shader);
glAttachShader(program_object, fragment_shader);
glLinkProgram(program_object);
glDeleteShader(vertex_shader);
glDeleteShader(fragment_shader);
GLint linked = 0;
glGetProgramiv(program_object, GL_LINK_STATUS, &linked);
if (!linked) {
glDeleteProgram(program_object);
return 0;
}
return program_object;
}
class ESMatrix {
public:
GLfloat m[4][4];
ESMatrix() {
LoadZero();
}
void LoadZero() {
memset(this, 0x0, sizeof(ESMatrix));
}
void LoadIdentity() {
LoadZero();
m[0][0] = 1.0f;
m[1][1] = 1.0f;
m[2][2] = 1.0f;
m[3][3] = 1.0f;
}
void Multiply(ESMatrix* a, ESMatrix* b) {
ESMatrix result;
for (int i = 0; i < 4; ++i) {
result.m[i][0] = (a->m[i][0] * b->m[0][0]) +
(a->m[i][1] * b->m[1][0]) +
(a->m[i][2] * b->m[2][0]) +
(a->m[i][3] * b->m[3][0]);
result.m[i][1] = (a->m[i][0] * b->m[0][1]) +
(a->m[i][1] * b->m[1][1]) +
(a->m[i][2] * b->m[2][1]) +
(a->m[i][3] * b->m[3][1]);
result.m[i][2] = (a->m[i][0] * b->m[0][2]) +
(a->m[i][1] * b->m[1][2]) +
(a->m[i][2] * b->m[2][2]) +
(a->m[i][3] * b->m[3][2]);
result.m[i][3] = (a->m[i][0] * b->m[0][3]) +
(a->m[i][1] * b->m[1][3]) +
(a->m[i][2] * b->m[2][3]) +
(a->m[i][3] * b->m[3][3]);
}
*this = result;
}
void Frustum(float left,
float right,
float bottom,
float top,
float near_z,
float far_z) {
float delta_x = right - left;
float delta_y = top - bottom;
float delta_z = far_z - near_z;
if ((near_z <= 0.0f) ||
(far_z <= 0.0f) ||
(delta_z <= 0.0f) ||
(delta_y <= 0.0f) ||
(delta_y <= 0.0f))
return;
ESMatrix frust;
frust.m[0][0] = 2.0f * near_z / delta_x;
frust.m[0][1] = frust.m[0][2] = frust.m[0][3] = 0.0f;
frust.m[1][1] = 2.0f * near_z / delta_y;
frust.m[1][0] = frust.m[1][2] = frust.m[1][3] = 0.0f;
frust.m[2][0] = (right + left) / delta_x;
frust.m[2][1] = (top + bottom) / delta_y;
frust.m[2][2] = -(near_z + far_z) / delta_z;
frust.m[2][3] = -1.0f;
frust.m[3][2] = -2.0f * near_z * far_z / delta_z;
frust.m[3][0] = frust.m[3][1] = frust.m[3][3] = 0.0f;
Multiply(&frust, this);
}
void Perspective(float fov_y, float aspect, float near_z, float far_z) {
GLfloat frustum_h = tanf(fov_y / 360.0f * kPi) * near_z;
GLfloat frustum_w = frustum_h * aspect;
Frustum(-frustum_w, frustum_w, -frustum_h, frustum_h, near_z, far_z);
}
void Translate(GLfloat tx, GLfloat ty, GLfloat tz) {
m[3][0] += m[0][0] * tx + m[1][0] * ty + m[2][0] * tz;
m[3][1] += m[0][1] * tx + m[1][1] * ty + m[2][1] * tz;
m[3][2] += m[0][2] * tx + m[1][2] * ty + m[2][2] * tz;
m[3][3] += m[0][3] * tx + m[1][3] * ty + m[2][3] * tz;
}
void Rotate(GLfloat angle, GLfloat x, GLfloat y, GLfloat z) {
GLfloat mag = sqrtf(x * x + y * y + z * z);
GLfloat sin_angle = sinf(angle * kPi / 180.0f);
GLfloat cos_angle = cosf(angle * kPi / 180.0f);
if (mag > 0.0f) {
GLfloat xx, yy, zz, xy, yz, zx, xs, ys, zs;
GLfloat one_minus_cos;
ESMatrix rotation;
x /= mag;
y /= mag;
z /= mag;
xx = x * x;
yy = y * y;
zz = z * z;
xy = x * y;
yz = y * z;
zx = z * x;
xs = x * sin_angle;
ys = y * sin_angle;
zs = z * sin_angle;
one_minus_cos = 1.0f - cos_angle;
rotation.m[0][0] = (one_minus_cos * xx) + cos_angle;
rotation.m[0][1] = (one_minus_cos * xy) - zs;
rotation.m[0][2] = (one_minus_cos * zx) + ys;
rotation.m[0][3] = 0.0F;
rotation.m[1][0] = (one_minus_cos * xy) + zs;
rotation.m[1][1] = (one_minus_cos * yy) + cos_angle;
rotation.m[1][2] = (one_minus_cos * yz) - xs;
rotation.m[1][3] = 0.0F;
rotation.m[2][0] = (one_minus_cos * zx) - ys;
rotation.m[2][1] = (one_minus_cos * yz) + xs;
rotation.m[2][2] = (one_minus_cos * zz) + cos_angle;
rotation.m[2][3] = 0.0F;
rotation.m[3][0] = 0.0F;
rotation.m[3][1] = 0.0F;
rotation.m[3][2] = 0.0F;
rotation.m[3][3] = 1.0F;
Multiply(&rotation, this);
}
}
};
float RotationForTimeDelta(float delta_time) {
return delta_time * 40.0f;
}
float RotationForDragDistance(float drag_distance) {
return drag_distance / 5; // Arbitrary damping.
}
} // namespace
class SpinningCube::GLState {
public:
GLState();
void OnGLContextLost();
GLfloat angle_; // Survives losing the GL context.
GLuint program_object_;
GLint position_location_;
GLint mvp_location_;
GLuint vbo_vertices_;
GLuint vbo_indices_;
int num_indices_;
ESMatrix mvp_matrix_;
};
SpinningCube::GLState::GLState()
: angle_(0) {
OnGLContextLost();
}
void SpinningCube::GLState::OnGLContextLost() {
program_object_ = 0;
position_location_ = 0;
mvp_location_ = 0;
vbo_vertices_ = 0;
vbo_indices_ = 0;
num_indices_ = 0;
}
SpinningCube::SpinningCube()
: initialized_(false),
width_(0),
height_(0),
state_(new GLState()),
fling_multiplier_(1.0f),
direction_(1) {
state_->angle_ = 45.0f;
}
SpinningCube::~SpinningCube() {
if (!initialized_)
return;
if (state_->vbo_vertices_)
glDeleteBuffers(1, &state_->vbo_vertices_);
if (state_->vbo_indices_)
glDeleteBuffers(1, &state_->vbo_indices_);
if (state_->program_object_)
glDeleteProgram(state_->program_object_);
delete state_;
}
void SpinningCube::Init(uint32_t width, uint32_t height) {
width_ = width;
height_ = height;
if (!initialized_) {
initialized_ = true;
const char vertext_shader_source[] =
"uniform mat4 u_mvpMatrix;\n"
"attribute vec4 a_position;\n"
"void main()\n"
"{\n"
" gl_Position = u_mvpMatrix * a_position;\n"
"}\n";
const char fragment_shader_source[] =
"precision mediump float;\n"
"void main()\n"
"{\n"
" gl_FragColor = vec4( 0.0, 0.0, 1.0, 1.0 );\n"
"}\n";
state_->program_object_ = LoadProgram(
vertext_shader_source, fragment_shader_source);
state_->position_location_ = glGetAttribLocation(
state_->program_object_, "a_position");
state_->mvp_location_ = glGetUniformLocation(
state_->program_object_, "u_mvpMatrix");
state_->num_indices_ = GenerateCube(
&state_->vbo_vertices_, &state_->vbo_indices_);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
}
}
void SpinningCube::OnGLContextLost() {
// TODO(yzshen): Is it correct that in this case we don't need to do cleanup
// for program and buffers?
initialized_ = false;
height_ = 0;
width_ = 0;
state_->OnGLContextLost();
}
void SpinningCube::SetFlingMultiplier(float drag_distance, float drag_time) {
fling_multiplier_ = RotationForDragDistance(drag_distance) / RotationForTimeDelta(drag_time);
}
void SpinningCube::UpdateForTimeDelta(float delta_time) {
state_->angle_ += RotationForTimeDelta(delta_time) * fling_multiplier_;
if (state_->angle_ >= 360.0f)
state_->angle_ -= 360.0f;
// Arbitrary 50-step linear reduction in spin speed.
if (fling_multiplier_ > 1.0f) {
fling_multiplier_ = std::max(1.0f, fling_multiplier_ - (fling_multiplier_ - 1.0f) / 50);
}
Update();
}
void SpinningCube::UpdateForDragDistance(float distance) {
state_->angle_ += RotationForDragDistance(distance);
if (state_->angle_ >= 360.0f )
state_->angle_ -= 360.0f;
Update();
}
void SpinningCube::Draw() {
glViewport(0, 0, width_, height_);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(state_->program_object_);
glBindBuffer(GL_ARRAY_BUFFER, state_->vbo_vertices_);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, state_->vbo_indices_);
glVertexAttribPointer(state_->position_location_, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), 0);
glEnableVertexAttribArray(state_->position_location_);
glUniformMatrix4fv(state_->mvp_location_, 1, GL_FALSE, (GLfloat*) &state_->mvp_matrix_.m[0][0]);
glDrawElements(GL_TRIANGLES, state_->num_indices_, GL_UNSIGNED_SHORT, 0);
}
void SpinningCube::Update() {
float aspect = static_cast<GLfloat>(width_) / static_cast<GLfloat>(height_);
ESMatrix perspective;
perspective.LoadIdentity();
perspective.Perspective(60.0f, aspect, 1.0f, 20.0f );
ESMatrix modelview;
modelview.LoadIdentity();
modelview.Translate(0.0, 0.0, -2.0);
modelview.Rotate(state_->angle_ * direction_, 1.0, 0.0, 1.0);
state_->mvp_matrix_.Multiply(&modelview, &perspective);
}

View File

@ -0,0 +1,37 @@
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef PPAPI_EXAMPLES_GLES2_SPINNING_CUBE_SPINNING_CUBE_H_
#define PPAPI_EXAMPLES_GLES2_SPINNING_CUBE_SPINNING_CUBE_H_
#include "ppapi/c/pp_stdint.h"
class SpinningCube {
public:
SpinningCube();
~SpinningCube();
void Init(uint32_t width, uint32_t height);
void set_direction(int direction) { direction_ = direction; }
void SetFlingMultiplier(float drag_distance, float drag_time);
void UpdateForTimeDelta(float delta_time);
void UpdateForDragDistance(float distance);
void Draw();
void OnGLContextLost();
private:
class GLState;
// Disallow copy and assign.
SpinningCube(const SpinningCube& other);
SpinningCube& operator=(const SpinningCube& other);
void Update();
bool initialized_;
uint32_t width_;
uint32_t height_;
// Owned ptr.
GLState* state_;
float fling_multiplier_;
int direction_;
};
#endif // PPAPI_EXAMPLES_GLES2_SPINNING_CUBE_SPINNING_CUBE_H_

35
main.js Normal file
View File

@ -0,0 +1,35 @@
var {app, BrowserWindow} = require('electron');
var path = require('path')
var mainWindow = null;
var lib
if (process.platform != 'win32') {
lib = path.join(__dirname, 'libppapi_hello.so')
} else {
lib = path.join(__dirname, 'libppapi_hello')
if (process.arch == 'x64') {
lib = path.join(lib, 'x64')
}
lib = path.join(lib, 'Release', 'libppapi_hello.dll')
}
var plugin = lib + ';application/x-hello'
console.log(plugin)
app.commandLine.appendSwitch('register-pepper-plugins', plugin)
app.commandLine.appendSwitch('vmodule', '=ppb*=4')
app.commandLine.appendSwitch('enable-logging', 'stderr')
app.on('ready', function() {
mainWindow = new BrowserWindow({
height: 800,
width: 1024,
title: 'electron',
webPreferences : {
'plugins': true,
devTools: true,
}
});
mainWindow.loadURL('file://' + __dirname + '/nacl.html');
});

46
nacl.html Normal file
View File

@ -0,0 +1,46 @@
<!DOCTYPE html>
<html>
<!--
Copyright (c) 2013 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->
<head>
<title>hello_tutorial</title>
<script type="text/javascript">
// The 'message' event handler. This handler is fired when the NaCl module
// posts a message to the browser by calling PPB_Messaging.PostMessage()
// (in C) or pp::Instance.PostMessage() (in C++). This implementation
// simply displays the content of the message in an alert panel.
function handleMessage(message_event) {
console.log('message:', message_event.data)
//alert(message_event.data);
}
</script>
<style>
button {
position: relative;
z-index: 5;
top: -300px;
left: 350px;
}
</style>
</head>
<body>
<div id="listener">
<script type="text/javascript">
var listener = document.getElementById('listener');
listener.addEventListener('message', handleMessage, true);
</script>
<embed
id="hello_tutorial"
width="800"
height="600"
type="application/x-hello" />
</div>
<button>Кнопка поверх OpenGL</button>
</body>
</html>

8
package.json Normal file
View File

@ -0,0 +1,8 @@
{
"main": "main.js",
"name": "electron",
"description": "testing third party plugin load",
"version": "0.0.1",
"license": "MIT"
}

2
run-linux.sh Executable file
View File

@ -0,0 +1,2 @@
#!/bin/bash
./electron/electron .

2
run-macos.sh Executable file
View File

@ -0,0 +1,2 @@
#!/bin/bash
./Electron.app/Contents/MacOS/Electron .

2
run-win32.sh Executable file
View File

@ -0,0 +1,2 @@
#!/bin/bash
./electron32/electron.exe .

5
run-win64.sh Executable file
View File

@ -0,0 +1,5 @@
#!/bin/bash
export NACL_SRPC_DEBUG=255
export NACLVERBOSITY=255
export NACL_PLUGIN_DEBUG=1
./electron64/electron.exe .

31
setup-linux.sh Executable file
View File

@ -0,0 +1,31 @@
#!/bin/bash
fix_cacerts() {
cd sdk_tools/
mv cacerts.txt cacerts.txt.old
wget https://gist.githubusercontent.com/OrcaXS/df9db730a12f7e1f8b713cd3761de2c5/raw/52d9216cb8577050668ef9f6f58947be913d83b0/cacerts.txt
cd ..
./naclsdk list
}
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd $DIR
wget https://github.com/electron/electron/releases/download/v1.8.8/electron-v1.8.8-linux-x64.zip
wget https://storage.googleapis.com/nativeclient-mirror/nacl/nacl_sdk/nacl_sdk.zip
unzip nacl_sdk.zip
unzip -d electron electron-v1.8.8-linux-x64.zip
cd nacl_sdk
# gentoo fix
export EPYTHON=python2.7
# twice
fix_cacerts
fix_cacerts
./naclsdk update

26
setup-macos.sh Executable file
View File

@ -0,0 +1,26 @@
#!/bin/bash
fix_cacerts() {
cd sdk_tools/
mv cacerts.txt cacerts.txt.old
wget https://gist.githubusercontent.com/OrcaXS/df9db730a12f7e1f8b713cd3761de2c5/raw/52d9216cb8577050668ef9f6f58947be913d83b0/cacerts.txt
cd ..
./naclsdk list
}
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd $DIR
wget https://github.com/electron/electron/releases/download/v1.8.8/electron-v1.8.8-win32-x64.zip || exit
wget https://storage.googleapis.com/nativeclient-mirror/nacl/nacl_sdk/nacl_sdk.zip || exit
unzip nacl_sdk.zip
unzip electron-v1.8.8-darwin-x64.zip
cd nacl_sdk
fix_cacerts
./naclsdk update

33
setup-win.sh Executable file
View File

@ -0,0 +1,33 @@
#!/bin/bash
# https://stackoverflow.com/questions/33557506/timespec-redefinition-error
# https://github.com/Kagami/mpv.js#build-on-x86
fix_cacerts() {
cd sdk_tools/
mv cacerts.txt cacerts.txt.old
curl -Lo cacerts.txt https://gist.githubusercontent.com/OrcaXS/df9db730a12f7e1f8b713cd3761de2c5/raw/52d9216cb8577050668ef9f6f58947be913d83b0/cacerts.txt || exit 1
cd ..
./naclsdk list
}
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd $DIR
curl -Lo electron-v1.8.8-win32-x64.zip https://github.com/electron/electron/releases/download/v1.8.8/electron-v1.8.8-win32-x64.zip || exit 1
curl -Lo electron-v1.8.8-win32-ia32.zip https://github.com/electron/electron/releases/download/v1.8.8/electron-v1.8.8-win32-ia32.zip || exit 1
curl -Lo nacl_sdk.zip https://storage.googleapis.com/nativeclient-mirror/nacl/nacl_sdk/nacl_sdk.zip || exit 1
unzip nacl_sdk.zip || exit 1
unzip -d electron64 electron-v1.8.8-win32-x64.zip || exit 1
unzip -d electron32 electron-v1.8.8-win32-ia32.zip || exit 1
cd nacl_sdk
# twice!
fix_cacerts
fix_cacerts
./naclsdk update

403
spinning_cube.c Normal file
View File

@ -0,0 +1,403 @@
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This example program is based on Simple_VertexShader.c from:
//
// Book: OpenGL(R) ES 2.0 Programming Guide
// Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner
// ISBN-10: 0321502795
// ISBN-13: 9780321502797
// Publisher: Addison-Wesley Professional
// URLs: http://safari.informit.com/9780321563835
// http://www.opengles-book.com
//
#include "spinning_cube.h"
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include "GLES2/gl2.h"
namespace {
const float kPi = 3.14159265359f;
int GenerateCube(GLuint *vbo_vertices, GLuint *vbo_indices) {
const int num_indices = 36;
const GLfloat cube_vertices[] = {
-0.5f, -0.5f, -0.5f,
-0.5f, -0.5f, 0.5f,
0.5f, -0.5f, 0.5f,
0.5f, -0.5f, -0.5f,
-0.5f, 0.5f, -0.5f,
-0.5f, 0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
0.5f, 0.5f, -0.5f,
-0.5f, -0.5f, -0.5f,
-0.5f, 0.5f, -0.5f,
0.5f, 0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
-0.5f, -0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
0.5f, -0.5f, 0.5f,
-0.5f, -0.5f, -0.5f,
-0.5f, -0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
-0.5f, 0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
0.5f, -0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
0.5f, 0.5f, -0.5f,
};
const GLushort cube_indices[] = {
0, 2, 1,
0, 3, 2,
4, 5, 6,
4, 6, 7,
8, 9, 10,
8, 10, 11,
12, 15, 14,
12, 14, 13,
16, 17, 18,
16, 18, 19,
20, 23, 22,
20, 22, 21
};
if (vbo_vertices) {
glGenBuffers(1, vbo_vertices);
glBindBuffer(GL_ARRAY_BUFFER, *vbo_vertices);
glBufferData(GL_ARRAY_BUFFER,
sizeof(cube_vertices),
cube_vertices,
GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
if (vbo_indices) {
glGenBuffers(1, vbo_indices);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, *vbo_indices);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,
sizeof(cube_indices),
cube_indices,
GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
return num_indices;
}
GLuint LoadShader(GLenum type, const char* shader_source) {
GLuint shader = glCreateShader(type);
glShaderSource(shader, 1, &shader_source, NULL);
glCompileShader(shader);
GLint compiled = 0;
glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
if (!compiled) {
glDeleteShader(shader);
return 0;
}
return shader;
}
GLuint LoadProgram(const char* vertext_shader_source, const char* fragment_shader_source) {
GLuint vertex_shader = LoadShader(GL_VERTEX_SHADER,
vertext_shader_source);
if (!vertex_shader)
return 0;
GLuint fragment_shader = LoadShader(GL_FRAGMENT_SHADER,
fragment_shader_source);
if (!fragment_shader) {
glDeleteShader(vertex_shader);
return 0;
}
GLuint program_object = glCreateProgram();
glAttachShader(program_object, vertex_shader);
glAttachShader(program_object, fragment_shader);
glLinkProgram(program_object);
glDeleteShader(vertex_shader);
glDeleteShader(fragment_shader);
GLint linked = 0;
glGetProgramiv(program_object, GL_LINK_STATUS, &linked);
if (!linked) {
glDeleteProgram(program_object);
return 0;
}
return program_object;
}
class ESMatrix {
public:
GLfloat m[4][4];
ESMatrix() {
LoadZero();
}
void LoadZero() {
memset(this, 0x0, sizeof(ESMatrix));
}
void LoadIdentity() {
LoadZero();
m[0][0] = 1.0f;
m[1][1] = 1.0f;
m[2][2] = 1.0f;
m[3][3] = 1.0f;
}
void Multiply(ESMatrix* a, ESMatrix* b) {
ESMatrix result;
for (int i = 0; i < 4; ++i) {
result.m[i][0] = (a->m[i][0] * b->m[0][0]) +
(a->m[i][1] * b->m[1][0]) +
(a->m[i][2] * b->m[2][0]) +
(a->m[i][3] * b->m[3][0]);
result.m[i][1] = (a->m[i][0] * b->m[0][1]) +
(a->m[i][1] * b->m[1][1]) +
(a->m[i][2] * b->m[2][1]) +
(a->m[i][3] * b->m[3][1]);
result.m[i][2] = (a->m[i][0] * b->m[0][2]) +
(a->m[i][1] * b->m[1][2]) +
(a->m[i][2] * b->m[2][2]) +
(a->m[i][3] * b->m[3][2]);
result.m[i][3] = (a->m[i][0] * b->m[0][3]) +
(a->m[i][1] * b->m[1][3]) +
(a->m[i][2] * b->m[2][3]) +
(a->m[i][3] * b->m[3][3]);
}
*this = result;
}
void Frustum(float left,
float right,
float bottom,
float top,
float near_z,
float far_z) {
float delta_x = right - left;
float delta_y = top - bottom;
float delta_z = far_z - near_z;
if ((near_z <= 0.0f) ||
(far_z <= 0.0f) ||
(delta_z <= 0.0f) ||
(delta_y <= 0.0f) ||
(delta_y <= 0.0f))
return;
ESMatrix frust;
frust.m[0][0] = 2.0f * near_z / delta_x;
frust.m[0][1] = frust.m[0][2] = frust.m[0][3] = 0.0f;
frust.m[1][1] = 2.0f * near_z / delta_y;
frust.m[1][0] = frust.m[1][2] = frust.m[1][3] = 0.0f;
frust.m[2][0] = (right + left) / delta_x;
frust.m[2][1] = (top + bottom) / delta_y;
frust.m[2][2] = -(near_z + far_z) / delta_z;
frust.m[2][3] = -1.0f;
frust.m[3][2] = -2.0f * near_z * far_z / delta_z;
frust.m[3][0] = frust.m[3][1] = frust.m[3][3] = 0.0f;
Multiply(&frust, this);
}
void Perspective(float fov_y, float aspect, float near_z, float far_z) {
GLfloat frustum_h = tanf(fov_y / 360.0f * kPi) * near_z;
GLfloat frustum_w = frustum_h * aspect;
Frustum(-frustum_w, frustum_w, -frustum_h, frustum_h, near_z, far_z);
}
void Translate(GLfloat tx, GLfloat ty, GLfloat tz) {
m[3][0] += m[0][0] * tx + m[1][0] * ty + m[2][0] * tz;
m[3][1] += m[0][1] * tx + m[1][1] * ty + m[2][1] * tz;
m[3][2] += m[0][2] * tx + m[1][2] * ty + m[2][2] * tz;
m[3][3] += m[0][3] * tx + m[1][3] * ty + m[2][3] * tz;
}
void Rotate(GLfloat angle, GLfloat x, GLfloat y, GLfloat z) {
GLfloat mag = sqrtf(x * x + y * y + z * z);
GLfloat sin_angle = sinf(angle * kPi / 180.0f);
GLfloat cos_angle = cosf(angle * kPi / 180.0f);
if (mag > 0.0f) {
GLfloat xx, yy, zz, xy, yz, zx, xs, ys, zs;
GLfloat one_minus_cos;
ESMatrix rotation;
x /= mag;
y /= mag;
z /= mag;
xx = x * x;
yy = y * y;
zz = z * z;
xy = x * y;
yz = y * z;
zx = z * x;
xs = x * sin_angle;
ys = y * sin_angle;
zs = z * sin_angle;
one_minus_cos = 1.0f - cos_angle;
rotation.m[0][0] = (one_minus_cos * xx) + cos_angle;
rotation.m[0][1] = (one_minus_cos * xy) - zs;
rotation.m[0][2] = (one_minus_cos * zx) + ys;
rotation.m[0][3] = 0.0F;
rotation.m[1][0] = (one_minus_cos * xy) + zs;
rotation.m[1][1] = (one_minus_cos * yy) + cos_angle;
rotation.m[1][2] = (one_minus_cos * yz) - xs;
rotation.m[1][3] = 0.0F;
rotation.m[2][0] = (one_minus_cos * zx) - ys;
rotation.m[2][1] = (one_minus_cos * yz) + xs;
rotation.m[2][2] = (one_minus_cos * zz) + cos_angle;
rotation.m[2][3] = 0.0F;
rotation.m[3][0] = 0.0F;
rotation.m[3][1] = 0.0F;
rotation.m[3][2] = 0.0F;
rotation.m[3][3] = 1.0F;
Multiply(&rotation, this);
}
}
};
float RotationForTimeDelta(float delta_time) {
return delta_time * 40.0f;
}
float RotationForDragDistance(float drag_distance) {
return drag_distance / 5; // Arbitrary damping.
}
} // namespace
class SpinningCube::GLState {
public:
GLState();
void OnGLContextLost();
GLfloat angle_; // Survives losing the GL context.
GLuint program_object_;
GLint position_location_;
GLint mvp_location_;
GLuint vbo_vertices_;
GLuint vbo_indices_;
int num_indices_;
ESMatrix mvp_matrix_;
};
SpinningCube::GLState::GLState()
: angle_(0) {
OnGLContextLost();
}
void SpinningCube::GLState::OnGLContextLost() {
program_object_ = 0;
position_location_ = 0;
mvp_location_ = 0;
vbo_vertices_ = 0;
vbo_indices_ = 0;
num_indices_ = 0;
}
SpinningCube::SpinningCube()
: initialized_(false),
width_(0),
height_(0),
state_(new GLState()),
fling_multiplier_(1.0f),
direction_(1) {
state_->angle_ = 45.0f;
}
SpinningCube::~SpinningCube() {
if (!initialized_)
return;
if (state_->vbo_vertices_)
glDeleteBuffers(1, &state_->vbo_vertices_);
if (state_->vbo_indices_)
glDeleteBuffers(1, &state_->vbo_indices_);
if (state_->program_object_)
glDeleteProgram(state_->program_object_);
delete state_;
}
void SpinningCube::Init(uint32_t width, uint32_t height) {
width_ = width;
height_ = height;
if (!initialized_) {
initialized_ = true;
const char vertext_shader_source[] =
"uniform mat4 u_mvpMatrix;\n"
"attribute vec4 a_position;\n"
"void main()\n"
"{\n"
" gl_Position = u_mvpMatrix * a_position;\n"
"}\n";
const char fragment_shader_source[] =
"precision mediump float;\n"
"void main()\n"
"{\n"
" gl_FragColor = vec4( 0.0, 0.0, 1.0, 1.0 );\n"
"}\n";
state_->program_object_ = LoadProgram(
vertext_shader_source, fragment_shader_source);
state_->position_location_ = glGetAttribLocation(
state_->program_object_, "a_position");
state_->mvp_location_ = glGetUniformLocation(
state_->program_object_, "u_mvpMatrix");
state_->num_indices_ = GenerateCube(
&state_->vbo_vertices_, &state_->vbo_indices_);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
}
}
void SpinningCube::OnGLContextLost() {
// TODO(yzshen): Is it correct that in this case we don't need to do cleanup
// for program and buffers?
initialized_ = false;
height_ = 0;
width_ = 0;
state_->OnGLContextLost();
}
void SpinningCube::SetFlingMultiplier(float drag_distance, float drag_time) {
fling_multiplier_ = RotationForDragDistance(drag_distance) / RotationForTimeDelta(drag_time);
}
void SpinningCube::UpdateForTimeDelta(float delta_time) {
state_->angle_ += RotationForTimeDelta(delta_time) * fling_multiplier_;
if (state_->angle_ >= 360.0f)
state_->angle_ -= 360.0f;
// Arbitrary 50-step linear reduction in spin speed.
if (fling_multiplier_ > 1.0f) {
fling_multiplier_ = std::max(1.0f, fling_multiplier_ - (fling_multiplier_ - 1.0f) / 50);
}
Update();
}
void SpinningCube::UpdateForDragDistance(float distance) {
state_->angle_ += RotationForDragDistance(distance);
if (state_->angle_ >= 360.0f )
state_->angle_ -= 360.0f;
Update();
}
void SpinningCube::Draw() {
glViewport(0, 0, width_, height_);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(state_->program_object_);
glBindBuffer(GL_ARRAY_BUFFER, state_->vbo_vertices_);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, state_->vbo_indices_);
glVertexAttribPointer(state_->position_location_, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), 0);
glEnableVertexAttribArray(state_->position_location_);
glUniformMatrix4fv(state_->mvp_location_, 1, GL_FALSE, (GLfloat*) &state_->mvp_matrix_.m[0][0]);
glDrawElements(GL_TRIANGLES, state_->num_indices_, GL_UNSIGNED_SHORT, 0);
}
void SpinningCube::Update() {
float aspect = static_cast<GLfloat>(width_) / static_cast<GLfloat>(height_);
ESMatrix perspective;
perspective.LoadIdentity();
perspective.Perspective(60.0f, aspect, 1.0f, 20.0f );
ESMatrix modelview;
modelview.LoadIdentity();
modelview.Translate(0.0, 0.0, -2.0);
modelview.Rotate(state_->angle_ * direction_, 1.0, 0.0, 1.0);
state_->mvp_matrix_.Multiply(&modelview, &perspective);
}

37
spinning_cube.h Normal file
View File

@ -0,0 +1,37 @@
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef PPAPI_EXAMPLES_GLES2_SPINNING_CUBE_SPINNING_CUBE_H_
#define PPAPI_EXAMPLES_GLES2_SPINNING_CUBE_SPINNING_CUBE_H_
#include "ppapi/c/pp_stdint.h"
class SpinningCube {
public:
SpinningCube();
~SpinningCube();
void Init(uint32_t width, uint32_t height);
void set_direction(int direction) { direction_ = direction; }
void SetFlingMultiplier(float drag_distance, float drag_time);
void UpdateForTimeDelta(float delta_time);
void UpdateForDragDistance(float distance);
void Draw();
void OnGLContextLost();
private:
class GLState;
// Disallow copy and assign.
SpinningCube(const SpinningCube& other);
SpinningCube& operator=(const SpinningCube& other);
void Update();
bool initialized_;
uint32_t width_;
uint32_t height_;
// Owned ptr.
GLState* state_;
float fling_multiplier_;
int direction_;
};
#endif // PPAPI_EXAMPLES_GLES2_SPINNING_CUBE_SPINNING_CUBE_H_