static CanvasRenderingContext2D InternalConstructor(int w, int h) { // tested by X:\jsc.svn\examples\javascript\ImageCachedIntoLocalStorageExperiment\ImageCachedIntoLocalStorageExperiment\Application.cs var canvas = new IHTMLCanvas { width = w, height = h }; var context = (CanvasRenderingContext2D)canvas.getContext("2d"); return context; }
static WebGL2RenderingContext InternalConstructor( ) { // tested by X:\jsc.svn\examples\javascript\ImageCachedIntoLocalStorageExperiment\ImageCachedIntoLocalStorageExperiment\Application.cs // X:\jsc.svn\examples\javascript\WebGL\Test\TestWebGL2RenderingContext\TestWebGL2RenderingContext\Application.cs var canvas = new IHTMLCanvas(); var context = (WebGL2RenderingContext)canvas.getContext("experimental-webgl2"); return(context); }
public FlashPlasmaDocument() { Plasma.generatePlasma(DefaultWidth, DefaultHeight); var shift = 0; var canvas = new IHTMLCanvas(); canvas.width = DefaultWidth; canvas.height = DefaultHeight; var context = (CanvasRenderingContext2D)canvas.getContext("2d"); var xx = context.getImageData(0, 0, DefaultWidth, DefaultHeight); var x = (ImageData)(object)xx; Action AtTick = null; AtTick = delegate { var buffer = Plasma.shiftPlasma(shift); //var x = context.createImageData(DefaultWidth, DefaultHeight); var k = 0; for (int i = 0; i < DefaultWidth; i++) { for (int j = 0; j < DefaultHeight; j++) { var i4 = i * 4; var j4 = j * 4; x.data[i4 + j4 * DefaultWidth + 2] = (byte)((buffer[k] >> (0 * 8)) & 0xff); x.data[i4 + j4 * DefaultWidth + 1] = (byte)((buffer[k] >> (1 * 8)) & 0xff); x.data[i4 + j4 * DefaultWidth + 0] = (byte)((buffer[k] >> (2 * 8)) & 0xff); x.data[i4 + j4 * DefaultWidth + 3] = 0xff; k++; } } context.putImageData(xx, 0, 0, 0, 0, DefaultWidth, DefaultHeight); shift++; Native.Window.requestAnimationFrame += AtTick; }; Native.Window.requestAnimationFrame += AtTick; canvas.AttachToDocument(); }
public __Bitmap(int width, int height) { this.Width = width; this.Height = height; this.InternalCanvas = new IHTMLCanvas { width = width, height = height }; this.InternalContext = (CanvasRenderingContext2D)this.InternalCanvas.getContext("2d"); }
public FlashPlasmaDocument() { Plasma.generatePlasma(DefaultWidth, DefaultHeight); var shift = 0; var canvas = new IHTMLCanvas(); canvas.width = DefaultWidth; canvas.height = DefaultHeight; var context = (CanvasRenderingContext2D)canvas.getContext("2d"); var xx = context.getImageData(0, 0, DefaultWidth, DefaultHeight); var x = (ImageData)(object)xx; Action AtTick = null; AtTick = delegate { var buffer = Plasma.shiftPlasma(shift); //var x = context.createImageData(DefaultWidth, DefaultHeight); var k = 0; for (int i = 0; i < DefaultWidth; i++) for (int j = 0; j < DefaultHeight; j++) { var i4 = i * 4; var j4 = j * 4; x.data[i4 + j4 * DefaultWidth + 2] = (byte)((buffer[k] >> (0 * 8)) & 0xff); x.data[i4 + j4 * DefaultWidth + 1] = (byte)((buffer[k] >> (1 * 8)) & 0xff); x.data[i4 + j4 * DefaultWidth + 0] = (byte)((buffer[k] >> (2 * 8)) & 0xff); x.data[i4 + j4 * DefaultWidth + 3] = 0xff; k++; } context.putImageData(xx, 0, 0, 0, 0, DefaultWidth, DefaultHeight); shift++; Native.Window.requestAnimationFrame += AtTick; }; Native.Window.requestAnimationFrame += AtTick; canvas.AttachToDocument(); }
/// <summary> /// This is a javascript application. /// </summary> /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param> public Application(IDefault page) { var c = new IHTMLCanvas(); c.style.border = "1px solid red"; //http://www.khronos.org/webgl/public-mailing-list/archives/1002/msg00125.html c.width = w; c.height = h; page.Content.Clear(); c.AttachTo(page.Content); var gl = c.getContext("experimental-webgl"); if (gl != null) Initialize(c, (ScriptCoreLib.JavaScript.WebGL.WebGLRenderingContext)gl, page); }
/// <summary> /// This is a javascript application. /// </summary> /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param> public Application(IDefault page) { var c = new IHTMLCanvas(); c.style.border = "1px solid red"; //http://www.khronos.org/webgl/public-mailing-list/archives/1002/msg00125.html c.width = w; c.height = h; page.Content.Clear(); c.AttachTo(page.Content); var gl = c.getContext("experimental-webgl"); if (gl != null) { Initialize(c, (ScriptCoreLib.JavaScript.WebGL.WebGLRenderingContext)gl, page); } }
void InitializeContent(IDefaultPage page) { page.PageContainer.style.color = Color.Blue; var size = 600; #region canvas var canvas = new IHTMLCanvas().AttachToDocument(); Native.Document.body.style.overflow = IStyle.OverflowEnum.hidden; canvas.style.SetLocation(0, 0, size, size); canvas.width = size; canvas.height = size; #endregion #region gl - Initialise WebGL var gl = default(WebGLRenderingContext); try { gl = (WebGLRenderingContext)canvas.getContext("experimental-webgl"); } catch { } if (gl == null) { Native.Window.alert("WebGL not supported"); throw new InvalidOperationException("cannot create webgl context"); } #endregion var gl_viewportWidth = size; var gl_viewportHeight = size; var shaderProgram = gl.createProgram(); #region createShader Func<ScriptCoreLib.GLSL.Shader, WebGLShader> createShader = (src) => { var shader = gl.createShader(src); // verify if (gl.getShaderParameter(shader, gl.COMPILE_STATUS) == null) { Native.Window.alert("error in SHADER:\n" + gl.getShaderInfoLog(shader)); return null; } return shader; }; #endregion var vs = createShader(new GeometryVertexShader()); var fs = createShader(new GeometryFragmentShader()); if (vs == null || fs == null) throw new InvalidOperationException("shader failed"); gl.attachShader(shaderProgram, vs); gl.attachShader(shaderProgram, fs); gl.linkProgram(shaderProgram); gl.useProgram(shaderProgram); var shaderProgram_vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition"); gl.enableVertexAttribArray((ulong)shaderProgram_vertexPositionAttribute); // new in lesson 02 var shaderProgram_vertexColorAttribute = gl.getAttribLocation(shaderProgram, "aVertexColor"); gl.enableVertexAttribArray((ulong)shaderProgram_vertexColorAttribute); var shaderProgram_pMatrixUniform = gl.getUniformLocation(shaderProgram, "uPMatrix"); var shaderProgram_mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix"); var mvMatrix = __glMatrix.mat4.create(); var mvMatrixStack = new Stack<Float32Array>(); var pMatrix = __glMatrix.mat4.create(); #region mvMatrixScope Action mvPushMatrix = delegate { var copy = __glMatrix.mat4.create(); __glMatrix.mat4.set(mvMatrix, copy); mvMatrixStack.Push(copy); }; Action mvPopMatrix = delegate { mvMatrix = mvMatrixStack.Pop(); }; Action<Action> mvMatrixScope = h => { mvPushMatrix(); h(); mvPopMatrix(); }; #endregion #region setMatrixUniforms Action setMatrixUniforms = delegate { gl.uniformMatrix4fv(shaderProgram_pMatrixUniform, false, pMatrix); gl.uniformMatrix4fv(shaderProgram_mvMatrixUniform, false, mvMatrix); }; #endregion #region init buffers #region cube var cubeVertexPositionBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexPositionBuffer); var cubesize = 0.005f; var vertices = new[]{ // Front face -cubesize, -cubesize, cubesize, cubesize, -cubesize, cubesize, cubesize, cubesize, cubesize, -cubesize, cubesize, cubesize, // Back face -cubesize, -cubesize, -cubesize, -cubesize, cubesize, -cubesize, cubesize, cubesize, -cubesize, cubesize, -cubesize, -cubesize, // Top face -cubesize, cubesize, -cubesize, -cubesize, cubesize, cubesize, cubesize, cubesize, cubesize, cubesize, cubesize, -cubesize, // Bottom face -cubesize, -cubesize, -cubesize, cubesize, -cubesize, -cubesize, cubesize, -cubesize, cubesize, -cubesize, -cubesize, cubesize, // Right face cubesize, -cubesize, -cubesize, cubesize, cubesize, -cubesize, cubesize, cubesize, cubesize, cubesize, -cubesize, cubesize, // Left face -cubesize, -cubesize, -cubesize, -cubesize, -cubesize, cubesize, -cubesize, cubesize, cubesize, -cubesize, cubesize, -cubesize }; gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW); var cubeVertexPositionBuffer_itemSize = 3; var cubeVertexPositionBuffer_numItems = 36; // 216, 191, 18 #region colors1 var colors_orange = new[]{ 1.0f, 0.6f, 0.0f, 1.0f, // Front face 1.0f, 0.6f, 0.0f, 1.0f, // Front face 1.0f, 0.6f, 0.0f, 1.0f, // Front face 1.0f, 0.6f, 0.0f, 1.0f, // Front face 0.8f, 0.4f, 0.0f, 1.0f, // Back face 0.8f, 0.4f, 0.0f, 1.0f, // Back face 0.8f, 0.4f, 0.0f, 1.0f, // Back face 0.8f, 0.4f, 0.0f, 1.0f, // Back face 0.9f, 0.5f, 0.0f, 1.0f, // Top face 0.9f, 0.5f, 0.0f, 1.0f, // Top face 0.9f, 0.5f, 0.0f, 1.0f, // Top face 0.9f, 0.5f, 0.0f, 1.0f, // Top face 1.0f, 0.5f, 0.0f, 1.0f, // Bottom face 1.0f, 0.5f, 0.0f, 1.0f, // Bottom face 1.0f, 0.5f, 0.0f, 1.0f, // Bottom face 1.0f, 0.5f, 0.0f, 1.0f, // Bottom face 1.0f, 0.8f, 0.0f, 1.0f, // Right face 1.0f, 0.8f, 0.0f, 1.0f, // Right face 1.0f, 0.8f, 0.0f, 1.0f, // Right face 1.0f, 0.8f, 0.0f, 1.0f, // Right face 1.0f, 0.8f, 0.0f, 1.0f, // Left face 1.0f, 0.8f, 0.0f, 1.0f, // Left face 1.0f, 0.8f, 0.0f, 1.0f, // Left face 1.0f, 0.8f, 0.0f, 1.0f // Left face }; var cubeVertexColorBuffer_orange = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexColorBuffer_orange); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors_orange), gl.STATIC_DRAW); #endregion #region colors2 var colors2 = new[]{ 0.0f, 0.6f, 1.0f, 1.0f, // Front face 0.0f, 0.6f, 1.0f, 1.0f, // Front face 0.0f, 0.6f, 1.0f, 1.0f, // Front face 0.0f, 0.6f, 1.0f, 1.0f, // Front face 0.0f, 0.4f, 0.8f, 1.0f, // Back face 0.0f, 0.4f, 0.8f, 1.0f, // Back face 0.0f, 0.4f, 0.8f, 1.0f, // Back face 0.0f, 0.4f, 0.8f, 1.0f, // Back face 0.0f, 0.5f, 0.9f, 1.0f, // Top face 0.0f, 0.5f, 0.9f, 1.0f, // Top face 0.0f, 0.5f, 0.9f, 1.0f, // Top face 0.0f, 0.5f, 0.9f, 1.0f, // Top face 0.0f, 0.5f, 1.0f, 1.0f, // Bottom face 0.0f, 0.5f, 1.0f, 1.0f, // Bottom face 0.0f, 0.5f, 1.0f, 1.0f, // Bottom face 0.0f, 0.5f, 1.0f, 1.0f, // Bottom face 0.0f, 0.8f, 1.0f, 1.0f, // Right face 0.0f, 0.8f, 1.0f, 1.0f, // Right face 0.0f, 0.8f, 1.0f, 1.0f, // Right face 0.0f, 0.8f, 1.0f, 1.0f, // Right face 0.0f, 0.8f, 1.0f, 1.0f, // Left face 0.0f, 0.8f, 1.0f, 1.0f, // Left face 0.0f, 0.8f, 1.0f, 1.0f, // Left face 0.0f, 0.8f, 1.0f, 1.0f // Left face }; var cubeVertexColorBuffer2 = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexColorBuffer2); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors2), gl.STATIC_DRAW); #endregion #region colors3 var colors_green = new[]{ 0.0f, 1.0f, 0.0f, 1.0f, // Front face 0.0f, 1.0f, 0.0f, 1.0f, // Front face 0.0f, 1.0f, 0.0f, 1.0f, // Front face 0.0f, 1.0f, 0.0f, 1.0f, // Front face 0.0f, 0.4f, 0.0f, 1.0f, // Back face 0.0f, 0.4f, 0.0f, 1.0f, // Back face 0.0f, 0.4f, 0.0f, 1.0f, // Back face 0.0f, 0.4f, 0.0f, 1.0f, // Back face 0.0f, 0.5f, 0.0f, 1.0f, // Top face 0.0f, 0.5f, 0.0f, 1.0f, // Top face 0.0f, 0.5f, 0.0f, 1.0f, // Top face 0.0f, 0.5f, 0.0f, 1.0f, // Top face 0.0f, 0.7f, 0.0f, 1.0f, // Bottom face 0.0f, 0.7f, 0.0f, 1.0f, // Bottom face 0.0f, 0.7f, 0.0f, 1.0f, // Bottom face 0.0f, 0.7f, 0.0f, 1.0f, // Bottom face 0.0f, 0.8f, 0.0f, 1.0f, // Right face 0.0f, 0.8f, 0.0f, 1.0f, // Right face 0.0f, 0.8f, 0.0f, 1.0f, // Right face 0.0f, 0.8f, 0.0f, 1.0f, // Right face 0.0f, 0.9f, 0.0f, 1.0f, // Left face 0.0f, 0.9f, 0.0f, 1.0f, // Left face 0.0f, 0.9f, 0.0f, 1.0f, // Left face 0.0f, 0.9f, 0.0f, 1.0f // Left face }; var cubeVertexColorBuffer_green = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexColorBuffer_green); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors_green), gl.STATIC_DRAW); #endregion #region colors_black var colors_black = new[]{ 0.0f, 0.0f, 0.0f, 1.0f, // Front face 0.0f, 0.0f, 0.0f, 1.0f, // Front face 0.0f, 0.0f, 0.0f, 1.0f, // Front face 0.0f, 0.0f, 0.0f, 1.0f, // Front face 0.0f, 0.0f, 0.0f, 1.0f, // Back face 0.0f, 0.0f, 0.0f, 1.0f, // Back face 0.0f, 0.0f, 0.0f, 1.0f, // Back face 0.0f, 0.0f, 0.0f, 1.0f, // Back face 0.0f, 0.0f, 0.0f, 1.0f, // Top face 0.0f, 0.0f, 0.0f, 1.0f, // Top face 0.0f, 0.0f, 0.0f, 1.0f, // Top face 0.0f, 0.0f, 0.0f, 1.0f, // Top face 0.0f, 0.0f, 0.0f, 1.0f, // Bottom face 0.0f, 0.0f, 0.0f, 1.0f, // Bottom face 0.0f, 0.0f, 0.0f, 1.0f, // Bottom face 0.0f, 0.0f, 0.0f, 1.0f, // Bottom face 0.0f, 0.0f, 0.0f, 1.0f, // Right face 0.0f, 0.0f, 0.0f, 1.0f, // Right face 0.0f, 0.0f, 0.0f, 1.0f, // Right face 0.0f, 0.0f, 0.0f, 1.0f, // Right face 0.0f, 0.0f, 0.0f, 1.0f, // Left face 0.0f, 0.0f, 0.0f, 1.0f, // Left face 0.0f, 0.0f, 0.0f, 1.0f, // Left face 0.0f, 0.0f, 0.0f, 1.0f // Left face }; var cubeVertexColorBuffer_black = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexColorBuffer_black); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors_black), gl.STATIC_DRAW); #endregion var cubeVertexColorBuffer_itemSize = 4; var cubeVertexColorBuffer_numItems = 24; var cubeVertexIndexBuffer = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVertexIndexBuffer); var cubeVertexIndices = new UInt16[]{ 0, 1, 2, 0, 2, 3, // Front face 4, 5, 6, 4, 6, 7, // Back face 8, 9, 10, 8, 10, 11, // Top face 12, 13, 14, 12, 14, 15, // Bottom face 16, 17, 18, 16, 18, 19, // Right face 20, 21, 22, 20, 22, 23 // Left face }; gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(cubeVertexIndices), gl.STATIC_DRAW); var cubeVertexIndexBuffer_itemSize = 1; var cubeVertexIndexBuffer_numItems = 36; #endregion #endregion gl.clearColor(0.0f, 0.0f, 0.0f, 1.0f); gl.enable(gl.DEPTH_TEST); var IsWalking = false; var WalkMultiplier = 0.0f; var ego_x = 0f; var ego_y = 0f; var ego_z = 0f; var ego_za = 0f; var rCube = 0f; var raCube = 0f; var lastTime = 0L; Action animate = delegate { var timeNow = new IDate().getTime(); if (lastTime != 0) { var elapsed = timeNow - lastTime; var u = ego_z + ego_za * (elapsed) / 1000.0f; // script: error JSC1000: No implementation found for this native method, please implement [static System.Math.Min(System.Single, System.Single)] if (u < 0) ego_z = (float)Math.Min((double)ego_z, (double)0); else ego_z = u; ego_za -= 3.2f * (elapsed) / 1000.0f; raCube += (75 * elapsed) / 1000.0f; } lastTime = timeNow; }; Func<float, float> degToRad = (degrees) => { return degrees * (f)Math.PI / 180f; }; var c = 0; #region drawScene Action drawScene = delegate { if (ego_x < 0) ego_x = 0; if (ego_y > 0) ego_y = 0; gl.viewport(0, 0, gl_viewportWidth, gl_viewportHeight); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); __glMatrix.mat4.perspective(45f, (float)gl_viewportWidth / (float)gl_viewportHeight, 0.1f, 100.0f, pMatrix); __glMatrix.mat4.identity(mvMatrix); #region vertex gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexPositionBuffer); gl.vertexAttribPointer((ulong)shaderProgram_vertexPositionAttribute, cubeVertexPositionBuffer_itemSize, gl.FLOAT, false, 0, 0); #endregion //__glMatrix.mat4.rotate(mvMatrix, degToRad(-33), new float[] { 0f, 1f, 0f }); //__glMatrix.mat4.rotate(mvMatrix, rCube, new float[] { 1f, 0f, 0f }); #region OriginalCubeAt Action<float, float, float> OriginalCubeAt = (x, y, z) => { mvMatrixScope( delegate { __glMatrix.mat4.translate(mvMatrix, new float[] { x, y, z }); __glMatrix.mat4.rotate(mvMatrix, degToRad(raCube), new float[] { 1f, 1f, 1f }); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVertexIndexBuffer); setMatrixUniforms(); gl.drawElements(gl.TRIANGLES, cubeVertexPositionBuffer_numItems, gl.UNSIGNED_SHORT, 0); } ); }; #endregion mvMatrixScope( delegate { __glMatrix.mat4.translate(mvMatrix, new float[] { - 1.5f, 0, - 7f}); __glMatrix.mat4.rotate(mvMatrix, degToRad(-80), new float[] { 1f, 0f, 0f }); #region grid #region color gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexColorBuffer_green); gl.vertexAttribPointer((ulong)shaderProgram_vertexColorAttribute, cubeVertexColorBuffer_itemSize, gl.FLOAT, false, 0, 0); #endregion var GridZoom = 0.3f; Action<float> WriteYLine = x => { for (int i = -12; i < -1; i++) { OriginalCubeAt(x * GridZoom, (i) * GridZoom, 0); } }; for (int i = 1; i < 12; i++) WriteYLine(i); #region color gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexColorBuffer_orange); gl.vertexAttribPointer((ulong)shaderProgram_vertexColorAttribute, cubeVertexColorBuffer_itemSize, gl.FLOAT, false, 0, 0); #endregion for (int i = 1; i < 12; i++) OriginalCubeAt(i * GridZoom, 0, 0); for (int i = -12; i < 0; i++) OriginalCubeAt(0, (i) * GridZoom, 0); #endregion #region color gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexColorBuffer2); gl.vertexAttribPointer((ulong)shaderProgram_vertexColorAttribute, cubeVertexColorBuffer_itemSize, gl.FLOAT, false, 0, 0); #endregion { var _y = (float)Math.Cos(raCube * 0.05f) * 0.1f; var _x = (float)Math.Sin(raCube * 0.05f) * 0.1f; OriginalCubeAt(_x, _y, 0); } { var _y = (float)Math.Sin(rCube) * 0.2f; var _x = (float)Math.Cos(rCube) * 0.2f; OriginalCubeAt(_x, _y, 0); } mvMatrixScope( delegate { // where are we __glMatrix.mat4.translate(mvMatrix, new float[] { ego_x, ego_y, ego_z }); // rotate all of it //__glMatrix.mat4.rotate(mvMatrix, degToRad(-45), new float[] { 1f, 0f, 0f }); // which way are we looking at? __glMatrix.mat4.rotate(mvMatrix, rCube, new float[] { 0f, 0f, 1f }); #region cube Action<float, float, float> cube = (x, y, z) => { mvPushMatrix(); __glMatrix.mat4.translate(mvMatrix, new float[] { 2 * cubesize * x, 2 * cubesize * y, 2 * cubesize * z}); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVertexIndexBuffer); setMatrixUniforms(); gl.drawElements(gl.TRIANGLES, cubeVertexPositionBuffer_numItems, gl.UNSIGNED_SHORT, 0); mvPopMatrix(); }; #endregion cube #region draw Action<int, int, int> rect = (ix, iy, z) => { for (int y = 0; y < ix; y++) { for (int x = 0; x < iy; x++) { cube(x, y, z); } } }; #endregion draw #region leg Action<int, float, float> leg = (y, hiprotation, kneerotation) => { mvPushMatrix(); #region hiprotation __glMatrix.mat4.translate(mvMatrix, new float[] { 2 * cubesize * 2, 2 * cubesize * 0, 2 * cubesize * 11}); __glMatrix.mat4.rotate(mvMatrix, degToRad(hiprotation), new float[] { 0f, 1f, 0f }); __glMatrix.mat4.translate(mvMatrix, new float[] { 2 * cubesize * -2, 2 * cubesize * 0, 2 * cubesize * -11}); #endregion __glMatrix.mat4.translate(mvMatrix, new float[] { 2 * cubesize * 1, 2 * cubesize * y, 2 * cubesize * 0}); mvPushMatrix(); #region kneerotation __glMatrix.mat4.translate(mvMatrix, new float[] { 2 * cubesize * 1, 2 * cubesize * 0, 2 * cubesize * 6f}); __glMatrix.mat4.rotate(mvMatrix, degToRad(kneerotation), new float[] { 0f, 1f, 0f }); __glMatrix.mat4.translate(mvMatrix, new float[] { 2 * cubesize * -1, 2 * cubesize * 0, 2 * cubesize * -6f}); #endregion #region color gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexColorBuffer_orange); gl.vertexAttribPointer((ulong)shaderProgram_vertexColorAttribute, cubeVertexColorBuffer_itemSize, gl.FLOAT, false, 0, 0); #endregion #region lower leg rect(3, 5, 0); rect(3, 5, 1); rect(3, 5, 2); rect(3, 3, 3); #endregion #region color gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexColorBuffer2); gl.vertexAttribPointer((ulong)shaderProgram_vertexColorAttribute, cubeVertexColorBuffer_itemSize, gl.FLOAT, false, 0, 0); #endregion rect(3, 3, 4); rect(3, 3, 5); rect(3, 3, 6); mvPopMatrix(); #region upper leg mvPushMatrix(); __glMatrix.mat4.translate(mvMatrix, new float[] { 2 * cubesize * 1, 2 * cubesize * 0, 2 * cubesize * 0}); rect(3, 3, 7); rect(3, 3, 8); rect(3, 3, 9); mvPopMatrix(); #endregion #region hips rect(3, 4, 10); //rect(3, 4, 11); #endregion mvPopMatrix(); }; #endregion var seed = (raCube * WalkMultiplier * 16); #region animated_leg Action<int, int> animated_leg = (seed_offset, x) => { var seed_180 = (float)((seed + seed_offset) % 180f); var left_hip = 30f; var left_knee = 0f; if (ego_z < 0) { // crouch left_hip = -66; left_knee = left_hip * -2; } else if (ego_z > 0) { // crouch left_hip = 10; left_knee = 10; } else if (!IsWalking) { left_hip = 0; left_knee = 0; } else { left_hip = seed_180; if (left_hip > 90) { left_hip = 180 - left_hip; // -60 should be 0 - front // 0 should be 60 // 30 should be 0 - back var v = (90 - left_hip) - 70; if (v < 0) left_knee = 70 + v; else if (v == 0) left_knee = 70; else if (v > 0) left_knee = (20 - v) * (70 / 20); //page.Data1.innerText = "" + new { left_hip, v, left_knee }; } else { } left_hip -= 45; } leg(x, left_hip, left_knee); }; #endregion animated_leg(0, -2); animated_leg(90, 128 - 5); #region body mvMatrixScope( delegate { __glMatrix.mat4.translate(mvMatrix, new float[] { 2 * cubesize * 1, 2 * cubesize * -2, 2 * cubesize * 11}); rect(128, 128, 0); } ); #endregion } ); } ); }; drawScene(); #endregion #region requestAnimFrame var requestAnimFrame = (IFunction)new IFunction( @"return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(/* function FrameRequestCallback */ callback, /* DOMElement Element */ element) { window.setTimeout(callback, 1000/60); };" ).apply(null); #endregion #region tick - new in lesson 03 var tick = default(Action); tick = delegate { c++; Native.Document.title = "" + c + " " + (rCube) + " " + ego_z + " " + ego_za; drawScene(); animate(); requestAnimFrame.apply(null, IFunction.OfDelegate(tick)); }; tick(); #endregion #region onkeyup Native.Document.body.onkeyup += (e) => { //Native.Document.title = "" + new { e.KeyCode }; if (e.KeyCode == 17) { ego_z = 0; } if (e.KeyCode == 32) { ego_z = 0; ego_za = 2; } if (e.KeyCode == 38) { IsWalking = false; } if (e.KeyCode == 40) { IsWalking = false; } }; #endregion #region onkeydown Native.Document.body.onkeydown += (e) => { // see also: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes e.PreventDefault(); #region turnspeed var turnspeed = 0.05f; if (e.KeyCode == 37) { // left rCube += turnspeed; } if (e.KeyCode == 65) { // left rCube += turnspeed; } if (e.KeyCode == 39) { rCube -= turnspeed; // right } if (e.KeyCode == 68) { rCube -= turnspeed; // right } #endregion if (e.KeyCode == 17) { ego_z = -cubesize * 6; } if (e.KeyCode == 32) { ego_z = -cubesize * 6; } if (ego_z > 0) { // not on ground. cant walk :) } else { if (e.KeyCode == 38) { IsWalking = true; // mat aint working .. if (!e.shiftKey) { WalkMultiplier = 0.04f; } else { WalkMultiplier = 0.02f; } ego_y += (float)Math.Sin(rCube) * WalkMultiplier; ego_x += (float)Math.Cos(rCube) * WalkMultiplier; } if (e.KeyCode == 40) { IsWalking = true; WalkMultiplier = 0.02f; ego_y -= (float)Math.Sin(rCube) * WalkMultiplier; ego_x -= (float)Math.Cos(rCube) * WalkMultiplier; } } }; #endregion }
/// <summary> /// This is a javascript application. /// </summary> /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param> public Application(IApp page) { // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2013/201311/20131110-dae var oo = new List <THREE.Object3D>(); #region scene var window = Native.window; var camera = new THREE.PerspectiveCamera( 45, window.aspect, 1, 1000 //2000 ); camera.position.z = 400; // scene var scene = new THREE.Scene(); var ambient = new THREE.AmbientLight(0x101030); scene.add(ambient); var directionalLight = new THREE.DirectionalLight(0xffeedd); directionalLight.position.set(0, 0, 1); scene.add(directionalLight); // WebGLRenderer preserveDrawingBuffer var renderer = new THREE.WebGLRenderer( new { preserveDrawingBuffer = true } ); // https://github.com/mrdoob/three.js/issues/3836 renderer.setClearColor(0xfffff, 1); renderer.setSize(window.Width, window.Height); renderer.domElement.AttachToDocument(); renderer.domElement.style.SetLocation(0, 0); this.canvas = (IHTMLCanvas)renderer.domElement; var mouseX = 0; var mouseY = 0; var st = new Stopwatch(); st.Start(); Native.window.onframe += delegate { renderer.clear(); //camera.aspect = window.aspect; //camera.aspect = canvas.clientWidth / (double)canvas.clientHeight; //camera.aspect = canvas.aspect; camera.updateProjectionMatrix(); oo.WithEach( x => x.rotation.y = st.ElapsedMilliseconds * 0.0001 ); camera.position.x += (mouseX - camera.position.x) * .05; camera.position.y += (-mouseY - camera.position.y) * .05; camera.lookAt(scene.position); renderer.render(scene, camera); }; Native.window.onresize += delegate { if (canvas.parentNode == Native.document.body) { renderer.setSize(window.Width, window.Height); } }; #endregion new Cisco().Source.Task.ContinueWithResult( dae => { //dae.scale.x = 30; //dae.scale.y = 30; //dae.scale.z = 30; //dae.castShadow = true; //dae.receiveShadow = true; dae.scale.x = 5; dae.scale.y = 5; dae.scale.z = 5; dae.position.y = -80; scene.add(dae); oo.Add(dae); } ); }
/// <summary> /// This is a javascript application. /// </summary> /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param> public Application(IApp page) { // why are the trucks black? // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2013/201311/20131110-dae // what will happen if we resync THREE version from 70 to? Native.document.title = new { THREE.REVISION }.ToString(); var oo = new List <THREE.Object3D>(); #region scene var window = Native.window; var camera = new THREE.PerspectiveCamera( 45, window.aspect, 1, 2000 ); camera.position.z = 400; // scene var scene = new THREE.Scene(); //var ambient = new THREE.AmbientLight(0x101030); var ambient = new THREE.AmbientLight(0x808080); scene.add(ambient); var directionalLight = new THREE.DirectionalLight(0xffeedd, 0.7); directionalLight.position.set(0, 0, 1); scene.add(directionalLight); // WebGLRenderer preserveDrawingBuffer var renderer = new THREE.WebGLRenderer( new { preserveDrawingBuffer = true } ); // https://github.com/mrdoob/three.js/issues/3836 renderer.setClearColor(0xfffff, 1); renderer.setSize(window.Width, window.Height); renderer.domElement.AttachToDocument(); renderer.domElement.style.SetLocation(0, 0); this.canvas = (IHTMLCanvas)renderer.domElement; var mouseX = 0; var mouseY = 0; var st = new Stopwatch(); st.Start(); var controls = new THREE.OrbitControls(camera, renderer.domElement); Native.window.onframe += delegate { renderer.clear(); //camera.aspect = window.aspect; //camera.aspect = canvas.clientWidth / (double)canvas.clientHeight; //camera.aspect = canvas.aspect; oo.WithEach( x => x.rotation.y = st.ElapsedMilliseconds * 0.0001 ); controls.update(); camera.position = controls.center.clone(); renderer.render(scene, camera); }; Native.window.onresize += delegate { if (canvas.parentNode == Native.document.body) { renderer.setSize(window.Width, window.Height); } }; #endregion new truck().Source.Task.ContinueWithResult( dae => { //dae.scale.x = 30; //dae.scale.y = 30; //dae.scale.z = 30; dae.position.z = 65; dae.scale.x = 10; dae.scale.y = 10; dae.scale.z = 10; dae.position.y = -80; scene.add(dae); oo.Add(dae); } ); //var ref0 = "assets/WebGLColladaExperiment/HZCannon_capture_009_04032013_192834.png"; //new HZCannon().Source.Task.ContinueWithResult( // dae => // { // //dae.scale.x = 30; // //dae.scale.y = 30; // //dae.scale.z = 30; // dae.castShadow = true; // dae.receiveShadow = true; // dae.scale.x = 3; // dae.scale.y = 3; // dae.scale.z = 3; // dae.position.y = -80; // scene.add(dae); // oo.Add(dae); // } //); }
private static void AddTransform(IHTMLCanvas canvas) { canvas.style.SetMatrixTransform( new AffineTransformBase { Left = 0, Top = 0, Width = 400, Height = 400, X1 = 400, Y1 = 100, X2 = 100, Y2 = 400, X3 = 0, Y3 = 0 } ); }
static WebGL2RenderingContext InternalConstructor( ) { // tested by X:\jsc.svn\examples\javascript\ImageCachedIntoLocalStorageExperiment\ImageCachedIntoLocalStorageExperiment\Application.cs // X:\jsc.svn\examples\javascript\WebGL\Test\TestWebGL2RenderingContext\TestWebGL2RenderingContext\Application.cs // ['webgl2', 'experimental-webgl2'] // X:\jsc.svn\examples\javascript\chrome\apps\WebGL\ChromeWebGLExtensions\ChromeWebGLExtensions\Application.cs var canvas = new IHTMLCanvas(); //var context = (WebGL2RenderingContext)canvas.getContext("experimental-webgl2"); var context = (WebGL2RenderingContext)canvas.getContext("webgl2"); return context; }
public void drawImage(IHTMLCanvas image, float dx, float dy, float dw, float dh) { }
/// <summary> /// This is a javascript application. /// </summary> /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param> public Application(IApp page) { // X:\jsc.svn\examples\javascript\synergy\webgl\WebGLDraggableCubes\WebGLDraggableCubes\Application.cs // X:\jsc.svn\examples\javascript\synergy\webgl\WebGLDraggableCubes\WebGLDraggableCubes\Design\AppCode.js var camera = new PerspectiveCamera(70, Native.window.aspect, 1, 10000); camera.position.set(0, 300, 500); var scene = new Scene(); var geometry = new BoxGeometry(100, 100, 100); var random = new Random(); objects = new THREE.Mesh[10]; for (var i = 0; i < 10; i++) { var rgb = (int)(random.NextDouble() * 0xffffff); Console.WriteLine(new { i, rgb }); var obj = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial(new { color = new THREE.Color(rgb) }) ); obj.position.x = random.NextDouble() * 800 - 400; obj.position.y = random.NextDouble() * 800 - 400; obj.position.z = random.NextDouble() * 800 - 400; obj.scale.x = random.NextDouble() * 2 + 1; obj.scale.y = random.NextDouble() * 2 + 1; obj.scale.z = random.NextDouble() * 2 + 1; obj.rotation.x = random.NextDouble() * 2 * Math.PI; obj.rotation.y = random.NextDouble() * 2 * Math.PI; obj.rotation.z = random.NextDouble() * 2 * Math.PI; scene.add(obj); objects[i] = obj; } // THREE.Projector has been moved to /examples/js/renderers/Projector.js. var projector = new THREE.Projector(); // ? var renderer = new THREE.WebGLRenderer(); renderer.setClearColor(new THREE.Color(0xf0f0f0)); //renderer.setSize(Native.window.Width, Native.window.Height); renderer.setSize(); this.canvas = (IHTMLCanvas)renderer.domElement; //renderer.domElement.AttachToDocument(); this.canvas.AttachToDocument(); this.canvas.style.SetLocation(0, 0); this.canvas.css.style.cursor = IStyle.CursorEnum.pointer; this.canvas.css.active.style.cursor = IStyle.CursorEnum.move; canvas.onresize += delegate { camera.aspect = Native.window.aspect; camera.updateProjectionMatrix(); //renderer.setSize(Native.window.Width, Native.window.Height); renderer.setSize(); }; canvas.onmousedown += ( e => { e.preventDefault(); var px = (e.CursorX / (double)Native.window.Width); var py = (e.CursorY / (double)Native.window.Height); var vx = px * 2 - 1; var vy = -py * 2 + 1; Console.WriteLine( new { e.CursorX, e.CursorY, px, py, vx, vy } ); //var vector = new THREE.Vector3( // vx, // vy, // 0.5); var vector = new THREE.Vector3( (e.CursorX / (double)Native.window.Width) * 2 - 1, vy, 0.5); //var vector = new THREE.Vector3(e.CursorX , e.CursorY, 1); projector.unprojectVector(vector, camera); //var raycaster = new THREE.Raycaster(); //raycaster.set(camera.position, vector.sub(camera.position).normalize()); // var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize()); //var raycaster = projector.pickingRay(vector.sub(camera.position).normalize(), camera); //var intersects = raycaster.intersectObjects(objects, true); var intersects = raycaster.intersectObjects(objects); Console.WriteLine("Intersects len " + intersects.Length); if (intersects.Length > 0) { var holder = ((THREE.Mesh)intersects[0].@object); var forthSmallestInnerCilinder = new THREE.Mesh( new THREE.CylinderGeometry(10, 10, 10, 32), new THREE.MeshPhongMaterial( new { specular = new THREE.Color(0xa0a0a0) }) ); forthSmallestInnerCilinder.position.y = ((THREE.Raycaster_intersectObject)intersects[0]).point.y; forthSmallestInnerCilinder.position.x = ((THREE.Raycaster_intersectObject)intersects[0]).point.x; forthSmallestInnerCilinder.position.z = ((THREE.Raycaster_intersectObject)intersects[0]).point.z; scene.add(forthSmallestInnerCilinder); // Console.WriteLine(holder.visible); //intersects[0].material.color.setHex(random.NextDouble()*0xffffff); Console.WriteLine("" + ((THREE.Raycaster_intersectObject)intersects[0]).point.x); holder.material.color = new THREE.Color(0xf000ff); foreach (var i in objects) { if (i == holder) { Console.WriteLine("Equals true"); i.material.color.setRGB(200, 0, 0); } } } }); var radius = 600; double theta = 0; Native.window.onframe += (e => { if (this.canvas.parentNode == null) return; theta += 0.1; camera.position.x = radius * Math.Sin(THREE.Math.degToRad(theta)); camera.position.y = radius * Math.Sin(THREE.Math.degToRad(theta)); camera.position.z = radius * Math.Cos(THREE.Math.degToRad(theta)); camera.lookAt(scene.position); renderer.render(scene, camera); }); var ze = new ZeProperties(); ze.Show(); ze.treeView1.Nodes.Clear(); ze.Add(() => renderer); //ze.Add(() => controls); ze.Add(() => scene); ze.Left = 0; }
/// <summary> /// This is a javascript application. /// </summary> /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param> public Application(IApp page) { // what are we looking at? var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera(45, Native.window.aspect, 1, 1000); camera.position.z = 300; var renderer = new THREE.WebGLRenderer( new { preserveDrawingBuffer = true } ); renderer.setSize(); scene.add(new THREE.AmbientLight(0x333333)); var light = new THREE.DirectionalLight(0xffffff, 1); light.position.set(5, 3, 5); scene.add(light); var cube = new THREE.CubeGeometry(0.5,0.5,0.5); var material = new THREE.MeshBasicMaterial(new { color = new THREE.Color(0xADD8E6), }); var obj = new THREE.Object3D(); for (var x = 0; x < 100; x++) { for (var y = 0; y < 100; y++) { for (var zz = 0; zz < 15; zz++) { var mesh1 = new THREE.Mesh(cube, material); mesh1.position.x = x; mesh1.position.y = y; mesh1.position.z = zz; obj.add(mesh1); } } } //var mesh1 = new THREE.Mesh(cube, material); //mesh1.position.x = 1; //mesh1.position.y = 1; //mesh1.position.z = 1; //obj.add(mesh1); scene.add(obj); var z = camera.position.z; this.canvas = (IHTMLCanvas)renderer.domElement; //renderer.domElement.AttachToDocument(); this.canvas.AttachToDocument(); this.canvas.style.SetLocation(0, 0); Native.window.onframe += e => { //if (this.canvas.parentNode == null) // return; camera.aspect = canvas.clientWidth / (double)canvas.clientHeight; camera.updateProjectionMatrix(); camera.position.z += (z - camera.position.z) * e.delay.ElapsedMilliseconds / 200; // the larger the vew the slower the rotation shall be var speed = 0.0001 * e.delay.ElapsedMilliseconds + 0.007 * 96.0 / canvas.clientHeight * 1.0 / camera.position.z; //Native.document.title = new { s = 96.0 / canvas.clientHeight }.ToString(); //Native.document.title = new { speed }.ToString(); //controls.update(); //sphere.rotation.y += speed; obj.rotation.y += speed; renderer.render(scene, camera); }; Native.window.onresize += delegate { //if (canvas.parentNode == Native.document.body) // are we embedded? if (page != null) renderer.setSize(); }; }
/// <summary> /// This is a javascript application. /// </summary> /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param> public Application(IApp page) { // X:\jsc.svn\examples\javascript\synergy\webgl\WebGLDraggableCubes\WebGLDraggableCubes\Application.cs // X:\jsc.svn\examples\javascript\synergy\webgl\WebGLDraggableCubes\WebGLDraggableCubes\Design\AppCode.js var camera = new PerspectiveCamera(70, Native.window.aspect, 1, 10000); camera.position.set(0, 300, 500); var scene = new Scene(); var geometry = new BoxGeometry(100, 100, 100); var random = new Random(); objects = new THREE.Mesh[10]; for (var i = 0; i < 10; i++) { var rgb = (int)(random.NextDouble() * 0xffffff); Console.WriteLine(new { i, rgb }); var obj = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial(new { color = new THREE.Color(rgb) }) ); obj.position.x = random.NextDouble() * 800 - 400; obj.position.y = random.NextDouble() * 800 - 400; obj.position.z = random.NextDouble() * 800 - 400; obj.scale.x = random.NextDouble() * 2 + 1; obj.scale.y = random.NextDouble() * 2 + 1; obj.scale.z = random.NextDouble() * 2 + 1; obj.rotation.x = random.NextDouble() * 2 * Math.PI; obj.rotation.y = random.NextDouble() * 2 * Math.PI; obj.rotation.z = random.NextDouble() * 2 * Math.PI; scene.add(obj); objects[i] = obj; } // THREE.Projector has been moved to /examples/js/renderers/Projector.js. var projector = new THREE.Projector(); // ? var renderer = new THREE.WebGLRenderer(); renderer.setClearColor(new THREE.Color(0xf0f0f0)); //renderer.setSize(Native.window.Width, Native.window.Height); renderer.setSize(); this.canvas = (IHTMLCanvas)renderer.domElement; //renderer.domElement.AttachToDocument(); this.canvas.AttachToDocument(); this.canvas.style.SetLocation(0, 0); this.canvas.css.style.cursor = IStyle.CursorEnum.pointer; this.canvas.css.active.style.cursor = IStyle.CursorEnum.move; canvas.onresize += delegate { camera.aspect = Native.window.aspect; camera.updateProjectionMatrix(); //renderer.setSize(Native.window.Width, Native.window.Height); renderer.setSize(); }; canvas.onmousedown += ( e => { e.preventDefault(); var px = (e.CursorX / (double)Native.window.Width); var py = (e.CursorY / (double)Native.window.Height); var vx = px * 2 - 1; var vy = -py * 2 + 1; Console.WriteLine( new { e.CursorX, e.CursorY, px, py, vx, vy } ); //var vector = new THREE.Vector3( // vx, // vy, // 0.5); var vector = new THREE.Vector3( (e.CursorX / (double)Native.window.Width) * 2 - 1, vy, 0.5); //var vector = new THREE.Vector3(e.CursorX , e.CursorY, 1); projector.unprojectVector(vector, camera); //var raycaster = new THREE.Raycaster(); //raycaster.set(camera.position, vector.sub(camera.position).normalize()); // var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize()); //var raycaster = projector.pickingRay(vector.sub(camera.position).normalize(), camera); //var intersects = raycaster.intersectObjects(objects, true); var intersects = raycaster.intersectObjects(objects); Console.WriteLine("Intersects len " + intersects.Length); if (intersects.Length > 0) { var holder = ((THREE.Mesh)intersects[0].@object); var forthSmallestInnerCilinder = new THREE.Mesh( new THREE.CylinderGeometry(10, 10, 10, 32), new THREE.MeshPhongMaterial( new { specular = new THREE.Color(0xa0a0a0) }) ); forthSmallestInnerCilinder.position.y = ((THREE.Raycaster_intersectObject)intersects[0]).point.y; forthSmallestInnerCilinder.position.x = ((THREE.Raycaster_intersectObject)intersects[0]).point.x; forthSmallestInnerCilinder.position.z = ((THREE.Raycaster_intersectObject)intersects[0]).point.z; scene.add(forthSmallestInnerCilinder); // Console.WriteLine(holder.visible); //intersects[0].material.color.setHex(random.NextDouble()*0xffffff); Console.WriteLine("" + ((THREE.Raycaster_intersectObject)intersects[0]).point.x); holder.material.color = new THREE.Color(0xf000ff); foreach (var i in objects) { if (i == holder) { Console.WriteLine("Equals true"); i.material.color.setRGB(200, 0, 0); } } } }); var radius = 600; double theta = 0; Native.window.onframe += (e => { if (this.canvas.parentNode == null) { return; } theta += 0.1; camera.position.x = radius * Math.Sin(THREE.Math.degToRad(theta)); camera.position.y = radius * Math.Sin(THREE.Math.degToRad(theta)); camera.position.z = radius * Math.Cos(THREE.Math.degToRad(theta)); camera.lookAt(scene.position); renderer.render(scene, camera); }); var ze = new ZeProperties(); ze.Show(); ze.treeView1.Nodes.Clear(); ze.Add(() => renderer); //ze.Add(() => controls); ze.Add(() => scene); ze.Left = 0; }
/// <summary> /// This is a javascript application. /// </summary> /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param> public Application(IApp page) { // what are we looking at? var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera(45, Native.window.aspect, 1, 1000); camera.position.z = 300; var renderer = new THREE.WebGLRenderer( new { preserveDrawingBuffer = true } ); renderer.setSize(); scene.add(new THREE.AmbientLight(0x333333)); var light = new THREE.DirectionalLight(0xffffff, 1); light.position.set(5, 3, 5); scene.add(light); var cube = new THREE.CubeGeometry(0.5, 0.5, 0.5); var material = new THREE.MeshBasicMaterial(new { color = new THREE.Color(0xADD8E6), }); var obj = new THREE.Object3D(); for (var x = 0; x < 100; x++) { for (var y = 0; y < 100; y++) { for (var zz = 0; zz < 15; zz++) { var mesh1 = new THREE.Mesh(cube, material); mesh1.position.x = x; mesh1.position.y = y; mesh1.position.z = zz; obj.add(mesh1); } } } //var mesh1 = new THREE.Mesh(cube, material); //mesh1.position.x = 1; //mesh1.position.y = 1; //mesh1.position.z = 1; //obj.add(mesh1); scene.add(obj); var z = camera.position.z; this.canvas = (IHTMLCanvas)renderer.domElement; //renderer.domElement.AttachToDocument(); this.canvas.AttachToDocument(); this.canvas.style.SetLocation(0, 0); Native.window.onframe += e => { //if (this.canvas.parentNode == null) // return; camera.aspect = canvas.clientWidth / (double)canvas.clientHeight; camera.updateProjectionMatrix(); camera.position.z += (z - camera.position.z) * e.delay.ElapsedMilliseconds / 200; // the larger the vew the slower the rotation shall be var speed = 0.0001 * e.delay.ElapsedMilliseconds + 0.007 * 96.0 / canvas.clientHeight * 1.0 / camera.position.z; //Native.document.title = new { s = 96.0 / canvas.clientHeight }.ToString(); //Native.document.title = new { speed }.ToString(); //controls.update(); //sphere.rotation.y += speed; obj.rotation.y += speed; renderer.render(scene, camera); }; Native.window.onresize += delegate { //if (canvas.parentNode == Native.document.body) // are we embedded? if (page != null) { renderer.setSize(); } }; }
void InitializeContent(IDefault page = null) { var gl_viewportWidth = 800; var gl_viewportHeight = 640; #region canvas var canvas = new IHTMLCanvas().AttachToDocument(); Native.Document.body.style.overflow = IStyle.OverflowEnum.hidden; canvas.style.SetLocation(0, 0, gl_viewportWidth, gl_viewportHeight); canvas.width = gl_viewportWidth; canvas.height = gl_viewportHeight; #endregion #region gl - Initialise WebGL var gl = default(gl); try { gl = (gl)canvas.getContext("experimental-webgl"); } catch { } if (gl == null) { Native.window.alert("WebGL not supported"); throw new InvalidOperationException("cannot create webgl context"); } #endregion #region Dispose var IsDisposed = false; Dispose = delegate { if (IsDisposed) { return; } IsDisposed = true; canvas.Orphanize(); }; #endregion #region initShaders var shaderProgram = gl.createProgram( new GeometryVertexShader(), new GeometryFragmentShader() ); gl.linkProgram(shaderProgram); gl.useProgram(shaderProgram); var vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition"); gl.enableVertexAttribArray((uint)vertexPositionAttribute); var vertexNormalAttribute = gl.getAttribLocation(shaderProgram, "aVertexNormal"); gl.enableVertexAttribArray((uint)vertexNormalAttribute); var vertexColorAttribute = gl.getAttribLocation(shaderProgram, "aVertexColor"); gl.enableVertexAttribArray((uint)vertexColorAttribute); #endregion gl.clearColor(0.0f, 0.0f, 0.0f, 1.0f); gl.clearDepth(1.0f); gl.enable(gl.DEPTH_TEST); // missing from WebGL IDL? //gl.enable(gl.POLYGON_SMOOTH); // Enable point size gl.enable(0x8642); gl.depthFunc(gl.LEQUAL); #region initBuffers var vertexBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer); var planet = new Planet(129); var planetData = planet.generate(); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(planetData.vertices), gl.STATIC_DRAW); var vertexBuffer_itemSize = 3; var vertexBuffer_numItems = planetData.vertices.Length / 3; var colorBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(planetData.colors), gl.STATIC_DRAW); var colorBuffer_itemSize = 4; var colorBuffer_numItems = planetData.colors.Length / 4; var normalBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, normalBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(planetData.normals), gl.STATIC_DRAW); var normalBuffer_itemSize = 3; var normalBuffer_numItems = planetData.normals.Length / 3; var indexBuffer = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(planetData.indices), gl.STATIC_DRAW); var indexBuffer_itemSize = 1; var indexBuffer_numItems = planetData.indices.Length; #endregion var lastTime = 0L; var yRot = -180.0f; var ySpeed = -50.0f; #region glCore var mvMatrix = default(Matrix); var mvMatrixStack = new Stack <Matrix>(); var pMatrix = default(Matrix); Action loadIdentity = delegate { mvMatrix = __sylvester.Matrix.I(4); }; Action <float, float, float, float> perspective = (fovy, aspect, znear, zfar) => { pMatrix = __glUtils.globals.makePerspective(fovy, aspect, znear, zfar); }; Action <Matrix> multMatrix = (m) => { mvMatrix = mvMatrix.x(m); }; // http://prototypejs.org/api/array/flatten Action setMatrixUniforms = delegate { var shaderProgram_pMatrixUniform = gl.getUniformLocation(shaderProgram, "uPMatrix"); gl.uniformMatrix4fv(shaderProgram_pMatrixUniform, false, new Float32Array(pMatrix.flatten())); var shaderProgram_mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix"); gl.uniformMatrix4fv(shaderProgram_mvMatrixUniform, false, new Float32Array(mvMatrix.flatten())); var normalMatrix = mvMatrix.inverse(); normalMatrix = normalMatrix.transpose(); var nUniform = gl.getUniformLocation(shaderProgram, "uNMatrix"); gl.uniformMatrix4fv(nUniform, false, new Float32Array(mvMatrix.flatten())); }; Action <float, float[]> mvRotate = (ang, v) => { var arad = ang * Math.PI / 180.0; var m = __sylvester.Matrix.Rotation(arad, __sylvester.Vector.create(new[] { v[0], v[1], v[2] })).ensure4x4(); multMatrix(m); }; Action <f, f, f, f, f, f, f, f, f> lookAt = (ex, ey, ez, cx, cy, cz, ux, uy, uz) => { mvMatrix = mvMatrix.x(__glUtils.globals.makeLookAt(ex, ey, ez, cx, cy, cz, ux, uy, uz)); }; #endregion #region drawScene Action drawScene = delegate { gl.viewport(0, 0, gl_viewportWidth, gl_viewportHeight); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); //perspective(45f, (float)gl_viewportWidth / (float)gl_viewportHeight, 0.1f, 100.0f); perspective(60f, (float)gl_viewportWidth / (float)gl_viewportHeight, 0.1f, 1000.0f); //perspective(60f, 800 / 640, 0.1f, 1000.0f); loadIdentity(); lookAt(0, 0, 500, 0, 0, 0, 0, 1, 0); mvRotate(yRot, new[] { 0f, 1f, 0f }); gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer); gl.vertexAttribPointer((uint)vertexPositionAttribute, vertexBuffer_itemSize, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, normalBuffer); gl.vertexAttribPointer((uint)vertexNormalAttribute, normalBuffer_itemSize, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer); gl.vertexAttribPointer((uint)vertexColorAttribute, colorBuffer_itemSize, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer); setMatrixUniforms(); gl.drawElements(gl.TRIANGLES, indexBuffer_numItems, gl.UNSIGNED_SHORT, 0); //gl.drawArrays(gl.POINTS, 0, vertexBuffer.numItems); }; #endregion #region animate Action animate = () => { var timeNow = new IDate().getTime(); if (lastTime != 0) { var elapsed = timeNow - lastTime; yRot += (ySpeed * elapsed) / 1000.0f; } lastTime = timeNow; }; #endregion #region tick Action tick = null; tick = () => { drawScene(); animate(); Native.window.requestAnimationFrame += tick; }; Native.window.requestAnimationFrame += tick; #endregion #region AtResize Action AtResize = delegate { gl_viewportWidth = Native.window.Width; gl_viewportHeight = Native.window.Height; canvas.style.SetLocation(0, 0, Native.window.Width, Native.window.Height); canvas.width = Native.window.Width; canvas.height = Native.window.Height; }; #region onresize Native.window.onresize += delegate { AtResize(); }; #endregion AtResize(); #endregion #region requestFullscreen Native.Document.body.ondblclick += delegate { if (IsDisposed) { return; } // http://tutorialzine.com/2012/02/enhance-your-website-fullscreen-api/ Native.Document.body.requestFullscreen(); }; #endregion }
/// <summary> /// This is a javascript application. /// </summary> /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param> public Application(IApp page) { // http://www.doingbusiness.org/data/exploreeconomies/puerto-rico/starting-a-business // http://www.doingbusiness.org/data/exploretopics/starting-a-business // X:\jsc.svn\examples\javascript\svg\DEAGELForecast\DEAGELForecast\Application.cs // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201410/20141028 // http://www.thecommonsenseshow.com/2014/10/23/the-target-date-for-americas-depopulation-has-been-set/ // would ScriptCoreLib be able to // play navigator if we also // have the role of AppWindow or Android Widget Service? // if we are running in a SYSTEM account // the chrome no-sandbox only allows software renderer // where we get 1 frame per sec. // on older systems we may not get GL_OES_standard_derivatives // http://stackoverflow.com/questions/16795278/disable-some-gl-extensions-for-debugging-three-js-app // ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "", // or that system is just old as hell // http://stackoverflow.com/questions/16795278/disable-some-gl-extensions-for-debugging-three-js-app //http://thematicmapping.org/playground/webgl/earth/ // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201402/20140222 // Earth params var radius = 0.5; //var segments = 32; var segments = 128; var rotation = 6; var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera(45, Native.window.aspect, 0.01, 1000); camera.position.z = 1.5; var renderer = new THREE.WebGLRenderer( new { // http://stackoverflow.com/questions/20495302/transparent-background-with-three-js alpha = true, preserveDrawingBuffer = true } ); renderer.setSize(); //renderer.setClearColor( scene.add(new THREE.AmbientLight(0x333333)); var light = new THREE.DirectionalLight(0xffffff, 1); light.position.set(5, 3, 5); scene.add(light); #region sphere var sphere = new THREE.Mesh( new THREE.SphereGeometry(radius, segments, segments), new THREE.MeshPhongMaterial( new { map = new THREE.Texture().With( async s => { //0:75ms event: _2_no_clouds_4k_low view-source:36543 //Application Cache Progress event (1 of 2) http://192.168.1.72:22248/view-source 192.168.1.72/:1 //Application Cache Progress event (2 of 2) 192.168.1.72/:1 //Application Cache Cached event 192.168.1.72/:1 //1:1018ms event: _2_no_clouds_4k_low done view-source:36543 //1:1019ms event: _2_no_clouds_4k view-source:36543 //event.returnValue is deprecated. Please use the standard event.preventDefault() instead. view-source:2995 //1:16445ms event: _2_no_clouds_4k done // ~ tilde to open css editor? Console.WriteLine("event: _2_no_clouds_4k_low"); //s.image = await new _2_no_clouds_4k_low(); s.image = await new _2_no_clouds_DEAGEL_4k_low().async.oncomplete; // http://www.deagel.com/ //s.image = await new _2_no_clouds_DEAGEL_CIMSS_4k_low(); //s.image = new _2_no_clouds_4k_low(); //await s.image; s.needsUpdate = true; Console.WriteLine("event: _2_no_clouds_4k_low done"); //await 20000; //Console.WriteLine("event: _2_no_clouds_4k"); s.image = await new _2_no_clouds_4k(); s.needsUpdate = true; //Console.WriteLine("event: _2_no_clouds_4k done"); } ), bumpMap = THREE.ImageUtils.loadTexture( new elev_bump_4k().src //new elev_bump_4k_low().src ), // applies onyl to shaders to create the shadow bumpScale = 0.005, specularMap = new THREE.Texture().With( async s => { Console.WriteLine("event: water_4k_low"); s.image = await new water_4k_low().async.oncomplete; s.needsUpdate = true; Console.WriteLine("event: water_4k_low done"); await Task.Delay(20000); Console.WriteLine("event: water_4k"); s.image = await new water_4k().async.oncomplete; s.needsUpdate = true; Console.WriteLine("event: water_4k done"); } ), //specular = new THREE.Color("grey") specular = new THREE.Color(0xa0a0a0) }) ); #endregion // http://stackoverflow.com/questions/12447734/three-js-updateing-texture-on-plane sphere.rotation.y = rotation; scene.add(sphere); #region clouds var clouds = new THREE.Mesh( new THREE.SphereGeometry( //radius + 0.003, radius + 0.006, segments, segments), new THREE.MeshPhongMaterial( new { //map = THREE.ImageUtils.loadTexture( // //new fair_clouds_4k().src // new fair_clouds_4k_low().src // ), map = new THREE.Texture().With( async s => { Console.WriteLine("event: fair_clouds_4k_low"); s.image = await new fair_clouds_4k_low().async.oncomplete; s.needsUpdate = true; Console.WriteLine("event: fair_clouds_4k_low done"); await Task.Delay(20000); Console.WriteLine("event: fair_clouds_4k"); s.image = await new fair_clouds_4k().async.oncomplete; s.needsUpdate = true; Console.WriteLine("event: fair_clouds_4k done"); } ), transparent = true }) ); clouds.rotation.y = rotation; scene.add(clouds); #endregion // X:\jsc.svn\examples\javascript\chrome\apps\ChromeEarth\ChromeEarth\Application.cs // X:\jsc.svn\examples\javascript\canvas\ConvertBlackToAlpha\ConvertBlackToAlpha\Application.cs // hidden for alpha AppWindows //#if FBACKGROUND #region galaxy_starfield new THREE.Texture().With( async s => { var i = new HTML.Images.FromAssets.galaxy_starfield(); var bytes = await i.async.bytes; for (int ii = 0; ii < bytes.Length; ii += 4) { bytes[ii + 3] = (byte)(bytes[ii + 0]); bytes[ii + 0] = 0xff; bytes[ii + 1] = 0xff; bytes[ii + 2] = 0xff; } var c = new CanvasRenderingContext2D(i.width, i.height); c.bytes = bytes; s.image = c; s.needsUpdate = true; var stars_material = new THREE.MeshBasicMaterial( new { //map = THREE.ImageUtils.loadTexture(new galaxy_starfield().src), map = s, side = THREE.BackSide, transparent = true }); var stars = new THREE.Mesh( new THREE.SphereGeometry(90, 64, 64), stars_material ); // http://stackoverflow.com/questions/8502150/three-js-how-can-i-dynamically-change-objects-opacity //(stars_material as dynamic).opacity = 0.5; scene.add(stars); } ); #endregion //#endif //var controls = new THREE.TrackballControls(camera); //Native.document.body.style.margin = "0"; //Native.document.body.style.overflow = IStyle.OverflowEnum.hidden; this.canvas = (IHTMLCanvas)renderer.domElement; //renderer.domElement.AttachToDocument(); this.canvas.AttachToDocument(); this.canvas.style.SetLocation(0, 0); // jsc, what pointers do we have in store? this.canvas.css.style.cursor = IStyle.CursorEnum.pointer; this.canvas.css.active.style.cursor = IStyle.CursorEnum.move; var old = new { sphere = new { sphere.rotation.x, sphere.rotation.y }, clouds = new { clouds.rotation.x, clouds.rotation.y, }, CursorX = 0, CursorY = 0 }; var z = camera.position.z; #region sfx var sfx = new WebGLEarthByBjorn.HTML.Audio.FromAssets.SatelliteBeep_Sputnik1 { autobuffer = true, // this aint working //loop = true }; sfx.play(); #endregion //sfx.AttachToHead(); // http://soundfxnow.com/sound-fx/sputnik-satellite-beeping/ #region onmousewheel this.canvas.onmousewheel += e => { //camera.position.z = 1.5; // min max. shall adjust speed also! // max 4.0 // min 0.6 z -= 0.1 * e.WheelDirection; z = z.Max(0.6).Min(4.5); //Native.document.title = new { camera.position.z }.ToString(); }; #endregion #region onmousedown this.canvas.onmousedown += e => { var pointerLock = this.canvas == Native.document.pointerLockElement; if (e.MouseButton == IEvent.MouseButtonEnum.Middle) { // F11 ? //this.canvas.requestFullscreen(); this.canvas.requestPointerLock(); } else { // movementX no longer works old = new { sphere = new { sphere.rotation.x, sphere.rotation.y }, clouds = new { clouds.rotation.x, clouds.rotation.y, }, e.CursorX, e.CursorY }; if (pointerLock) { // skip } else { e.CaptureMouse(); } } }; #endregion canvas.css.active.style.cursor = IStyle.CursorEnum.move; // X:\jsc.svn\examples\javascript\Test\TestMouseMovement\TestMouseMovement\Application.cs #region onmousemove this.canvas.onmousemove += e => { var pointerLock = this.canvas == Native.document.pointerLockElement; //Console.WriteLine(new { e.MouseButton, pointerLock, e.movementX }); if (e.MouseButton == IEvent.MouseButtonEnum.Left) { if (pointerLock) { sphere.rotation.x += 0.01 * e.movementY; sphere.rotation.y += 0.01 * e.movementX; clouds.rotation.x += 0.01 * e.movementY; clouds.rotation.y += 0.01 * e.movementX; } else { sphere.rotation.x = old.sphere.x + 0.01 * (e.CursorY - old.CursorY); sphere.rotation.y = old.sphere.y + 0.01 * (e.CursorX - old.CursorX); clouds.rotation.x = old.clouds.x + 0.01 * (e.CursorY - old.CursorY); clouds.rotation.y = old.clouds.y + 0.01 * (e.CursorX - old.CursorX); } // Native.document.title = new { e.movementX, e.movementY }.ToString(); } }; #endregion // could we #region onframe Native.window.onframe += e => { if (this.canvas.parentNode == null) return; camera.aspect = canvas.clientWidth / (double)canvas.clientHeight; camera.updateProjectionMatrix(); camera.position.z += (z - camera.position.z) * e.delay.ElapsedMilliseconds / 200; // autorotation should pause while under mouse drag? // the larger the vew the slower the rotation shall be var speed = 0.0001 * e.delay.ElapsedMilliseconds + 0.007 * 96.0 / canvas.clientHeight * 1.0 / camera.position.z; //Native.document.title = new { s = 96.0 / canvas.clientHeight }.ToString(); //Native.document.title = new { speed }.ToString(); //controls.update(); sphere.rotation.y += speed; clouds.rotation.y += speed; renderer.render(scene, camera); }; #endregion Native.window.onresize += delegate { //if (canvas.parentNode == Native.document.body) // are we embedded? if (page != null) renderer.setSize(); }; //var ze = new ZeProperties(); //ze.Show(); //ze.treeView1.Nodes.Clear(); //ze.Add(() => renderer); ////ze.Add(() => controls); //ze.Add(() => scene); //ze.Left = 0; //new IStyle(this.canvas.css.before) //{ // content = "'do a middle click to maximize the earth dashboard'", // left = "1em", // bottom = "1em", // color = "white", // position = IStyle.PositionEnum.absolute //}; }
/// <summary> /// This is a javascript application. /// </summary> /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param> public Application(IApp page) { // SCENE scene = new THREE.Scene(); // CAMERA var SCREEN_WIDTH = Native.window.Width; var SCREEN_HEIGHT = Native.window.Height; var VIEW_ANGLE = 45; var ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT; var NEAR = 0.1; var FAR = 20000; // perspective cameras perspectiveCamera = new THREE.PerspectiveCamera(VIEW_ANGLE, ASPECT, NEAR, FAR); perspectiveCamera.position.set(0,200,550); perspectiveCamera.lookAt(scene.position); scene.add(perspectiveCamera); // orthographic cameras mapCamera = new THREE.OrthographicCamera( Native.window.Width / -2, // Left Native.window.Width / 2, // Right Native.window.Height / 2, // Top Native.window.Height / -2, // Bottom -5000, // Near 10000 ); // Far mapCamera.up = new THREE.Vector3(0,0,-1); mapCamera.lookAt( new THREE.Vector3(0,-1,0) ); scene.add(mapCamera); renderer = new THREE.WebGLRenderer( new { antialias = true } ); // RENDERER renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT); this.container = (IHTMLCanvas)renderer.domElement; this.container.AttachToDocument(); this.container.style.SetLocation(0, 0); // EVENTS //THREEx.WindowResize(renderer, mapCamera); //THREEx.FullScreen.bindKey({ charCode : 'm'.charCodeAt(0) }); // STATS //stats = new Stats(); //stats.domElement.style.position = 'absolute'; //stats.domElement.style.bottom = '0px'; //stats.domElement.style.zIndex = 100; //container.appendChild( stats.domElement ); // LIGHT var light = new THREE.PointLight(0xffffff); light.position.set(0,250,0); scene.add(light); // FLOOR var img = new uvgrid01(); var floorTexture = new THREE.Texture().With( async s => { s.image = await img; s.needsUpdate = true; }); floorTexture.wrapS = floorTexture.wrapT = THREE.RepeatWrapping; floorTexture.repeat.set( 10, 10 ); var floorMaterial = new THREE.MeshBasicMaterial( new { map = floorTexture, side = THREE.DoubleSide } ); var floorGeometry = new THREE.PlaneGeometry(2000, 2000, 10, 10); var floor = new THREE.Mesh(floorGeometry, floorMaterial); floor.position.y = -0.5; floor.rotation.x = Math.PI / 2; scene.add(floor); //////////// // CUSTOM // //////////// // materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'images/xpos.png' ) })); //materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'images/xneg.png' ) })); //materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'images/ypos.png' ) })); //materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'images/yneg.png' ) })); //materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'images/zpos.png' ) })); //materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'images/zneg.png' ) })); // create an array with six textures for cube var materialArray = new THREE.MeshBasicMaterial[6]; materialArray[0] = (new THREE.MeshBasicMaterial( new { map = new THREE.Texture().With( async s => { s.image = await new xpos(); s.needsUpdate = true; }) })); materialArray[1] = (new THREE.MeshBasicMaterial( new { map = new THREE.Texture().With( async s => { s.image = await new xneg(); s.needsUpdate = true; }) })); materialArray[2] = (new THREE.MeshBasicMaterial( new { map = new THREE.Texture().With( async s => { s.image = await new ypos(); s.needsUpdate = true; }) })); materialArray[3] = (new THREE.MeshBasicMaterial( new { map = new THREE.Texture().With( async s => { s.image = await new yneg(); s.needsUpdate = true; }) })); materialArray[4] = (new THREE.MeshBasicMaterial( new {map = new THREE.Texture().With( async s => { s.image = await new zpos(); s.needsUpdate = true; }) })); materialArray[5] = (new THREE.MeshBasicMaterial( new { map = new THREE.Texture().With( async s => { s.image = await new zneg(); s.needsUpdate = true; }) })); //var MovingCubeMat = new THREE.MeshFaceMaterial(new { material = materialArray }); var MovingCubeGeom = new THREE.CubeGeometry(50, 50, 50, 1, 1, 1); var MovingCube = new THREE.Mesh(MovingCubeGeom, new THREE.MeshBasicMaterial(new { color = new THREE.Color(0xFFFFFF) })); MovingCube.position.set(0, 25.1, 0); scene.add(MovingCube); // a little bit of scenery... var ambientlight = new THREE.AmbientLight(0x111111); scene.add( ambientlight ); // torus knot var colorMaterial = new THREE.MeshLambertMaterial(new { color = new THREE.Color(0xff3333) }); var shape = new THREE.Mesh(new THREE.TorusKnotGeometry(30, 6, 160, 10, 2, 5, 4), colorMaterial); shape.position.set(-200, 50, -200); scene.add(shape); // torus knot var colorMaterial2 = new THREE.MeshLambertMaterial(new { color = new THREE.Color(0x33ff33) }); var shape2 = new THREE.Mesh(new THREE.TorusKnotGeometry(30, 6, 160, 10, 3, 2, 4), colorMaterial2); shape2.position.set(200, 50, -200); scene.add(shape2); // torus knot var colorMaterial3 = new THREE.MeshLambertMaterial(new { color = new THREE.Color(0xffff33) }); var shape3 = new THREE.Mesh(new THREE.TorusKnotGeometry(30, 6, 160, 10, 4, 3, 4), colorMaterial3); shape3.position.set(200, 50, 200); scene.add(shape3); // torus knot var colorMaterial4 = new THREE.MeshLambertMaterial(new { color = new THREE.Color(0x3333ff) }); var shape4 = new THREE.Mesh(new THREE.TorusKnotGeometry(30, 6, 160, 10, 3, 4, 4), colorMaterial4); shape4.position.set(-200, 50, 200); scene.add(shape4); renderer.setSize(Native.window.Width, Native.window.Height); renderer.setClearColor( 0x000000, 1 ); renderer.autoClear = false; Native.window.onframe += e => { perspectiveCamera.updateProjectionMatrix(); render(); }; var isPushed = false; this.container.onkeydown += m => { isPushed = true; if (isPushed) { //var delta = clock.getDelta(); // seconds. var moveDistance = 200 * 2; // 200 pixels per second var rotateAngle = Math.PI / 2 * 2; // pi/2 radians (90 degrees) per second // local transformations // move forwards/backwards/left/right if (m.KeyCode == 87) MovingCube.translateZ(-moveDistance); if (m.KeyCode == 83) MovingCube.translateZ(moveDistance); if (m.KeyCode == 81) MovingCube.translateX(-moveDistance); if (m.KeyCode == 69) MovingCube.translateX(moveDistance); //// rotate left/right/up/down //var rotation_matrix = new THREE.Matrix4().identity(); //if (m.KeyCode == 65) // MovingCube.rotateOnAxis(new THREE.Vector3(0, 1, 0), rotateAngle); //if (m.KeyCode == 68) // MovingCube.rotateOnAxis(new THREE.Vector3(0, 1, 0), -rotateAngle); //if (m.KeyCode == 90) //{ // MovingCube.position.set(0, 25.1, 0); // MovingCube.rotation.set(0, 0, 0); //} } }; this.container.onkeyup += e => { isPushed = false; }; Native.window.onresize += delegate { //if (canvas.parentNode == Native.document.body) // are we embedded? if (page != null) renderer.setSize(); }; }
/// <summary> /// This is a javascript application. /// </summary> /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param> public Application(IApp page) { "Spiral".ToDocumentTitle(); var canvas = new IHTMLCanvas().AttachToDocument(); Native.Document.body.style.overflow = IStyle.OverflowEnum.hidden; canvas.style.SetLocation(0, 0); #region gl var gl = default(WebGLRenderingContext); try { gl = (WebGLRenderingContext)canvas.getContext("experimental-webgl"); } catch { } if (gl == null) { //Native.Window.alert("WebGL not supported"); //throw new InvalidOperationException("cannot create webgl context"); return; } #endregion #region Dispose var IsDisposed = false; //Dispose = delegate //{ // if (IsDisposed) // return; // IsDisposed = true; // canvas.Orphanize(); //}; #endregion var s = new SpiralSurface(this); this.onsurface(gl); #region AtResize Action AtResize = delegate { if (IsDisposed) { return; } canvas.width = Native.window.Width; canvas.height = Native.window.Height; this.onresize(Native.window.Width, Native.window.Height); }; AtResize(); Native.window.onresize += delegate { AtResize(); }; #endregion Native.window.onframe += delegate { this.onframe(); }; #region requestFullscreen Native.Document.body.ondblclick += delegate { if (IsDisposed) return; // http://tutorialzine.com/2012/02/enhance-your-website-fullscreen-api/ Native.Document.body.requestFullscreen(); }; #endregion Native.Document.onmousemove += e => { s.ucolor_1 = e.CursorX / Native.window.Width; s.ucolor_2 = e.CursorY / Native.window.Height; }; }
/// <summary> /// This is a javascript application. /// </summary> /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param> public Application(IApp page) { onMouseDownPosition = new THREE.Vector2(); //camera = new THREE.PerspectiveCamera( // 45, // Native.window.aspect, // 1, // 1000 // //2000 // ); //camera.position.z = 400; camera = new THREE.PerspectiveCamera(40, Native.window.Width / Native.window.Height, 1, 10000); camera.position.x = radious * Math.Sin(theta * Math.PI / 360) * Math.Cos(phi * Math.PI / 360); camera.position.y = radious * Math.Sin(phi * Math.PI / 360); camera.position.z = radious * Math.Cos(theta * Math.PI / 360) * Math.Cos(phi * Math.PI / 360); scene = new THREE.Scene(); var ambientLight = new THREE.AmbientLight(0x404040); scene.add(ambientLight); var directionalLight = new THREE.DirectionalLight(0xffeedd); directionalLight.position.set(0, 0, 1); scene.add(directionalLight); var obj = new THREE.Object3D(); var buttomCylinder1 = new THREE.Mesh( new THREE.CylinderGeometry(50, 50, 50, 32), new THREE.MeshPhongMaterial( new { specular = new THREE.Color(0xa0a0a0), color = new THREE.Color(0xa0a0a0), }) ); buttomCylinder1.rotation.x = -90 * Math.PI / 180; //buttomCylinder1.position.x = 0; //buttomCylinder1.position.y = 0; //buttomCylinder1.position.z = 0; obj.add(buttomCylinder1); scene.add(obj); var renderer = new THREE.WebGLRenderer( new { preserveDrawingBuffer = true } ); renderer.setSize(Native.window.Width, Native.window.Height); this.canvas = (IHTMLCanvas)renderer.domElement; this.canvas.AttachToDocument(); this.canvas.style.SetLocation(0, 0); camera.lookAt(scene.position); scene.add(obj); //var plane = new THREE.Mesh(new THREE.Plane(1000, 1000)); //plane.rotation.x = -90 * Math.PI / 180; //scene.add(plane); #region onmousedown this.canvas.onmousedown += e => { e.preventDefault(); isMouseDown = true; onMouseDownTheta = theta; onMouseDownPhi = phi; onMouseDownPosition.x = e.CursorX; onMouseDownPosition.y = e.CursorY; }; #endregion this.canvas.onmousewheel += e => { radious -= e.WheelDirection; camera.position.x = radious * Math.Sin(theta * Math.PI / 360) * Math.Cos(phi * Math.PI / 360); camera.position.y = radious * Math.Sin(phi * Math.PI / 360); camera.position.z = radious * Math.Cos(theta * Math.PI / 360) * Math.Cos(phi * Math.PI / 360); camera.updateMatrix(); }; #region onmousemove this.canvas.onmousemove += e => { e.preventDefault(); if (isMouseDown) { theta = -((e.CursorX - onMouseDownPosition.x) * 0.5) + onMouseDownTheta; phi = ((e.CursorX - onMouseDownPosition.y) * 0.5) + onMouseDownPhi; phi = Math.Min(360, Math.Max(0, phi)); camera.position.x = radious * Math.Sin(theta * Math.PI / 360) * Math.Cos(phi * Math.PI / 360); camera.position.y = radious * Math.Sin(phi * Math.PI / 360); camera.position.z = radious * Math.Cos(theta * Math.PI / 360) * Math.Cos(phi * Math.PI / 360); camera.updateMatrix(); } }; #endregion this.canvas.onmouseup += e => { e.preventDefault(); isMouseDown = false; onMouseDownPosition.x = e.CursorX - onMouseDownPosition.x; onMouseDownPosition.y = e.CursorY - onMouseDownPosition.y; }; // could we Native.window.onframe += e => { renderer.clear(); camera.updateProjectionMatrix(); camera.lookAt(scene.position); renderer.render(scene, camera); }; Native.window.onresize += delegate { //if (canvas.parentNode == Native.document.body) // are we embedded? if (page != null) { renderer.setSize(); } }; }
public Application(IDefault page = null) { var size = 500; var gl = new WebGLRenderingContext(antialias: true, preserveDrawingBuffer: true); this.canvas = gl.canvas.AttachToDocument(); canvas.style.backgroundColor = "black"; //canvas.style.backgroundColor = "blue"; Native.document.body.style.overflow = IStyle.OverflowEnum.hidden; canvas.style.SetLocation(0, 0, size, size); canvas.width = size; canvas.height = size; var gl_viewportWidth = size; var gl_viewportHeight = size; canvas.style.SetLocation(0, 0, gl_viewportWidth, gl_viewportHeight); #region IsDisposed var IsDisposed = false; this.Dispose = delegate { if (IsDisposed) { return; } IsDisposed = true; canvas.Orphanize(); }; #endregion #region AtResize Action AtResize = delegate { gl_viewportWidth = Native.window.Width; gl_viewportHeight = Native.window.Height; canvas.style.SetSize(gl_viewportWidth, gl_viewportHeight); canvas.width = gl_viewportWidth; canvas.height = gl_viewportHeight; }; if (page != null) { Native.window.onresize += e => { AtResize(); } } ; AtResize(); #endregion #region requestFullscreen Native.Document.body.ondblclick += delegate { if (IsDisposed) { return; } // http://tutorialzine.com/2012/02/enhance-your-website-fullscreen-api/ Native.Document.body.requestFullscreen(); }; #endregion #region initShaders var shaderProgram = gl.createProgram( new GeometryVertexShader(), new GeometryFragmentShader() ); gl.linkProgram(shaderProgram); gl.useProgram(shaderProgram); var shaderProgram_vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition"); gl.enableVertexAttribArray((uint)shaderProgram_vertexPositionAttribute); var shaderProgram_textureCoordAttribute = gl.getAttribLocation(shaderProgram, "aTextureCoord"); gl.enableVertexAttribArray((uint)shaderProgram_textureCoordAttribute); var shaderProgram_pMatrixUniform = gl.getUniformLocation(shaderProgram, "uPMatrix"); var shaderProgram_mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix"); // new in lesson 05 var shaderProgram_samplerUniform = gl.getUniformLocation(shaderProgram, "uSampler"); #endregion var mvMatrix = glMatrix.mat4.create(); var mvMatrixStack = new Stack <Float32Array>(); var pMatrix = glMatrix.mat4.create(); #region new in lesson 03 Action mvPushMatrix = delegate { var copy = glMatrix.mat4.create(); glMatrix.mat4.set(mvMatrix, copy); mvMatrixStack.Push(copy); }; Action mvPopMatrix = delegate { mvMatrix = mvMatrixStack.Pop(); }; #endregion #region setMatrixUniforms Action setMatrixUniforms = delegate { gl.uniformMatrix4fv(shaderProgram_pMatrixUniform, false, pMatrix); gl.uniformMatrix4fv(shaderProgram_mvMatrixUniform, false, mvMatrix); }; #endregion #region init buffers #region cubeVertexPositionBuffer var cubeVertexPositionBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexPositionBuffer); var vertices = new[] { // Front face RED -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, //// Back face YELLOW //-1.0f, -1.0f, -1.0f, //-1.0f, 1.0f, -1.0f, // 1.0f, 1.0f, -1.0f, // 1.0f, -1.0f, -1.0f, //// Top face GREEN //-1.0f, 1.0f, -1.0f, //-1.0f, 1.0f, 1.0f, // 1.0f, 1.0f, 1.0f, // 1.0f, 1.0f, -1.0f, //// Bottom face BEIGE //-1.0f, -1.0f, -1.0f, // 1.0f, -1.0f, -1.0f, // 1.0f, -1.0f, 1.0f, //-1.0f, -1.0f, 1.0f, //// Right face PURPLE // 1.0f, -1.0f, -1.0f, // 1.0f, 1.0f, -1.0f, // 1.0f, 1.0f, 1.0f, // 1.0f, -1.0f, 1.0f, //// Left face //-1.0f, -1.0f, -1.0f, //-1.0f, -1.0f, 1.0f, //-1.0f, 1.0f, 1.0f, //-1.0f, 1.0f, -1.0f }; gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW); var cubeVertexPositionBuffer_itemSize = 3; //var cubeVertexPositionBuffer_numItems = 6 * 6; var cubeVertexPositionBuffer_numItems = 6 * 1; #endregion #region cubeVertexTextureCoordBuffer var cubeVertexTextureCoordBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexTextureCoordBuffer); var textureCoords = new float[] { // Front face 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, //// Back face //1.0f, 0.0f, //1.0f, 1.0f, //0.0f, 1.0f, //0.0f, 0.0f, //// Top face //0.0f, 1.0f, //0.0f, 0.0f, //1.0f, 0.0f, //1.0f, 1.0f, //// Bottom face //1.0f, 1.0f, //0.0f, 1.0f, //0.0f, 0.0f, //1.0f, 0.0f, //// Right face //1.0f, 0.0f, //1.0f, 1.0f, //0.0f, 1.0f, //0.0f, 0.0f, //// Left face //0.0f, 0.0f, //1.0f, 0.0f, //1.0f, 1.0f, //0.0f, 1.0f, }; gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(textureCoords), gl.STATIC_DRAW); var cubeVertexTextureCoordBuffer_itemSize = 2; var cubeVertexTextureCoordBuffer_numItems = 24; var cubeVertexIndexBuffer = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVertexIndexBuffer); var cubeVertexIndices = new UInt16[] { 0, 1, 2, 0, 2, 3, // Front face 4, 5, 6, 4, 6, 7, // Back face 8, 9, 10, 8, 10, 11, // Top face 12, 13, 14, 12, 14, 15, // Bottom face 16, 17, 18, 16, 18, 19, // Right face 20, 21, 22, 20, 22, 23 // Left face }; gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(cubeVertexIndices), gl.STATIC_DRAW); var cubeVertexIndexBuffer_itemSize = 1; var cubeVertexIndexBuffer_numItems = cubeVertexPositionBuffer_numItems; #endregion #endregion var tex1 = gl.createTexture(); var tex1i = new WebGLSVGAnonymous.HTML.Images.FromAssets.Anonymous_LogosSingleNoWings(); //var tex1i = new WebGLSVGAnonymous.HTML.Images.FromAssets.nehe(); // WebGL: drawElements: texture bound to texture unit 0 is not renderable. It maybe non-power-of-2 and have incompatible texture filtering or is not 'texture complete'. Or the texture is Float or Half Float type with linear filtering while OES_float_linear or OES_half_float_linear extension is not enabled. tex1i.width = 1024 * 2; tex1i.height = 1024 * 2; // initTexture new in lesson 05 var tex0 = gl.createTexture(); var tex0i = new WebGLSVGAnonymous.HTML.Images.FromAssets.Anonymous_LogosSingleWings(); //var tex0i = new WebGLSVGAnonymous.HTML.Images.FromAssets.nehe(); // WebGL: drawElements: texture bound to texture unit 0 is not renderable. It maybe non-power-of-2 and have incompatible texture filtering or is not 'texture complete'. Or the texture is Float or Half Float type with linear filtering while OES_float_linear or OES_half_float_linear extension is not enabled. tex0i.width = 1024 * 2; tex0i.height = 1024 * 2; tex1i.InvokeOnComplete( delegate { tex0i.InvokeOnComplete( delegate { // this is a workaround // chrome has a bug where svg textures are merged.. var tex1ii = new CanvasRenderingContext2D(1024 * 2, 1024 * 2); tex1ii.drawImage( tex1i, 0, 0, 1024 * 2, 1024 * 2); { gl.activeTexture(gl.TEXTURE1); gl.bindTexture(gl.TEXTURE_2D, tex1); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, tex1ii.canvas); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, (int)gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, (int)gl.NEAREST); gl.generateMipmap(gl.TEXTURE_2D); gl.bindTexture(gl.TEXTURE_2D, null); } { gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, tex0); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1); // http://msdn.microsoft.com/en-us/library/ie/dn302435(v=vs.85).aspx gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, tex0i); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, (int)gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, (int)gl.NEAREST); gl.generateMipmap(gl.TEXTURE_2D); gl.bindTexture(gl.TEXTURE_2D, null); } //gl.clearColor(0.0f, 0.0f, 0.0f, 1.0f); //gl.enable(gl.DEPTH_TEST); gl.enable(gl.BLEND); //gl.enable(gl.CULL_FACE); // http://stackoverflow.com/questions/11521035/blending-with-html-background-in-webgl gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); var xRot = 0.0f; var yRot = 0.0f; var zRot = 0.0f; var lastTime = 0L; Action animate = delegate { var timeNow = new IDate().getTime(); if (lastTime != 0) { var elapsed = timeNow - lastTime; //xRot += (9 * elapsed) / 1000.0f; yRot += (40 * elapsed) / 1000.0f; //zRot += (9 * elapsed) / 1000.0f; } lastTime = timeNow; }; Func <float, float> degToRad = (degrees) => { return(degrees * (f)Math.PI / 180f); }; var f = new Designer(); f.trackBar1.Value = -20; f.trackBar2.Value = -10; if (page != null) { f.Show(); } Action <bool> drawScene = Anonymous_LogosSingleNoWings_Checked => { glMatrix.mat4.perspective(45f, (float)gl_viewportWidth / (float)gl_viewportHeight, 0.1f, 100.0f, pMatrix); glMatrix.mat4.identity(mvMatrix); var u1 = f.trackBar1.Value * 0.1f; glMatrix.mat4.translate(mvMatrix, new float[] { 0.0f, 0.0f, u1 }); //glMatrix.mat4.rotate(mvMatrix, degToRad(xRot), new[] { 1f, 0f, 0f }); if (Anonymous_LogosSingleNoWings_Checked) { glMatrix.mat4.rotate(mvMatrix, degToRad(yRot), new[] { 0f, 1f, 0f }); } else { glMatrix.mat4.rotate(mvMatrix, degToRad(f.trackBar3.Value), new[] { 0f, 1f, 0f }); } var u2 = f.trackBar2.Value * 0.1f; glMatrix.mat4.translate(mvMatrix, new float[] { 0.0f, 0.0f, u2 }); Native.document.title = new { u1, u2 }.ToString(); //glMatrix.mat4.rotate(mvMatrix, degToRad(zRot), new[] { 0f, 0f, 1f }); gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexPositionBuffer); gl.vertexAttribPointer((uint)shaderProgram_vertexPositionAttribute, cubeVertexPositionBuffer_itemSize, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexTextureCoordBuffer); gl.vertexAttribPointer((uint)shaderProgram_textureCoordAttribute, cubeVertexTextureCoordBuffer_itemSize, gl.FLOAT, false, 0, 0); if (Anonymous_LogosSingleNoWings_Checked) { gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, tex0); gl.uniform1i(shaderProgram_samplerUniform, 0); } else { gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, tex1); gl.uniform1i(shaderProgram_samplerUniform, 0); } gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVertexIndexBuffer); setMatrixUniforms(); gl.drawElements(gl.TRIANGLES, cubeVertexIndexBuffer_numItems, gl.UNSIGNED_SHORT, 0); gl.bindTexture(gl.TEXTURE_2D, null); }; var c = 0; Native.window.onframe += delegate { c++; if (page == null) { gl_viewportWidth = canvas.clientWidth; gl_viewportHeight = canvas.clientHeight; canvas.style.SetLocation(0, 0, gl_viewportWidth, gl_viewportHeight); canvas.width = gl_viewportWidth; canvas.height = gl_viewportHeight; } gl.viewport(0, 0, gl_viewportWidth, gl_viewportHeight); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); if (f.Anonymous_LogosSingleNoWings.Checked) { drawScene(false); } if (f.Anonymous_LogosSingleWings.Checked) { drawScene(true); } animate(); }; } ); } ); } }
//public static Task WriteAllBytes(this DirectoryEntry that, string filename, WebGL.WebGLRenderingContext gl) //{ //} public static Task WriteAllBytes(this DirectoryEntry that, string filename, IHTMLCanvas canvas) { // 754986ms WriteAllBytes { filename = 00272.png, position = 3101246, size = 3101246 } //view-source:63706 FileError is deprecated. Please use the 'name' or 'message' attributes of DOMError rather than 'code'. //view-source:54105 757622ms WriteAllBytes onerror { code = 7, message = An operation that depends on state cached in an interface object was made but the state had changed since it was read from disk., error = [object FileError] } //view-source:54105 757623ms out of files? //view-source:54105 757624ms WriteAllBytes { filename = 00273.png, position = 0, size = 3143207 } //view-source:54105 757624ms what happened? retry? //view-source:54105 760625ms what happened? retry! //view-source:54105 760626ms what happened? retry! retry7? //view-source:38832 Uncaught TypeError: Cannot read property 'toDataURL' of null //var data = canvas.toDataURL(); // Z:\jsc.svn\examples\javascript\chrome\apps\WebGL\360\x360eiffieballs\Application.cs //Z:\jsc.svn\examples\javascript\chrome\apps\WebGL\360\x360x83\Application.cs // 8K img png will be 50mb //var data = canvas.toDataURL(quality: 0.9); var data = canvas.toDataURL(quality: 1.0); //var data = canvas.toDataURL(quality: 0.1); // Z:\jsc.svn\examples\javascript\chrome\apps\WebGL\360stereo\x360stereotransition\Application.cs var prefix = "base64,"; var fileBytes = System.Convert.FromBase64String( data.Substring(data.IndexOf(prefix) + prefix.Length)); // https://groups.google.com/a/chromium.org/forum/#!topic/blink-dev/jcrEI_jfYFs // this blob wont delete? bytes = new Blob( blobParts: new ArrayBufferView[] { fileBytes }, options: new { type = "application/octet-stream;" + filename } ); fileBytes = null; data = null; //canvas = null; var c = new TaskCompletionSource<DirectoryEntry>(); // can do up to 120 files? // not disposing blob? //Blob blob = bytes; that.getFile( //"0000.jpg", filename, new { create = true, exclusive = false }, fentry => { // {{ fentry = [object FileEntry] }} //new IHTMLPre { new { fentry } }.AttachToDocument(); fentry.createWriter( w => { //new IHTMLPre { new { w } }.AttachToDocument(); // new Blob([document.getElementById("HTMLFile").value], //{ type: 'text/plain'} //var blob = new Blob( // blobParts: new ArrayBufferView[] { fileBytes }, // options: new { type = "application/octet-stream" } //); // http://stackoverflow.com/questions/12168909/blob-from-dataurl //w.write(fileBytes); //w.write(bytes); ////w.write() //// ready? var retry7 = false; //c.SetResult(that); //WriteAllBytes onerror { error = [object FileError], code = 7 } w.onerror = new Action( delegate { // https://developer.mozilla.org/en-US/docs/Web/API/FileError Console.WriteLine("WriteAllBytes onerror " + new { w.error.code, w.error.message, w.error }); if (w.error.code == 7) { Console.WriteLine("out of files? " + new { filename }); //https://code.google.com/p/chromium/issues/detail?id=83736 retry7 = true; } } ); //1063359ms WriteAllBytes onerror { code = 7, message = An operation that depends on state cached in an interface object was made but the state had changed since it was read from disk., error = [object FileError] } //view-source:54104 1063360ms out of files? //view-source:54104 1063361ms WriteAllBytes { filename = 00265.png, position = 0, size = 3058562 } //view-source:54104 1063361ms what happened? retry? //view-source:54104 1066363ms what happened? retry! w.onwriteend = new Action( delegate { var position = w.position; Console.WriteLine("onwriteend WriteAllBytes " + new { filename, position, bytes.size }); if (position < (long)bytes.size) { Console.WriteLine("what happened? retry? " + new { filename }); if (position == 0) { Native.setTimeout( delegate { if (retry7) { Console.WriteLine("what happened? retry7? " + new { filename }); WriteAllBytes(that, filename, canvas).ContinueWith( delegate { Console.WriteLine("what happened? retry7! " + new { filename }); c.SetResult(that); fentry = null; } ); return; } Console.WriteLine("what happened? retry! " + new { filename }); w.write(bytes); }, 5000 ); } return; } // https://groups.google.com/a/chromium.org/forum/#!topic/chromium-html5/6Behx6zrbCI //Console.WriteLine("WriteAllBytes Blob close"); // https://code.google.com/p/chromium/issues/detail?id=404301 // chrome://blob-internals/ //bytes.close(); bytes = null; //w.truncate(w.position); w = null; // need it? //Native.window.requestAnimationFrame += delegate //Console.WriteLine("WriteAllBytes yield"); c.SetResult(that); fentry = null; } ); w.write(bytes); } ); } ); return c.Task; }
void InitializeContent(IDefault page = null) { var vertices = new List<float>(); var indices = new List<ushort>(); var colors = new List<float>(); var uvs = new List<float>(); var radius = 7; var currentRadius = radius; var segments = (ushort)24; var spacing = 2; var numRings = 18; var index = (ushort)0; var currentTime = 0.0f; #region generateGeometry Action generateGeometry = delegate { for (var ring = 0; ring < numRings; ring++) { for (var segment = 0; segment < segments; segment++) { var degrees = (360 / segments) * segment; var radians = (Math.PI / 180) * degrees; var x = (float)Math.Cos(radians) * currentRadius; var y = (float)Math.Sin(radians) * currentRadius; var z = ring * -spacing; vertices.Add(x, y, z); if (segment < (segments - 1) / 2) { uvs.Add((1.0f / (segments)) * segment * 2, (1.0f / 4) * ring); } else { uvs.Add(2.0f - ((1.0f / (segments)) * segment * 2), (1.0f / 4) * ring); } var color = 1.0f - ((1.0f / (numRings - 1)) * ring); colors.Add(color, color, color, 1.0f); if (ring < numRings - 1) { if (segment < segments - 1) { indices.Add(index, (ushort)(index + segments + 1), (ushort)(index + segments)); indices.Add(index, (ushort)(index + 1), (ushort)(index + segments + 1)); } else { indices.Add(index, (ushort)(index + 1), (ushort)(index + segments)); indices.Add(index, (ushort)(index - segments + 1), (ushort)(index + 1)); } } index++; } currentRadius -= radius / numRings; } }; generateGeometry(); #endregion var size = 500; var gl_viewportWidth = size; var gl_viewportHeight = size; #region canvas var canvas = new IHTMLCanvas().AttachToDocument(); Native.Document.body.style.overflow = IStyle.OverflowEnum.hidden; canvas.style.SetLocation(0, 0, size, size); canvas.width = size; canvas.height = size; #endregion #region gl - Initialise WebGL var gl = default(WebGLRenderingContext); try { gl = (WebGLRenderingContext)canvas.getContext("experimental-webgl"); } catch { } if (gl == null) { Native.window.alert("WebGL not supported"); throw new InvalidOperationException("cannot create webgl context"); } #endregion #region drawingMode var drawingMode = gl.TRIANGLES; page.With( delegate { page.triangles.onchange += delegate { if (drawingMode == gl.TRIANGLES) drawingMode = gl.LINE_STRIP; else drawingMode = gl.TRIANGLES; }; } ); #endregion var shaderProgram = gl.createProgram( new TunnelVertexShader(), new TunnelFragmentShader() ); // "WebGL: INVALID_OPERATION: drawElements: attribs not setup correctly", source: http://192.168.43.252:16876/ (0) // I/chromium( 3770): [INFO:CONSOLE(0)] "WebGL: INVALID_OPERATION: useProgram: program not valid", source: http://192.168.43.252:16876/ (0) gl.linkProgram(shaderProgram); gl.useProgram(shaderProgram); var shaderProgram_vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition"); gl.enableVertexAttribArray((uint)shaderProgram_vertexPositionAttribute); var shaderProgram_vertexColorAttribute = gl.getAttribLocation(shaderProgram, "aVertexColor"); gl.enableVertexAttribArray((uint)shaderProgram_vertexColorAttribute); var shaderProgram_textureCoordAttribute = gl.getAttribLocation(shaderProgram, "aTextureCoord"); gl.enableVertexAttribArray((uint)shaderProgram_textureCoordAttribute); var shaderProgram_pMatrixUniform = gl.getUniformLocation(shaderProgram, "uPMatrix"); var shaderProgram_mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix"); var shaderProgram_fTimeUniform = gl.getUniformLocation(shaderProgram, "fTime"); var shaderProgram_samplerUniform = gl.getUniformLocation(shaderProgram, "uSampler"); var mvMatrix = default(Matrix); var mvMatrixStack = new Stack<Matrix>(); var pMatrix = default(Matrix); Action mvPopMatrix = delegate { mvMatrix = mvMatrixStack.Pop(); }; // http://prototypejs.org/api/array/flatten Action setMatrixUniforms = delegate { gl.uniformMatrix4fv(shaderProgram_pMatrixUniform, false, new Float32Array(pMatrix.flatten())); gl.uniformMatrix4fv(shaderProgram_mvMatrixUniform, false, new Float32Array(mvMatrix.flatten())); }; Action mvPushMatrix = delegate { mvMatrixStack.Push(mvMatrix.dup()); }; Action loadIdentity = delegate { mvMatrix = __sylvester.Matrix.I(4); }; Action<Matrix> multMatrix = (m) => { mvMatrix = mvMatrix.x(m); }; Action<float[]> mvTranslate = (v) => { var m = __sylvester.Matrix.Translation(__sylvester.Vector.create(new[] { v[0], v[1], v[2] })).ensure4x4(); multMatrix(m); }; Action<float, float[]> mvRotate = (ang, v) => { var arad = ang * Math.PI / 180.0; var m = __sylvester.Matrix.Rotation(arad, __sylvester.Vector.create(new[] { v[0], v[1], v[2] })).ensure4x4(); multMatrix(m); }; Action<float, float, float, float> perspective = (fovy, aspect, znear, zfar) => { pMatrix = __glUtils.globals.makePerspective(fovy, aspect, znear, zfar); }; #region IsDisposed var IsDisposed = false; Dispose = delegate { if (IsDisposed) return; IsDisposed = true; canvas.Orphanize(); }; #endregion new HTML.Images.FromAssets.texture().InvokeOnComplete( (texture_image) => { #region initTexture var texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texture_image); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, (int)gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, (int)gl.NEAREST); gl.bindTexture(gl.TEXTURE_2D, null); #endregion #region initBuffers var cubeVertexPositionBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexPositionBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices.ToArray()), gl.STATIC_DRAW); var cubeVertexPositionBuffer_itemSize = 3; var cubeVertexPositionBuffer_numItems = vertices.Count / 3; var cubeVertexColorBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexColorBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors.ToArray()), gl.STATIC_DRAW); var cubeVertexColorBuffer_itemSize = 4; var cubeVertexColorBuffer_numItems = colors.Count / 4; var cubeVertexIndexBuffer = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVertexIndexBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices.ToArray()), gl.STATIC_DRAW); var cubeVertexIndexBuffer_itemSize = 1; var cubeVertexIndexBuffer_numItems = indices.Count; var cubeVertexTextureCoordBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexTextureCoordBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(uvs.ToArray()), gl.STATIC_DRAW); var cubeVertexTextureCoordBuffer_itemSize = 2; var cubeVertexTextureCoordBuffer_numItems = uvs.Count / 2; #endregion gl.clearColor(0.0f, 0.0f, 0.0f, 1.0f); gl.clearDepth(1.0f); gl.enable(gl.DEPTH_TEST); gl.depthFunc(gl.LEQUAL); Action AtResize = delegate { gl_viewportWidth = Convert.ToInt32(Native.window.Width * zoom); gl_viewportHeight = Convert.ToInt32(Native.window.Height * zoom); canvas.style.SetLocation(0, 0, Native.window.Width, Native.window.Height); canvas.width = Convert.ToInt32(Native.window.Width * zoom); canvas.height = Convert.ToInt32(Native.window.Height * zoom); }; #region onresize Native.window.onresize += delegate { AtResize(); }; #endregion AtResize(); var rCube = 0; #region drawScene Native.window.onframe += delegate { if (IsDisposed) return; gl.viewport(0, 0, gl_viewportWidth, gl_viewportHeight); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); perspective(45f, (float)gl_viewportWidth / (float)gl_viewportHeight, 0.1f, 100.0f); loadIdentity(); mvTranslate(new[] { 0.0f, 0.0f, -8.0f }); mvPushMatrix(); mvRotate(rCube, new[] { 1f, 1f, 1f }); gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexPositionBuffer); gl.vertexAttribPointer((uint)shaderProgram_vertexPositionAttribute, cubeVertexPositionBuffer_itemSize, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexColorBuffer); gl.vertexAttribPointer((uint)shaderProgram_vertexColorAttribute, cubeVertexColorBuffer_itemSize, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexTextureCoordBuffer); gl.vertexAttribPointer((uint)shaderProgram_textureCoordAttribute, cubeVertexTextureCoordBuffer_itemSize, gl.FLOAT, false, 0, 0); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, texture); gl.uniform1i(shaderProgram_samplerUniform, 0); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVertexIndexBuffer); setMatrixUniforms(); // ? // a[0].CS___8__locals19.currentTime = (((a[0].CS___8__locals19.currentTime + 0.01)) >>> 0); // haha. wtf jsc. :) currentTime = (currentTime + 0.01f); Native.document.title = new { currentTime }.ToString(); gl.uniform1f(shaderProgram_fTimeUniform, currentTime); gl.drawElements(drawingMode, cubeVertexIndexBuffer_numItems, gl.UNSIGNED_SHORT, 0); mvPopMatrix(); }; #endregion #region requestFullscreen Native.Document.body.ondblclick += delegate { if (IsDisposed) return; // http://tutorialzine.com/2012/02/enhance-your-website-fullscreen-api/ Native.Document.body.requestFullscreen(); }; #endregion } ); }
private void Initialize(IHTMLCanvas c, WebGLRenderingContext gl, IDefault page) { // http://cs.helsinki.fi/u/ilmarihe/metatunnel.html // http://wakaba.c3.cx/w/puls.html Action<string> alert = Native.window.alert; c.style.border = "1px solid yellow"; page.MaxTextures.innerText = "" + gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS); // https://www.khronos.org/webgl/public-mailing-list/archives/1007/msg00034.html var vs = ""; vs += "precision highp float; \n"; vs += "attribute vec3 aVertexPosition;"; vs += "attribute vec2 aTextureCoord;"; vs += "uniform mat4 uModelViewMatrix;"; vs += "uniform mat4 uProjectionMatrix;"; vs += "varying vec2 vTextureCoord;"; vs += "void main(void) {"; vs += "gl_Position = uProjectionMatrix * uModelViewMatrix * vec4(aVertexPosition, 1.0);"; vs += "vTextureCoord = vec2(aTextureCoord.x, 1.0 - aTextureCoord.y);"; vs += "}"; var fs = ""; fs += "precision highp float; \n"; fs += "varying vec2 vTextureCoord;"; fs += "uniform sampler2D uSamplerDiffuse1;"; fs += "uniform sampler2D uSamplerDiffuse2;"; fs += "uniform sampler2D uSamplerDiffuse3;"; fs += "uniform sampler2D uSamplerDiffuse4;"; fs += "uniform sampler2D uSamplerDiffuse5;"; fs += "uniform sampler2D uSamplerDiffuse6;"; fs += "void main(void) {"; fs += "gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0) * texture2D(uSamplerDiffuse1, vTextureCoord)"; fs += "+ vec4(0.0, 1.0, 0.0, 1.0) * texture2D(uSamplerDiffuse2, vTextureCoord)"; fs += "+ vec4(0.0, 0.0, 1.0, 1.0) * texture2D(uSamplerDiffuse3, vTextureCoord)"; fs += "+ vec4(0.0, 1.0, 1.0, 1.0) * texture2D(uSamplerDiffuse4, vTextureCoord)"; fs += "+ vec4(1.0, 0.0, 1.0, 1.0) * texture2D(uSamplerDiffuse5, vTextureCoord)"; fs += "+ vec4(1.0, 1.0, 0.0, 1.0) * texture2D(uSamplerDiffuse6, vTextureCoord);"; fs += "}"; var xfs = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(xfs, fs); gl.compileShader(xfs); if ((int)gl.getShaderParameter(xfs, gl.COMPILE_STATUS) != 1) { // vs: ERROR: 0:2: '' : Version number not supported by ESSL // fs: ERROR: 0:1: '' : No precision specified for (float) var error = gl.getShaderInfoLog(xfs); Native.window.alert("fs: " + error); return; } var xvs = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(xvs, vs); gl.compileShader(xvs); if ((int)gl.getShaderParameter(xvs, gl.COMPILE_STATUS) != 1) { // vs: ERROR: 0:2: '' : Version number not supported by ESSL // vs: ERROR: 0:10: '-' : wrong operand types no operation '-' exists that takes a left-hand operand of type 'const mediump int' and a right operand of type 'float' (or there is no acceptable conversion) var error = gl.getShaderInfoLog(xvs); Native.window.alert("vs: " + error); return; } var shader = new foo(); shader.program = gl.createProgram(); gl.attachShader(shader.program, xvs); gl.attachShader(shader.program, xfs); gl.linkProgram(shader.program); var linked = gl.getProgramParameter(shader.program, gl.LINK_STATUS); if (linked == null) { var error = gl.getProgramInfoLog(shader.program); Native.window.alert("Error while linking: " + error); return; } gl.useProgram(shader.program); shader.aVertexPosition = gl.getAttribLocation(shader.program, "aVertexPosition"); shader.aTextureCoord = gl.getAttribLocation(shader.program, "aTextureCoord"); gl.enableVertexAttribArray((uint)shader.aVertexPosition); gl.enableVertexAttribArray((uint)shader.aTextureCoord); shader.u["uModelViewMatrix"] = gl.getUniformLocation(shader.program, "uModelViewMatrix"); shader.u["uProjectionMatrix"] = gl.getUniformLocation(shader.program, "uProjectionMatrix"); shader.u["uSamplerDiffuse1"] = gl.getUniformLocation(shader.program, "uSamplerDiffuse1"); shader.u["uSamplerDiffuse2"] = gl.getUniformLocation(shader.program, "uSamplerDiffuse2"); shader.u["uSamplerDiffuse3"] = gl.getUniformLocation(shader.program, "uSamplerDiffuse3"); shader.u["uSamplerDiffuse4"] = gl.getUniformLocation(shader.program, "uSamplerDiffuse4"); shader.u["uSamplerDiffuse5"] = gl.getUniformLocation(shader.program, "uSamplerDiffuse5"); shader.u["uSamplerDiffuse6"] = gl.getUniformLocation(shader.program, "uSamplerDiffuse6"); shader.MV_MATRIX = new float[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }; shader.PROJECTION_MATRIX = new float[] { 1.000f, 0.000f, 0.000f, 0.000f, 0.000f, 1.000f, 0.000f, 0.000f, 0.000f, 0.000f, 0.002f, 0.000f, 0.000f, 0.000f, 0.998f, 1.000f }; var bar = default(bar); bar = initObject( gl, delegate { if (bar == null) return; renderFrame(gl, shader, bar); c.style.border = "2px solid green"; } ); }
public Application(IDefault page = null) { var size = 500; var gl = new WebGLRenderingContext(antialias: true, preserveDrawingBuffer: true); this.canvas = gl.canvas.AttachToDocument(); canvas.style.backgroundColor = "black"; //canvas.style.backgroundColor = "blue"; Native.document.body.style.overflow = IStyle.OverflowEnum.hidden; canvas.style.SetLocation(0, 0, size, size); canvas.width = size; canvas.height = size; var gl_viewportWidth = size; var gl_viewportHeight = size; canvas.style.SetLocation(0, 0, gl_viewportWidth, gl_viewportHeight); #region IsDisposed var IsDisposed = false; this.Dispose = delegate { if (IsDisposed) return; IsDisposed = true; canvas.Orphanize(); }; #endregion #region AtResize Action AtResize = delegate { gl_viewportWidth = Native.window.Width; gl_viewportHeight = Native.window.Height; canvas.style.SetSize(gl_viewportWidth, gl_viewportHeight); canvas.width = gl_viewportWidth; canvas.height = gl_viewportHeight; }; if (page != null) Native.window.onresize += e => { AtResize(); }; AtResize(); #endregion #region requestFullscreen Native.Document.body.ondblclick += delegate { if (IsDisposed) return; // http://tutorialzine.com/2012/02/enhance-your-website-fullscreen-api/ Native.Document.body.requestFullscreen(); }; #endregion #region initShaders var shaderProgram = gl.createProgram( new GeometryVertexShader(), new GeometryFragmentShader() ); gl.linkProgram(shaderProgram); gl.useProgram(shaderProgram); var shaderProgram_vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition"); gl.enableVertexAttribArray((uint)shaderProgram_vertexPositionAttribute); var shaderProgram_textureCoordAttribute = gl.getAttribLocation(shaderProgram, "aTextureCoord"); gl.enableVertexAttribArray((uint)shaderProgram_textureCoordAttribute); var shaderProgram_pMatrixUniform = gl.getUniformLocation(shaderProgram, "uPMatrix"); var shaderProgram_mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix"); // new in lesson 05 var shaderProgram_samplerUniform = gl.getUniformLocation(shaderProgram, "uSampler"); #endregion var mvMatrix = glMatrix.mat4.create(); var mvMatrixStack = new Stack<Float32Array>(); var pMatrix = glMatrix.mat4.create(); #region new in lesson 03 Action mvPushMatrix = delegate { var copy = glMatrix.mat4.create(); glMatrix.mat4.set(mvMatrix, copy); mvMatrixStack.Push(copy); }; Action mvPopMatrix = delegate { mvMatrix = mvMatrixStack.Pop(); }; #endregion #region setMatrixUniforms Action setMatrixUniforms = delegate { gl.uniformMatrix4fv(shaderProgram_pMatrixUniform, false, pMatrix); gl.uniformMatrix4fv(shaderProgram_mvMatrixUniform, false, mvMatrix); }; #endregion #region init buffers #region cubeVertexPositionBuffer var cubeVertexPositionBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexPositionBuffer); var vertices = new[]{ // Front face RED -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, //// Back face YELLOW //-1.0f, -1.0f, -1.0f, //-1.0f, 1.0f, -1.0f, // 1.0f, 1.0f, -1.0f, // 1.0f, -1.0f, -1.0f, //// Top face GREEN //-1.0f, 1.0f, -1.0f, //-1.0f, 1.0f, 1.0f, // 1.0f, 1.0f, 1.0f, // 1.0f, 1.0f, -1.0f, //// Bottom face BEIGE //-1.0f, -1.0f, -1.0f, // 1.0f, -1.0f, -1.0f, // 1.0f, -1.0f, 1.0f, //-1.0f, -1.0f, 1.0f, //// Right face PURPLE // 1.0f, -1.0f, -1.0f, // 1.0f, 1.0f, -1.0f, // 1.0f, 1.0f, 1.0f, // 1.0f, -1.0f, 1.0f, //// Left face //-1.0f, -1.0f, -1.0f, //-1.0f, -1.0f, 1.0f, //-1.0f, 1.0f, 1.0f, //-1.0f, 1.0f, -1.0f }; gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW); var cubeVertexPositionBuffer_itemSize = 3; //var cubeVertexPositionBuffer_numItems = 6 * 6; var cubeVertexPositionBuffer_numItems = 6 * 1; #endregion #region cubeVertexTextureCoordBuffer var cubeVertexTextureCoordBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexTextureCoordBuffer); var textureCoords = new float[]{ // Front face 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, //// Back face //1.0f, 0.0f, //1.0f, 1.0f, //0.0f, 1.0f, //0.0f, 0.0f, //// Top face //0.0f, 1.0f, //0.0f, 0.0f, //1.0f, 0.0f, //1.0f, 1.0f, //// Bottom face //1.0f, 1.0f, //0.0f, 1.0f, //0.0f, 0.0f, //1.0f, 0.0f, //// Right face //1.0f, 0.0f, //1.0f, 1.0f, //0.0f, 1.0f, //0.0f, 0.0f, //// Left face //0.0f, 0.0f, //1.0f, 0.0f, //1.0f, 1.0f, //0.0f, 1.0f, }; gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(textureCoords), gl.STATIC_DRAW); var cubeVertexTextureCoordBuffer_itemSize = 2; var cubeVertexTextureCoordBuffer_numItems = 24; var cubeVertexIndexBuffer = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVertexIndexBuffer); var cubeVertexIndices = new UInt16[]{ 0, 1, 2, 0, 2, 3, // Front face 4, 5, 6, 4, 6, 7, // Back face 8, 9, 10, 8, 10, 11, // Top face 12, 13, 14, 12, 14, 15, // Bottom face 16, 17, 18, 16, 18, 19, // Right face 20, 21, 22, 20, 22, 23 // Left face }; gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(cubeVertexIndices), gl.STATIC_DRAW); var cubeVertexIndexBuffer_itemSize = 1; var cubeVertexIndexBuffer_numItems = cubeVertexPositionBuffer_numItems; #endregion #endregion var tex1 = gl.createTexture(); var tex1i = new WebGLSVGAnonymous.HTML.Images.FromAssets.Anonymous_LogosSingleNoWings(); //var tex1i = new WebGLSVGAnonymous.HTML.Images.FromAssets.nehe(); // WebGL: drawElements: texture bound to texture unit 0 is not renderable. It maybe non-power-of-2 and have incompatible texture filtering or is not 'texture complete'. Or the texture is Float or Half Float type with linear filtering while OES_float_linear or OES_half_float_linear extension is not enabled. tex1i.width = 1024 * 2; tex1i.height = 1024 * 2; // initTexture new in lesson 05 var tex0 = gl.createTexture(); var tex0i = new WebGLSVGAnonymous.HTML.Images.FromAssets.Anonymous_LogosSingleWings(); //var tex0i = new WebGLSVGAnonymous.HTML.Images.FromAssets.nehe(); // WebGL: drawElements: texture bound to texture unit 0 is not renderable. It maybe non-power-of-2 and have incompatible texture filtering or is not 'texture complete'. Or the texture is Float or Half Float type with linear filtering while OES_float_linear or OES_half_float_linear extension is not enabled. tex0i.width = 1024 * 2; tex0i.height = 1024 * 2; tex1i.InvokeOnComplete( delegate { tex0i.InvokeOnComplete( delegate { // this is a workaround // chrome has a bug where svg textures are merged.. var tex1ii = new CanvasRenderingContext2D(1024 * 2, 1024 * 2); tex1ii.drawImage( tex1i, 0, 0, 1024 * 2, 1024 * 2); { gl.activeTexture(gl.TEXTURE1); gl.bindTexture(gl.TEXTURE_2D, tex1); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, tex1ii.canvas); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, (int)gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, (int)gl.NEAREST); gl.generateMipmap(gl.TEXTURE_2D); gl.bindTexture(gl.TEXTURE_2D, null); } { gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, tex0); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1); // http://msdn.microsoft.com/en-us/library/ie/dn302435(v=vs.85).aspx gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, tex0i); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, (int)gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, (int)gl.NEAREST); gl.generateMipmap(gl.TEXTURE_2D); gl.bindTexture(gl.TEXTURE_2D, null); } //gl.clearColor(0.0f, 0.0f, 0.0f, 1.0f); //gl.enable(gl.DEPTH_TEST); gl.enable(gl.BLEND); //gl.enable(gl.CULL_FACE); // http://stackoverflow.com/questions/11521035/blending-with-html-background-in-webgl gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); var xRot = 0.0f; var yRot = 0.0f; var zRot = 0.0f; var lastTime = 0L; Action animate = delegate { var timeNow = new IDate().getTime(); if (lastTime != 0) { var elapsed = timeNow - lastTime; //xRot += (9 * elapsed) / 1000.0f; yRot += (40 * elapsed) / 1000.0f; //zRot += (9 * elapsed) / 1000.0f; } lastTime = timeNow; }; Func<float, float> degToRad = (degrees) => { return degrees * (f)Math.PI / 180f; }; var f = new Designer(); f.trackBar1.Value = -20; f.trackBar2.Value = -10; if (page != null) f.Show(); Action<bool> drawScene = Anonymous_LogosSingleNoWings_Checked => { glMatrix.mat4.perspective(45f, (float)gl_viewportWidth / (float)gl_viewportHeight, 0.1f, 100.0f, pMatrix); glMatrix.mat4.identity(mvMatrix); var u1 = f.trackBar1.Value * 0.1f; glMatrix.mat4.translate(mvMatrix, new float[] { 0.0f, 0.0f, u1 }); //glMatrix.mat4.rotate(mvMatrix, degToRad(xRot), new[] { 1f, 0f, 0f }); if (Anonymous_LogosSingleNoWings_Checked) glMatrix.mat4.rotate(mvMatrix, degToRad(yRot), new[] { 0f, 1f, 0f }); else glMatrix.mat4.rotate(mvMatrix, degToRad(f.trackBar3.Value), new[] { 0f, 1f, 0f }); var u2 = f.trackBar2.Value * 0.1f; glMatrix.mat4.translate(mvMatrix, new float[] { 0.0f, 0.0f, u2 }); Native.document.title = new { u1, u2 }.ToString(); //glMatrix.mat4.rotate(mvMatrix, degToRad(zRot), new[] { 0f, 0f, 1f }); gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexPositionBuffer); gl.vertexAttribPointer((uint)shaderProgram_vertexPositionAttribute, cubeVertexPositionBuffer_itemSize, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexTextureCoordBuffer); gl.vertexAttribPointer((uint)shaderProgram_textureCoordAttribute, cubeVertexTextureCoordBuffer_itemSize, gl.FLOAT, false, 0, 0); if (Anonymous_LogosSingleNoWings_Checked) { gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, tex0); gl.uniform1i(shaderProgram_samplerUniform, 0); } else { gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, tex1); gl.uniform1i(shaderProgram_samplerUniform, 0); } gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVertexIndexBuffer); setMatrixUniforms(); gl.drawElements(gl.TRIANGLES, cubeVertexIndexBuffer_numItems, gl.UNSIGNED_SHORT, 0); gl.bindTexture(gl.TEXTURE_2D, null); }; var c = 0; Native.window.onframe += delegate { c++; if (page == null) { gl_viewportWidth = canvas.clientWidth; gl_viewportHeight = canvas.clientHeight; canvas.style.SetLocation(0, 0, gl_viewportWidth, gl_viewportHeight); canvas.width = gl_viewportWidth; canvas.height = gl_viewportHeight; } gl.viewport(0, 0, gl_viewportWidth, gl_viewportHeight); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); if (f.Anonymous_LogosSingleNoWings.Checked) drawScene(false); if (f.Anonymous_LogosSingleWings.Checked) drawScene(true); animate(); }; } ); } ); }
/// <summary> /// This is a javascript application. /// </summary> /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param> public Application(IApp page) { var toolbar = new { createItem = new IFunction("y", "return opera.contexts.toolbar.createItem(y);"), addItem = new IFunction("y", "opera.contexts.toolbar.addItem(y);") }; var windows = new { // http://dev.opera.com/articles/view/extensions-api-windows-create/ create = new IFunction("", "return opera.extension.windows.create();"), // http://dev.opera.com/articles/view/extensions-api-window-update/ update = new IFunction("y", "this.update(y);"), }; try { // can only create one button? toolbar.createItem.apply(null, new Opera_UIItemProperties { title = "OperaExtensionExperiment", popup = new OperaToolbarPopupArguments { href = "index.html" } } ).With( theButton => { toolbar.addItem.apply(null, theButton); } ); } catch { // not running as extension? } // will only work on toolbar //page.NewBrowser.style.color = JSColor.Green; //page.NewBrowser.onclick += // delegate // { // var w = windows.create.apply(null); // windows.update.apply(w, // new Opera_BrowserWindowProperties // { // width = 400 // } // ); // }; page.IAmAPopup.style.color = JSColor.Green; page.IAmAPopup.onclick += delegate { page.IAmAPopup.style.color = JSColor.Red; var getScreenshot = new IFunction("y", "opera.extension.getScreenshot(y);"); Action<ImageData> applyScreenshot = imageData => { // Create a blank canvas var canvas = new IHTMLCanvas(); canvas.width = (int)imageData.width; canvas.height = (int)imageData.height; // Write the screenshot image data to the canvas context var ctx = (CanvasRenderingContext2D)canvas.getContext("2d"); ctx.putImageData(imageData, 0, 0, 0, 0, imageData.width, imageData.height); canvas.style.border = "1px solid blue"; canvas.AttachToDocument(); page.IAmAPopup.style.color = JSColor.Blue; }; // http://dev.opera.com/articles/view/extensions-api-screenshot/ getScreenshot.apply(null, IFunction.OfDelegate(applyScreenshot)); }; page.foooex.ondragstart += e => { // http://ajaxian.com/archives/how-to-drag-out-files-like-gmail e.dataTransfer.setData("DownloadURL", "application/octet-stream:foo.oex:" + page.foooex.href); }; }
void InitializeContent(IDefault page = null) { var gl_viewportWidth = 800; var gl_viewportHeight = 640; #region canvas var canvas = new IHTMLCanvas().AttachToDocument(); Native.Document.body.style.overflow = IStyle.OverflowEnum.hidden; canvas.style.SetLocation(0, 0, gl_viewportWidth, gl_viewportHeight); canvas.width = gl_viewportWidth; canvas.height = gl_viewportHeight; #endregion #region gl - Initialise WebGL var gl = default(gl); try { gl = (gl)canvas.getContext("experimental-webgl"); } catch { } if (gl == null) { Native.window.alert("WebGL not supported"); throw new InvalidOperationException("cannot create webgl context"); } #endregion #region Dispose var IsDisposed = false; Dispose = delegate { if (IsDisposed) return; IsDisposed = true; canvas.Orphanize(); }; #endregion #region initShaders var shaderProgram = gl.createProgram( new GeometryVertexShader(), new GeometryFragmentShader() ); gl.linkProgram(shaderProgram); gl.useProgram(shaderProgram); var vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition"); gl.enableVertexAttribArray((uint)vertexPositionAttribute); var vertexNormalAttribute = gl.getAttribLocation(shaderProgram, "aVertexNormal"); gl.enableVertexAttribArray((uint)vertexNormalAttribute); var vertexColorAttribute = gl.getAttribLocation(shaderProgram, "aVertexColor"); gl.enableVertexAttribArray((uint)vertexColorAttribute); #endregion gl.clearColor(0.0f, 0.0f, 0.0f, 1.0f); gl.clearDepth(1.0f); gl.enable(gl.DEPTH_TEST); // missing from WebGL IDL? //gl.enable(gl.POLYGON_SMOOTH); // Enable point size gl.enable(0x8642); gl.depthFunc(gl.LEQUAL); #region initBuffers var vertexBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer); var planet = new Planet(129); var planetData = planet.generate(); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(planetData.vertices), gl.STATIC_DRAW); var vertexBuffer_itemSize = 3; var vertexBuffer_numItems = planetData.vertices.Length / 3; var colorBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(planetData.colors), gl.STATIC_DRAW); var colorBuffer_itemSize = 4; var colorBuffer_numItems = planetData.colors.Length / 4; var normalBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, normalBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(planetData.normals), gl.STATIC_DRAW); var normalBuffer_itemSize = 3; var normalBuffer_numItems = planetData.normals.Length / 3; var indexBuffer = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(planetData.indices), gl.STATIC_DRAW); var indexBuffer_itemSize = 1; var indexBuffer_numItems = planetData.indices.Length; #endregion var lastTime = 0L; var yRot = -180.0f; var ySpeed = -50.0f; #region glCore var mvMatrix = default(Matrix); var mvMatrixStack = new Stack<Matrix>(); var pMatrix = default(Matrix); Action loadIdentity = delegate { mvMatrix = __sylvester.Matrix.I(4); }; Action<float, float, float, float> perspective = (fovy, aspect, znear, zfar) => { pMatrix = __glUtils.globals.makePerspective(fovy, aspect, znear, zfar); }; Action<Matrix> multMatrix = (m) => { mvMatrix = mvMatrix.x(m); }; // http://prototypejs.org/api/array/flatten Action setMatrixUniforms = delegate { var shaderProgram_pMatrixUniform = gl.getUniformLocation(shaderProgram, "uPMatrix"); gl.uniformMatrix4fv(shaderProgram_pMatrixUniform, false, new Float32Array(pMatrix.flatten())); var shaderProgram_mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix"); gl.uniformMatrix4fv(shaderProgram_mvMatrixUniform, false, new Float32Array(mvMatrix.flatten())); var normalMatrix = mvMatrix.inverse(); normalMatrix = normalMatrix.transpose(); var nUniform = gl.getUniformLocation(shaderProgram, "uNMatrix"); gl.uniformMatrix4fv(nUniform, false, new Float32Array(mvMatrix.flatten())); }; Action<float, float[]> mvRotate = (ang, v) => { var arad = ang * Math.PI / 180.0; var m = __sylvester.Matrix.Rotation(arad, __sylvester.Vector.create(new[] { v[0], v[1], v[2] })).ensure4x4(); multMatrix(m); }; Action<f, f, f, f, f, f, f, f, f> lookAt = (ex, ey, ez, cx, cy, cz, ux, uy, uz) => { mvMatrix = mvMatrix.x(__glUtils.globals.makeLookAt(ex, ey, ez, cx, cy, cz, ux, uy, uz)); }; #endregion #region drawScene Action drawScene = delegate { gl.viewport(0, 0, gl_viewportWidth, gl_viewportHeight); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); //perspective(45f, (float)gl_viewportWidth / (float)gl_viewportHeight, 0.1f, 100.0f); perspective(60f, (float)gl_viewportWidth / (float)gl_viewportHeight, 0.1f, 1000.0f); //perspective(60f, 800 / 640, 0.1f, 1000.0f); loadIdentity(); lookAt(0, 0, 500, 0, 0, 0, 0, 1, 0); mvRotate(yRot, new[] { 0f, 1f, 0f }); gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer); gl.vertexAttribPointer((uint)vertexPositionAttribute, vertexBuffer_itemSize, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, normalBuffer); gl.vertexAttribPointer((uint)vertexNormalAttribute, normalBuffer_itemSize, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer); gl.vertexAttribPointer((uint)vertexColorAttribute, colorBuffer_itemSize, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer); setMatrixUniforms(); gl.drawElements(gl.TRIANGLES, indexBuffer_numItems, gl.UNSIGNED_SHORT, 0); //gl.drawArrays(gl.POINTS, 0, vertexBuffer.numItems); }; #endregion #region animate Action animate = () => { var timeNow = new IDate().getTime(); if (lastTime != 0) { var elapsed = timeNow - lastTime; yRot += (ySpeed * elapsed) / 1000.0f; } lastTime = timeNow; }; #endregion #region tick Action tick = null; tick = () => { drawScene(); animate(); Native.window.requestAnimationFrame += tick; }; Native.window.requestAnimationFrame += tick; #endregion #region AtResize Action AtResize = delegate { gl_viewportWidth = Native.window.Width; gl_viewportHeight = Native.window.Height; canvas.style.SetLocation(0, 0, Native.window.Width, Native.window.Height); canvas.width = Native.window.Width; canvas.height = Native.window.Height; }; #region onresize Native.window.onresize += delegate { AtResize(); }; #endregion AtResize(); #endregion #region requestFullscreen Native.Document.body.ondblclick += delegate { if (IsDisposed) return; // http://tutorialzine.com/2012/02/enhance-your-website-fullscreen-api/ Native.Document.body.requestFullscreen(); }; #endregion }
/// <summary> /// This is a javascript application. /// </summary> /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param> public Application(IApp page) { onMouseDownPosition = new THREE.Vector2(); //camera = new THREE.PerspectiveCamera( // 45, // Native.window.aspect, // 1, // 1000 // //2000 // ); //camera.position.z = 400; camera = new THREE.PerspectiveCamera(40, Native.window.Width / Native.window.Height, 1, 10000); camera.position.x = radious * Math.Sin(theta * Math.PI / 360) * Math.Cos(phi * Math.PI / 360); camera.position.y = radious * Math.Sin(phi * Math.PI / 360); camera.position.z = radious * Math.Cos(theta * Math.PI / 360) * Math.Cos(phi * Math.PI / 360); scene = new THREE.Scene(); var ambientLight = new THREE.AmbientLight(0x404040); scene.add(ambientLight); var directionalLight = new THREE.DirectionalLight(0xffeedd); directionalLight.position.set(0, 0, 1); scene.add(directionalLight); var obj = new THREE.Object3D(); var buttomCylinder1 = new THREE.Mesh( new THREE.CylinderGeometry(50, 50, 50, 32), new THREE.MeshPhongMaterial( new { specular = new THREE.Color(0xa0a0a0), color = new THREE.Color(0xa0a0a0), }) ); buttomCylinder1.rotation.x = - 90 * Math.PI / 180; //buttomCylinder1.position.x = 0; //buttomCylinder1.position.y = 0; //buttomCylinder1.position.z = 0; obj.add(buttomCylinder1); scene.add(obj); var renderer = new THREE.WebGLRenderer( new { preserveDrawingBuffer = true } ); renderer.setSize(Native.window.Width, Native.window.Height); this.canvas = (IHTMLCanvas)renderer.domElement; this.canvas.AttachToDocument(); this.canvas.style.SetLocation(0, 0); camera.lookAt(scene.position); scene.add(obj); //var plane = new THREE.Mesh(new THREE.Plane(1000, 1000)); //plane.rotation.x = -90 * Math.PI / 180; //scene.add(plane); #region onmousedown this.canvas.onmousedown += e => { e.preventDefault(); isMouseDown = true; onMouseDownTheta = theta; onMouseDownPhi = phi; onMouseDownPosition.x = e.CursorX; onMouseDownPosition.y = e.CursorY; }; #endregion this.canvas.onmousewheel += e => { radious -= e.WheelDirection; camera.position.x = radious * Math.Sin(theta * Math.PI / 360) * Math.Cos(phi * Math.PI / 360); camera.position.y = radious * Math.Sin(phi * Math.PI / 360); camera.position.z = radious * Math.Cos(theta * Math.PI / 360) * Math.Cos(phi * Math.PI / 360); camera.updateMatrix(); }; #region onmousemove this.canvas.onmousemove += e => { e.preventDefault(); if (isMouseDown) { theta = -((e.CursorX - onMouseDownPosition.x) * 0.5) + onMouseDownTheta; phi = ((e.CursorX - onMouseDownPosition.y) * 0.5) + onMouseDownPhi; phi = Math.Min(360, Math.Max(0, phi)); camera.position.x = radious * Math.Sin(theta * Math.PI / 360) * Math.Cos(phi * Math.PI / 360); camera.position.y = radious * Math.Sin(phi * Math.PI / 360); camera.position.z = radious * Math.Cos(theta * Math.PI / 360) * Math.Cos(phi * Math.PI / 360); camera.updateMatrix(); } }; #endregion this.canvas.onmouseup += e => { e.preventDefault(); isMouseDown = false; onMouseDownPosition.x = e.CursorX - onMouseDownPosition.x; onMouseDownPosition.y = e.CursorY - onMouseDownPosition.y; }; // could we Native.window.onframe += e => { renderer.clear(); camera.updateProjectionMatrix(); camera.lookAt(scene.position); renderer.render(scene, camera); }; Native.window.onresize += delegate { //if (canvas.parentNode == Native.document.body) // are we embedded? if (page != null) renderer.setSize(); }; }
/// <summary> /// This is a javascript application. /// </summary> /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param> public Application(IApp page) { // why are the trucks black? // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2013/201311/20131110-dae // what will happen if we resync THREE version from 70 to? Native.document.title = new { THREE.REVISION }.ToString(); var oo = new List<THREE.Object3D>(); #region scene var window = Native.window; var camera = new THREE.PerspectiveCamera( 45, window.aspect, 1, 2000 ); camera.position.z = 400; // scene var scene = new THREE.Scene(); //var ambient = new THREE.AmbientLight(0x101030); var ambient = new THREE.AmbientLight(0x808080); scene.add(ambient); var directionalLight = new THREE.DirectionalLight(0xffeedd, 0.7); directionalLight.position.set(0, 0, 1); scene.add(directionalLight); // WebGLRenderer preserveDrawingBuffer var renderer = new THREE.WebGLRenderer( new { preserveDrawingBuffer = true } ); // https://github.com/mrdoob/three.js/issues/3836 renderer.setClearColor(0xfffff, 1); renderer.setSize(window.Width, window.Height); renderer.domElement.AttachToDocument(); renderer.domElement.style.SetLocation(0, 0); this.canvas = (IHTMLCanvas)renderer.domElement; var mouseX = 0; var mouseY = 0; var st = new Stopwatch(); st.Start(); var controls = new THREE.OrbitControls(camera, renderer.domElement); Native.window.onframe += delegate { renderer.clear(); //camera.aspect = window.aspect; //camera.aspect = canvas.clientWidth / (double)canvas.clientHeight; //camera.aspect = canvas.aspect; oo.WithEach( x => x.rotation.y = st.ElapsedMilliseconds * 0.0001 ); controls.update(); camera.position = controls.center.clone(); renderer.render(scene, camera); }; Native.window.onresize += delegate { if (canvas.parentNode == Native.document.body) { renderer.setSize(window.Width, window.Height); } }; #endregion new truck().Source.Task.ContinueWithResult( dae => { //dae.scale.x = 30; //dae.scale.y = 30; //dae.scale.z = 30; dae.position.z = 65; dae.scale.x = 10; dae.scale.y = 10; dae.scale.z = 10; dae.position.y = -80; scene.add(dae); oo.Add(dae); } ); //var ref0 = "assets/WebGLColladaExperiment/HZCannon_capture_009_04032013_192834.png"; //new HZCannon().Source.Task.ContinueWithResult( // dae => // { // //dae.scale.x = 30; // //dae.scale.y = 30; // //dae.scale.z = 30; // dae.castShadow = true; // dae.receiveShadow = true; // dae.scale.x = 3; // dae.scale.y = 3; // dae.scale.z = 3; // dae.position.y = -80; // scene.add(dae); // oo.Add(dae); // } //); }
/// <summary> /// This is a javascript application. /// </summary> /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param> public Application(IApp page) { // if we are running in a SYSTEM account // the chrome no-sandbox only allows software renderer // where we get 1 frame per sec. // on older systems we may not get GL_OES_standard_derivatives // http://stackoverflow.com/questions/16795278/disable-some-gl-extensions-for-debugging-three-js-app // ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "", // or that system is just old as hell // http://stackoverflow.com/questions/16795278/disable-some-gl-extensions-for-debugging-three-js-app //http://thematicmapping.org/playground/webgl/earth/ // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201402/20140222 // Earth params var radius = 0.5; //var segments = 32; var segments = 128; var rotation = 6; var scene = new THREE.Scene(); locations = new ArrayList(); var camera = new THREE.PerspectiveCamera(45, Native.window.aspect, 0.01, 1000); camera.position.z = 1.5; var renderer = new THREE.WebGLRenderer( new { preserveDrawingBuffer = true } ); renderer.setSize(); scene.add(new THREE.AmbientLight(0x333333)); var light = new THREE.DirectionalLight(0xffffff, 1); light.position.set(5, 3, 5); scene.add(light); parent = new THREE.Object3D(); scene.add(parent); #region sphere var sphere = new THREE.Mesh( new THREE.SphereGeometry(radius, segments, segments), new THREE.MeshPhongMaterial( new { map = new THREE.Texture().With( async s => { //0:75ms event: _2_no_clouds_4k_low view-source:36543 //Application Cache Progress event (1 of 2) http://192.168.1.72:22248/view-source 192.168.1.72/:1 //Application Cache Progress event (2 of 2) 192.168.1.72/:1 //Application Cache Cached event 192.168.1.72/:1 //1:1018ms event: _2_no_clouds_4k_low done view-source:36543 //1:1019ms event: _2_no_clouds_4k view-source:36543 //event.returnValue is deprecated. Please use the standard event.preventDefault() instead. view-source:2995 //1:16445ms event: _2_no_clouds_4k done // ~ tilde to open css editor? Console.WriteLine("event: _2_no_clouds_4k_low"); s.image = await new _2_no_clouds_4k_low(); s.needsUpdate = true; Console.WriteLine("event: _2_no_clouds_4k_low done"); await 20000; Console.WriteLine("event: _2_no_clouds_4k"); s.image = await new _2_no_clouds_4k(); s.needsUpdate = true; Console.WriteLine("event: _2_no_clouds_4k done"); } ), bumpMap = THREE.ImageUtils.loadTexture( new elev_bump_4k().src //new elev_bump_4k_low().src ), // applies onyl to shaders to create the shadow bumpScale = 0.001, specularMap = new THREE.Texture().With( async s => { Console.WriteLine("event: water_4k_low"); s.image = await new water_4k_low(); s.needsUpdate = true; Console.WriteLine("event: water_4k_low done"); await 20000; Console.WriteLine("event: water_4k"); s.image = await new water_4k(); s.needsUpdate = true; Console.WriteLine("event: water_4k done"); } ), //specular = new THREE.Color("grey") specular = new THREE.Color(0xa0a0a0) }) ); #endregion // http://stackoverflow.com/questions/12447734/three-js-updateing-texture-on-plane //sphere.rotation.y = rotation; parent.rotation.y = rotation; //sphere.position.x = 10; //sphere.position.y = 10; //sphere.position.z = 10; //sphere.position.normalize(); //sphere.position.multiplyScalar(200); parent.add(sphere); //scene.add(sphere); #region clouds var clouds = new THREE.Mesh( new THREE.SphereGeometry( //radius + 0.003, radius + 0.006, segments, segments), new THREE.MeshPhongMaterial( new { //map = THREE.ImageUtils.loadTexture( // //new fair_clouds_4k().src // new fair_clouds_4k_low().src // ), map = new THREE.Texture().With( async s => { Console.WriteLine("event: fair_clouds_4k_low"); s.image = await new fair_clouds_4k_low(); s.needsUpdate = true; Console.WriteLine("event: fair_clouds_4k_low done"); await 20000; Console.WriteLine("event: fair_clouds_4k"); s.image = await new fair_clouds_4k(); s.needsUpdate = true; Console.WriteLine("event: fair_clouds_4k done"); } ), transparent = true }) ); //clouds.rotation.y = rotation; parent.add(clouds); //scene.add(clouds); #endregion var citiesData = new XElement("cities"); { var cityH = new XElement("city"); cityH.Add(new XElement("name", "Tallinn")); cityH.Add(new XElement("longitude", "24.7281")); cityH.Add(new XElement("latitude", "59.4339")); citiesData.Add(cityH); } { var cityH = new XElement("city"); cityH.Add(new XElement("name", "London")); cityH.Add(new XElement("longitude", "-0.116667")); cityH.Add(new XElement("latitude", "51.5")); citiesData.Add(cityH); } var shadowL = new ShadowLayout().AttachTo(Native.shadow); page.dataHolder = citiesData; #region Location on sphere Action AddCities = async delegate { //var table = await this.GetAllCities(); //Console.WriteLine(table.Rows.Count.ToString()); //for (var r = 0; r < table.Rows.Count; r++) //{ // var latitude = (double)table.Rows[r]["Latitude"]; // var longtitude = (double)table.Rows[r]["Longtitude"]; // addLocation(latitude, longtitude, radius, 0.001, parent, 6); // Console.WriteLine(latitude.ToString()); // await 100; //} var elemList = citiesData.Elements(); Console.WriteLine(elemList.Count().ToString()); foreach (var i in elemList) { //Console.WriteLine(i.ToString()); //foreach (var t in i.Elements()) //{ // Console.WriteLine(t.ToString()); //} //var l = i.Element("name"); //if (l == null) //{ // Console.WriteLine("F**k"); //} //else //{ // Console.WriteLine(l.Value); //} //Console.WriteLine(i.Element("longitude")); //Console.WriteLine(i.Element("latitude")); var lat = i.Element("latitude"); if (lat != null) { Console.WriteLine("Latitude not null"); var latitude = Convert.ToDouble(lat.Value); Console.WriteLine(latitude.ToString()); var longit = i.Element("longitude"); if (longit != null) { Console.WriteLine("Longitude not null"); var longtitude = Convert.ToDouble(longit.Value); addLocation(latitude, longtitude, radius, 0.001, parent, 6); Console.WriteLine(longtitude.ToString()); } } } }; citiesData.Changed += (send, arg) => { //if(arg.ObjectChange == XObjectChange.Value) //{ //Console.WriteLine(citiesData); //Console.WriteLine("Sender name "+((XAttribute)send).Name); //Console.WriteLine("Sender val " + ((XAttribute)send).Value); removeLocations(); AddCities(); //} }; AddCities(); #endregion var stars = new THREE.Mesh( new THREE.SphereGeometry(90, 64, 64), new THREE.MeshBasicMaterial( new { map = THREE.ImageUtils.loadTexture(new galaxy_starfield().src), side = THREE.BackSide }) ); scene.add(stars); this.canvas = (IHTMLCanvas)renderer.domElement; //renderer.domElement.AttachToDocument(); this.canvas.AttachTo(shadowL.webGlCanvas); this.canvas.style.SetLocation(0, 0); // jsc, what pointers do we have in store? this.canvas.css.style.cursor = IStyle.CursorEnum.pointer; this.canvas.css.active.style.cursor = IStyle.CursorEnum.move; var old = new { parent = new { parent.rotation.x, parent.rotation.y }, //sphere = new //{ // //sphere.rotation.x, // //sphere.rotation.y //}, //clouds = new //{ // //clouds.rotation.x, // //clouds.rotation.y, //}, CursorX = 0, CursorY = 0 }; #region onmousedown this.canvas.onmousedown += e => { var pointerLock = this.canvas == Native.document.pointerLockElement; if (e.MouseButton == IEvent.MouseButtonEnum.Middle) { this.canvas.requestFullscreen(); this.canvas.requestPointerLock(); } else { // movementX no longer works old = new { parent = new { parent.rotation.x, parent.rotation.y }, //sphere = new //{ // sphere.rotation.x, // sphere.rotation.y //}, //clouds = new //{ // clouds.rotation.x, // clouds.rotation.y, //}, e.CursorX, e.CursorY }; if (pointerLock) { // skip } else { e.CaptureMouse(); } } }; #endregion var z = camera.position.z; var sfx = new TestWebGLEarthShadowDomXML.HTML.Audio.FromAssets.SatelliteBeep_Sputnik1 { autobuffer = true, // this aint working //loop = true }; sfx.play(); //sfx.AttachToHead(); // http://soundfxnow.com/sound-fx/sputnik-satellite-beeping/ this.canvas.onmousewheel += e => { //camera.position.z = 1.5; // min max. shall adjust speed also! // max 4.0 // min 0.6 z -= 0.1 * e.WheelDirection; z = z.Max(0.6).Min(4.5); //Native.document.title = new { camera.position.z }.ToString(); }; // X:\jsc.svn\examples\javascript\Test\TestMouseMovement\TestMouseMovement\Application.cs #region onmousemove this.canvas.onmousemove += e => { var pointerLock = this.canvas == Native.document.pointerLockElement; //Console.WriteLine(new { e.MouseButton, pointerLock, e.movementX }); if (e.MouseButton == IEvent.MouseButtonEnum.Left) { if (pointerLock) { parent.rotation.x += 0.01 * e.movementY; parent.rotation.y += 0.01 * e.movementX; //sphere.rotation.x += 0.01 * e.movementY; //sphere.rotation.y += 0.01 * e.movementX; //clouds.rotation.x += 0.01 * e.movementY; //clouds.rotation.y += 0.01 * e.movementX; } else { parent.rotation.x = old.parent.x + 0.01 * (e.CursorY - old.CursorY); parent.rotation.y = old.parent.y + 0.01 * (e.CursorX - old.CursorX); //sphere.rotation.x = old.sphere.x + 0.01 * (e.CursorY - old.CursorY); //sphere.rotation.y = old.sphere.y + 0.01 * (e.CursorX - old.CursorX); //clouds.rotation.x = old.clouds.x + 0.01 * (e.CursorY - old.CursorY); //clouds.rotation.y = old.clouds.y + 0.01 * (e.CursorX - old.CursorX); } // Native.document.title = new { e.movementX, e.movementY }.ToString(); } }; #endregion // could we Native.window.onframe += e => { if (this.canvas.parentNode == null) { return; } camera.aspect = canvas.clientWidth / (double)canvas.clientHeight; camera.updateProjectionMatrix(); camera.position.z += (z - camera.position.z) * e.delay.ElapsedMilliseconds / 200; // the larger the vew the slower the rotation shall be var speed = 0.0001 * e.delay.ElapsedMilliseconds + 0.007 * 96.0 / canvas.clientHeight * 1.0 / camera.position.z; //Native.document.title = new { s = 96.0 / canvas.clientHeight }.ToString(); //Native.document.title = new { speed }.ToString(); //controls.update(); //sphere.rotation.y += speed; //clouds.rotation.y += speed; parent.rotation.y += speed; renderer.render(scene, camera); }; Native.window.onresize += delegate { //if (canvas.parentNode == Native.document.body) // are we embedded? if (page != null) { renderer.setSize(); } }; //new IStyle(this.canvas.css.before) //{ // content = "'do a middle click to maximize the earth dashboard'", // left = "1em", // bottom = "1em", // color = "white", // position = IStyle.PositionEnum.absolute //}; }
void InitializeContent(IDefault page = null) { var vertices = new List <float>(); var indices = new List <ushort>(); var colors = new List <float>(); var uvs = new List <float>(); var radius = 7; var currentRadius = radius; var segments = (ushort)24; var spacing = 2; var numRings = 18; var index = (ushort)0; var currentTime = 0.0f; #region generateGeometry Action generateGeometry = delegate { for (var ring = 0; ring < numRings; ring++) { for (var segment = 0; segment < segments; segment++) { var degrees = (360 / segments) * segment; var radians = (Math.PI / 180) * degrees; var x = (float)Math.Cos(radians) * currentRadius; var y = (float)Math.Sin(radians) * currentRadius; var z = ring * -spacing; vertices.Add(x, y, z); if (segment < (segments - 1) / 2) { uvs.Add((1.0f / (segments)) * segment * 2, (1.0f / 4) * ring); } else { uvs.Add(2.0f - ((1.0f / (segments)) * segment * 2), (1.0f / 4) * ring); } var color = 1.0f - ((1.0f / (numRings - 1)) * ring); colors.Add(color, color, color, 1.0f); if (ring < numRings - 1) { if (segment < segments - 1) { indices.Add(index, (ushort)(index + segments + 1), (ushort)(index + segments)); indices.Add(index, (ushort)(index + 1), (ushort)(index + segments + 1)); } else { indices.Add(index, (ushort)(index + 1), (ushort)(index + segments)); indices.Add(index, (ushort)(index - segments + 1), (ushort)(index + 1)); } } index++; } currentRadius -= radius / numRings; } }; generateGeometry(); #endregion var size = 500; var gl_viewportWidth = size; var gl_viewportHeight = size; #region canvas var canvas = new IHTMLCanvas().AttachToDocument(); Native.Document.body.style.overflow = IStyle.OverflowEnum.hidden; canvas.style.SetLocation(0, 0, size, size); canvas.width = size; canvas.height = size; #endregion #region gl - Initialise WebGL var gl = default(WebGLRenderingContext); try { gl = (WebGLRenderingContext)canvas.getContext("experimental-webgl"); } catch { } if (gl == null) { Native.window.alert("WebGL not supported"); throw new InvalidOperationException("cannot create webgl context"); } #endregion #region drawingMode var drawingMode = gl.TRIANGLES; page.With( delegate { page.triangles.onchange += delegate { if (drawingMode == gl.TRIANGLES) { drawingMode = gl.LINE_STRIP; } else { drawingMode = gl.TRIANGLES; } }; } ); #endregion var shaderProgram = gl.createProgram( new TunnelVertexShader(), new TunnelFragmentShader() ); // "WebGL: INVALID_OPERATION: drawElements: attribs not setup correctly", source: http://192.168.43.252:16876/ (0) // I/chromium( 3770): [INFO:CONSOLE(0)] "WebGL: INVALID_OPERATION: useProgram: program not valid", source: http://192.168.43.252:16876/ (0) gl.linkProgram(shaderProgram); gl.useProgram(shaderProgram); var shaderProgram_vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition"); gl.enableVertexAttribArray((uint)shaderProgram_vertexPositionAttribute); var shaderProgram_vertexColorAttribute = gl.getAttribLocation(shaderProgram, "aVertexColor"); gl.enableVertexAttribArray((uint)shaderProgram_vertexColorAttribute); var shaderProgram_textureCoordAttribute = gl.getAttribLocation(shaderProgram, "aTextureCoord"); gl.enableVertexAttribArray((uint)shaderProgram_textureCoordAttribute); var shaderProgram_pMatrixUniform = gl.getUniformLocation(shaderProgram, "uPMatrix"); var shaderProgram_mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix"); var shaderProgram_fTimeUniform = gl.getUniformLocation(shaderProgram, "fTime"); var shaderProgram_samplerUniform = gl.getUniformLocation(shaderProgram, "uSampler"); var mvMatrix = default(Matrix); var mvMatrixStack = new Stack <Matrix>(); var pMatrix = default(Matrix); Action mvPopMatrix = delegate { mvMatrix = mvMatrixStack.Pop(); }; // http://prototypejs.org/api/array/flatten Action setMatrixUniforms = delegate { gl.uniformMatrix4fv(shaderProgram_pMatrixUniform, false, new Float32Array(pMatrix.flatten())); gl.uniformMatrix4fv(shaderProgram_mvMatrixUniform, false, new Float32Array(mvMatrix.flatten())); }; Action mvPushMatrix = delegate { mvMatrixStack.Push(mvMatrix.dup()); }; Action loadIdentity = delegate { mvMatrix = __sylvester.Matrix.I(4); }; Action <Matrix> multMatrix = (m) => { mvMatrix = mvMatrix.x(m); }; Action <float[]> mvTranslate = (v) => { var m = __sylvester.Matrix.Translation(__sylvester.Vector.create(new[] { v[0], v[1], v[2] })).ensure4x4(); multMatrix(m); }; Action <float, float[]> mvRotate = (ang, v) => { var arad = ang * Math.PI / 180.0; var m = __sylvester.Matrix.Rotation(arad, __sylvester.Vector.create(new[] { v[0], v[1], v[2] })).ensure4x4(); multMatrix(m); }; Action <float, float, float, float> perspective = (fovy, aspect, znear, zfar) => { pMatrix = __glUtils.globals.makePerspective(fovy, aspect, znear, zfar); }; #region IsDisposed var IsDisposed = false; Dispose = delegate { if (IsDisposed) { return; } IsDisposed = true; canvas.Orphanize(); }; #endregion new HTML.Images.FromAssets.texture().InvokeOnComplete( (texture_image) => { #region initTexture var texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texture_image); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, (int)gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, (int)gl.NEAREST); gl.bindTexture(gl.TEXTURE_2D, null); #endregion #region initBuffers var cubeVertexPositionBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexPositionBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices.ToArray()), gl.STATIC_DRAW); var cubeVertexPositionBuffer_itemSize = 3; var cubeVertexPositionBuffer_numItems = vertices.Count / 3; var cubeVertexColorBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexColorBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors.ToArray()), gl.STATIC_DRAW); var cubeVertexColorBuffer_itemSize = 4; var cubeVertexColorBuffer_numItems = colors.Count / 4; var cubeVertexIndexBuffer = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVertexIndexBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices.ToArray()), gl.STATIC_DRAW); var cubeVertexIndexBuffer_itemSize = 1; var cubeVertexIndexBuffer_numItems = indices.Count; var cubeVertexTextureCoordBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexTextureCoordBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(uvs.ToArray()), gl.STATIC_DRAW); var cubeVertexTextureCoordBuffer_itemSize = 2; var cubeVertexTextureCoordBuffer_numItems = uvs.Count / 2; #endregion gl.clearColor(0.0f, 0.0f, 0.0f, 1.0f); gl.clearDepth(1.0f); gl.enable(gl.DEPTH_TEST); gl.depthFunc(gl.LEQUAL); Action AtResize = delegate { gl_viewportWidth = Convert.ToInt32(Native.window.Width * zoom); gl_viewportHeight = Convert.ToInt32(Native.window.Height * zoom); canvas.style.SetLocation(0, 0, Native.window.Width, Native.window.Height); canvas.width = Convert.ToInt32(Native.window.Width * zoom); canvas.height = Convert.ToInt32(Native.window.Height * zoom); }; #region onresize Native.window.onresize += delegate { AtResize(); }; #endregion AtResize(); var rCube = 0; #region drawScene Native.window.onframe += delegate { if (IsDisposed) { return; } gl.viewport(0, 0, gl_viewportWidth, gl_viewportHeight); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); perspective(45f, (float)gl_viewportWidth / (float)gl_viewportHeight, 0.1f, 100.0f); loadIdentity(); mvTranslate(new[] { 0.0f, 0.0f, -8.0f }); mvPushMatrix(); mvRotate(rCube, new[] { 1f, 1f, 1f }); gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexPositionBuffer); gl.vertexAttribPointer((uint)shaderProgram_vertexPositionAttribute, cubeVertexPositionBuffer_itemSize, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexColorBuffer); gl.vertexAttribPointer((uint)shaderProgram_vertexColorAttribute, cubeVertexColorBuffer_itemSize, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexTextureCoordBuffer); gl.vertexAttribPointer((uint)shaderProgram_textureCoordAttribute, cubeVertexTextureCoordBuffer_itemSize, gl.FLOAT, false, 0, 0); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, texture); gl.uniform1i(shaderProgram_samplerUniform, 0); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVertexIndexBuffer); setMatrixUniforms(); // ? // a[0].CS___8__locals19.currentTime = (((a[0].CS___8__locals19.currentTime + 0.01)) >>> 0); // haha. wtf jsc. :) currentTime = (currentTime + 0.01f); Native.document.title = new { currentTime }.ToString(); gl.uniform1f(shaderProgram_fTimeUniform, currentTime); gl.drawElements(drawingMode, cubeVertexIndexBuffer_numItems, gl.UNSIGNED_SHORT, 0); mvPopMatrix(); }; #endregion #region requestFullscreen Native.Document.body.ondblclick += delegate { if (IsDisposed) { return; } // http://tutorialzine.com/2012/02/enhance-your-website-fullscreen-api/ Native.Document.body.requestFullscreen(); }; #endregion } ); }
private void InitializeContent(IDefault page = null) { #region += Launched chrome.app.window dynamic self = Native.self; dynamic self_chrome = self.chrome; object self_chrome_socket = self_chrome.socket; if (self_chrome_socket != null) { if (!(Native.window.opener == null && Native.window.parent == Native.window.self)) { Console.WriteLine("chrome.app.window.create, is that you?"); // pass thru } else { // should jsc send a copresence udp message? chrome.runtime.UpdateAvailable += delegate { new chrome.Notification(title: "UpdateAvailable"); }; chrome.app.runtime.Launched += async delegate { // 0:12094ms chrome.app.window.create {{ href = chrome-extension://aemlnmcokphbneegoefdckonejmknohh/_generated_background_page.html }} Console.WriteLine("chrome.app.window.create " + new { Native.document.location.href }); new chrome.Notification(title: "ChromeUDPSendAsync"); var xappwindow = await chrome.app.window.create( Native.document.location.pathname, options : null ); //xappwindow.setAlwaysOnTop xappwindow.show(); await xappwindow.contentWindow.async.onload; Console.WriteLine("chrome.app.window loaded!"); }; return; } } #endregion var canvas = new IHTMLCanvas().AttachToDocument(); Native.Document.body.style.overflow = IStyle.OverflowEnum.hidden; canvas.style.SetLocation(0, 0); //http://www.khronos.org/webgl/public-mailing-list/archives/1002/msg00125.html var gl = (WebGLRenderingContext)canvas.getContext("experimental-webgl"); #region Dispose var IsDisposed = false; Dispose = delegate { if (IsDisposed) { return; } IsDisposed = true; canvas.Orphanize(); }; #endregion var s = new PulsSurface(this); this.onsurface(gl); #region AtResize Action AtResize = delegate { if (IsDisposed) { return; } canvas.width = Native.window.Width; canvas.height = Native.window.Height; this.onresize(Native.window.Width, Native.window.Height); Console.WriteLine("onresize"); }; AtResize(); Native.window.onresize += delegate { AtResize(); }; #endregion #region requestFullscreen Native.Document.body.ondblclick += delegate { if (IsDisposed) { return; } // http://tutorialzine.com/2012/02/enhance-your-website-fullscreen-api/ Native.Document.body.requestFullscreen(); }; #endregion #region loop Action loop = null; loop = delegate { if (IsDisposed) { return; } this.onframe(); Native.window.requestAnimationFrame += loop; }; Native.window.requestAnimationFrame += loop; #endregion }
//public static Task WriteAllBytes(this DirectoryEntry that, string filename, WebGL.WebGLRenderingContext gl) //{ //} public static Task WriteAllBytes(this DirectoryEntry that, string filename, IHTMLCanvas canvas) { // 754986ms WriteAllBytes { filename = 00272.png, position = 3101246, size = 3101246 } //view-source:63706 FileError is deprecated. Please use the 'name' or 'message' attributes of DOMError rather than 'code'. //view-source:54105 757622ms WriteAllBytes onerror { code = 7, message = An operation that depends on state cached in an interface object was made but the state had changed since it was read from disk., error = [object FileError] } //view-source:54105 757623ms out of files? //view-source:54105 757624ms WriteAllBytes { filename = 00273.png, position = 0, size = 3143207 } //view-source:54105 757624ms what happened? retry? //view-source:54105 760625ms what happened? retry! //view-source:54105 760626ms what happened? retry! retry7? //view-source:38832 Uncaught TypeError: Cannot read property 'toDataURL' of null //var data = canvas.toDataURL(); // Z:\jsc.svn\examples\javascript\chrome\apps\WebGL\360\x360eiffieballs\Application.cs //Z:\jsc.svn\examples\javascript\chrome\apps\WebGL\360\x360x83\Application.cs // 8K img png will be 50mb //var data = canvas.toDataURL(quality: 0.9); var data = canvas.toDataURL(quality: 1.0); //var data = canvas.toDataURL(quality: 0.1); // Z:\jsc.svn\examples\javascript\chrome\apps\WebGL\360stereo\x360stereotransition\Application.cs var prefix = "base64,"; var fileBytes = System.Convert.FromBase64String( data.Substring(data.IndexOf(prefix) + prefix.Length)); // https://groups.google.com/a/chromium.org/forum/#!topic/blink-dev/jcrEI_jfYFs // this blob wont delete? bytes = new Blob( blobParts: new ArrayBufferView[] { fileBytes }, options: new { type = "application/octet-stream;" + filename } ); fileBytes = null; data = null; //canvas = null; var c = new TaskCompletionSource <DirectoryEntry>(); // can do up to 120 files? // not disposing blob? //Blob blob = bytes; that.getFile( //"0000.jpg", filename, new { create = true, exclusive = false }, fentry => { // {{ fentry = [object FileEntry] }} //new IHTMLPre { new { fentry } }.AttachToDocument(); fentry.createWriter( w => { //new IHTMLPre { new { w } }.AttachToDocument(); // new Blob([document.getElementById("HTMLFile").value], //{ type: 'text/plain'} //var blob = new Blob( // blobParts: new ArrayBufferView[] { fileBytes }, // options: new { type = "application/octet-stream" } //); // http://stackoverflow.com/questions/12168909/blob-from-dataurl //w.write(fileBytes); //w.write(bytes); ////w.write() //// ready? var retry7 = false; //c.SetResult(that); //WriteAllBytes onerror { error = [object FileError], code = 7 } w.onerror = new Action( delegate { // https://developer.mozilla.org/en-US/docs/Web/API/FileError Console.WriteLine("WriteAllBytes onerror " + new { w.error.code, w.error.message, w.error }); if (w.error.code == 7) { Console.WriteLine("out of files? " + new { filename }); //https://code.google.com/p/chromium/issues/detail?id=83736 retry7 = true; } } ); //1063359ms WriteAllBytes onerror { code = 7, message = An operation that depends on state cached in an interface object was made but the state had changed since it was read from disk., error = [object FileError] } //view-source:54104 1063360ms out of files? //view-source:54104 1063361ms WriteAllBytes { filename = 00265.png, position = 0, size = 3058562 } //view-source:54104 1063361ms what happened? retry? //view-source:54104 1066363ms what happened? retry! w.onwriteend = new Action( delegate { var position = w.position; Console.WriteLine("onwriteend WriteAllBytes " + new { filename, position, bytes.size }); if (position < (long)bytes.size) { Console.WriteLine("what happened? retry? " + new { filename }); if (position == 0) { Native.setTimeout( delegate { if (retry7) { Console.WriteLine("what happened? retry7? " + new { filename }); WriteAllBytes(that, filename, canvas).ContinueWith( delegate { Console.WriteLine("what happened? retry7! " + new { filename }); c.SetResult(that); fentry = null; } ); return; } Console.WriteLine("what happened? retry! " + new { filename }); w.write(bytes); }, 5000 ); } return; } // https://groups.google.com/a/chromium.org/forum/#!topic/chromium-html5/6Behx6zrbCI //Console.WriteLine("WriteAllBytes Blob close"); // https://code.google.com/p/chromium/issues/detail?id=404301 // chrome://blob-internals/ //bytes.close(); bytes = null; //w.truncate(w.position); w = null; // need it? //Native.window.requestAnimationFrame += delegate //Console.WriteLine("WriteAllBytes yield"); c.SetResult(that); fentry = null; } ); w.write(bytes); } ); } ); return(c.Task); }
/// <summary> /// This is a javascript application. /// </summary> /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param> public Application(IApp page) { // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2013/201311/20131110-dae var oo = new List<THREE.Object3D>(); #region scene var window = Native.window; var camera = new THREE.PerspectiveCamera( 45, window.aspect, 1, 1000 //2000 ); camera.position.z = 400; // scene var scene = new THREE.Scene(); var ambient = new THREE.AmbientLight(0x101030); scene.add(ambient); var directionalLight = new THREE.DirectionalLight(0xffeedd); directionalLight.position.set(0, 0, 1); scene.add(directionalLight); // WebGLRenderer preserveDrawingBuffer var renderer = new THREE.WebGLRenderer( new { preserveDrawingBuffer = true } ); // https://github.com/mrdoob/three.js/issues/3836 renderer.setClearColor(0xfffff, 1); renderer.setSize(window.Width, window.Height); renderer.domElement.AttachToDocument(); renderer.domElement.style.SetLocation(0, 0); this.canvas = (IHTMLCanvas)renderer.domElement; var mouseX = 0; var mouseY = 0; var st = new Stopwatch(); st.Start(); Native.window.onframe += delegate { renderer.clear(); //camera.aspect = window.aspect; //camera.aspect = canvas.clientWidth / (double)canvas.clientHeight; //camera.aspect = canvas.aspect; camera.updateProjectionMatrix(); oo.WithEach( x => x.rotation.y = st.ElapsedMilliseconds * 0.0001 ); camera.position.x += (mouseX - camera.position.x) * .05; camera.position.y += (-mouseY - camera.position.y) * .05; camera.lookAt(scene.position); renderer.render(scene, camera); }; Native.window.onresize += delegate { if (canvas.parentNode == Native.document.body) { renderer.setSize(window.Width, window.Height); } }; #endregion new Cisco().Source.Task.ContinueWithResult( dae => { //dae.scale.x = 30; //dae.scale.y = 30; //dae.scale.z = 30; //dae.castShadow = true; //dae.receiveShadow = true; dae.scale.x = 5; dae.scale.y = 5; dae.scale.z = 5; dae.position.y = -80; scene.add(dae); oo.Add(dae); } ); }
private void InitializeContent(IDefault page = null) { #region += Launched chrome.app.window dynamic self = Native.self; dynamic self_chrome = self.chrome; object self_chrome_socket = self_chrome.socket; if (self_chrome_socket != null) { if (!(Native.window.opener == null && Native.window.parent == Native.window.self)) { Console.WriteLine("chrome.app.window.create, is that you?"); // pass thru } else { // should jsc send a copresence udp message? chrome.runtime.UpdateAvailable += delegate { new chrome.Notification(title: "UpdateAvailable"); }; chrome.app.runtime.Launched += async delegate { // 0:12094ms chrome.app.window.create {{ href = chrome-extension://aemlnmcokphbneegoefdckonejmknohh/_generated_background_page.html }} Console.WriteLine("chrome.app.window.create " + new { Native.document.location.href }); new chrome.Notification(title: "ChromeUDPSendAsync"); var xappwindow = await chrome.app.window.create( Native.document.location.pathname, options: null ); //xappwindow.setAlwaysOnTop xappwindow.show(); await xappwindow.contentWindow.async.onload; Console.WriteLine("chrome.app.window loaded!"); }; return; } } #endregion var canvas = new IHTMLCanvas().AttachToDocument(); Native.Document.body.style.overflow = IStyle.OverflowEnum.hidden; canvas.style.SetLocation(0, 0); //http://www.khronos.org/webgl/public-mailing-list/archives/1002/msg00125.html var gl = (WebGLRenderingContext)canvas.getContext("experimental-webgl"); #region Dispose var IsDisposed = false; Dispose = delegate { if (IsDisposed) return; IsDisposed = true; canvas.Orphanize(); }; #endregion var s = new PulsSurface(this); this.onsurface(gl); #region AtResize Action AtResize = delegate { if (IsDisposed) { return; } canvas.width = Native.window.Width; canvas.height = Native.window.Height; this.onresize(Native.window.Width, Native.window.Height); Console.WriteLine("onresize"); }; AtResize(); Native.window.onresize += delegate { AtResize(); }; #endregion #region requestFullscreen Native.Document.body.ondblclick += delegate { if (IsDisposed) return; // http://tutorialzine.com/2012/02/enhance-your-website-fullscreen-api/ Native.Document.body.requestFullscreen(); }; #endregion #region loop Action loop = null; loop = delegate { if (IsDisposed) return; this.onframe(); Native.window.requestAnimationFrame += loop; }; Native.window.requestAnimationFrame += loop; #endregion }
/// <summary> /// This is a javascript application. /// </summary> /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param> public Application(IApp page) { // if we are running in a SYSTEM account // the chrome no-sandbox only allows software renderer // where we get 1 frame per sec. // on older systems we may not get GL_OES_standard_derivatives // http://stackoverflow.com/questions/16795278/disable-some-gl-extensions-for-debugging-three-js-app // ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "", // or that system is just old as hell // http://stackoverflow.com/questions/16795278/disable-some-gl-extensions-for-debugging-three-js-app //http://thematicmapping.org/playground/webgl/earth/ // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201402/20140222 // Earth params var radius = 0.5; //var segments = 32; var segments = 128; var rotation = 6; var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera(45, Native.window.aspect, 0.01, 1000); camera.position.z = 1.5; var renderer = new THREE.WebGLRenderer( new { preserveDrawingBuffer = true } ); renderer.setSize(); scene.add(new THREE.AmbientLight(0x333333)); var light = new THREE.DirectionalLight(0xffffff, 1); light.position.set(5, 3, 5); scene.add(light); var parent = new THREE.Object3D(); scene.add(parent); #region sphere var sphere = new THREE.Mesh( new THREE.SphereGeometry(radius, segments, segments), new THREE.MeshPhongMaterial( new { map = new THREE.Texture().With( async s => { //0:75ms event: _2_no_clouds_4k_low view-source:36543 //Application Cache Progress event (1 of 2) http://192.168.1.72:22248/view-source 192.168.1.72/:1 //Application Cache Progress event (2 of 2) 192.168.1.72/:1 //Application Cache Cached event 192.168.1.72/:1 //1:1018ms event: _2_no_clouds_4k_low done view-source:36543 //1:1019ms event: _2_no_clouds_4k view-source:36543 //event.returnValue is deprecated. Please use the standard event.preventDefault() instead. view-source:2995 //1:16445ms event: _2_no_clouds_4k done // ~ tilde to open css editor? Console.WriteLine("event: _2_no_clouds_4k_low"); s.image = await new _2_no_clouds_4k_low(); s.needsUpdate = true; Console.WriteLine("event: _2_no_clouds_4k_low done"); await 20000; Console.WriteLine("event: _2_no_clouds_4k"); s.image = await new _2_no_clouds_4k(); s.needsUpdate = true; Console.WriteLine("event: _2_no_clouds_4k done"); } ), bumpMap = THREE.ImageUtils.loadTexture( new elev_bump_4k().src //new elev_bump_4k_low().src ), // applies onyl to shaders to create the shadow bumpScale = 0.001, specularMap = new THREE.Texture().With( async s => { Console.WriteLine("event: water_4k_low"); s.image = await new water_4k_low(); s.needsUpdate = true; Console.WriteLine("event: water_4k_low done"); await 20000; Console.WriteLine("event: water_4k"); s.image = await new water_4k(); s.needsUpdate = true; Console.WriteLine("event: water_4k done"); } ), //specular = new THREE.Color("grey") specular = new THREE.Color(0xa0a0a0) }) ); #endregion // http://stackoverflow.com/questions/12447734/three-js-updateing-texture-on-plane //sphere.rotation.y = rotation; parent.rotation.y = rotation; //sphere.position.x = 10; //sphere.position.y = 10; //sphere.position.z = 10; //sphere.position.normalize(); //sphere.position.multiplyScalar(200); parent.add(sphere); //scene.add(sphere); #region clouds var clouds = new THREE.Mesh( new THREE.SphereGeometry( //radius + 0.003, radius + 0.006, segments, segments), new THREE.MeshPhongMaterial( new { //map = THREE.ImageUtils.loadTexture( // //new fair_clouds_4k().src // new fair_clouds_4k_low().src // ), map = new THREE.Texture().With( async s => { Console.WriteLine("event: fair_clouds_4k_low"); s.image = await new fair_clouds_4k_low(); s.needsUpdate = true; Console.WriteLine("event: fair_clouds_4k_low done"); await 20000; Console.WriteLine("event: fair_clouds_4k"); s.image = await new fair_clouds_4k(); s.needsUpdate = true; Console.WriteLine("event: fair_clouds_4k done"); } ), transparent = true }) ); //clouds.rotation.y = rotation; parent.add(clouds); //scene.add(clouds); #endregion #region Location on sphere Action AddCities = async delegate { var table = await this.GetAllCities(); Console.WriteLine(table.Rows.Count.ToString()); for (var r = 0; r < table.Rows.Count; r++) { var latitude = (double)table.Rows[r]["Latitude"]; var longtitude = (double)table.Rows[r]["Longtitude"]; addLocation(latitude, longtitude, radius, 0.001, parent, 6); Console.WriteLine(latitude.ToString()); await 100; } }; AddCities(); #endregion var stars = new THREE.Mesh( new THREE.SphereGeometry(90, 64, 64), new THREE.MeshBasicMaterial( new { map = THREE.ImageUtils.loadTexture(new galaxy_starfield().src), side = THREE.BackSide }) ); scene.add(stars); this.canvas = (IHTMLCanvas)renderer.domElement; //renderer.domElement.AttachToDocument(); this.canvas.AttachToDocument(); this.canvas.style.SetLocation(0, 0); // jsc, what pointers do we have in store? this.canvas.css.style.cursor = IStyle.CursorEnum.pointer; this.canvas.css.active.style.cursor = IStyle.CursorEnum.move; var old = new { parent = new { parent.rotation.x, parent.rotation.y }, //sphere = new //{ // //sphere.rotation.x, // //sphere.rotation.y //}, //clouds = new //{ // //clouds.rotation.x, // //clouds.rotation.y, //}, CursorX = 0, CursorY = 0 }; #region onmousedown this.canvas.onmousedown += e => { var pointerLock = this.canvas == Native.document.pointerLockElement; if (e.MouseButton == IEvent.MouseButtonEnum.Middle) { this.canvas.requestFullscreen(); this.canvas.requestPointerLock(); } else { // movementX no longer works old = new { parent = new { parent.rotation.x, parent.rotation.y }, //sphere = new //{ // sphere.rotation.x, // sphere.rotation.y //}, //clouds = new //{ // clouds.rotation.x, // clouds.rotation.y, //}, e.CursorX, e.CursorY }; if (pointerLock) { // skip } else { e.CaptureMouse(); } } }; #endregion var z = camera.position.z; var sfx = new WebGLEarthTest.HTML.Audio.FromAssets.SatelliteBeep_Sputnik1 { autobuffer = true, // this aint working //loop = true }; sfx.play(); //sfx.AttachToHead(); // http://soundfxnow.com/sound-fx/sputnik-satellite-beeping/ this.canvas.onmousewheel += e => { //camera.position.z = 1.5; // min max. shall adjust speed also! // max 4.0 // min 0.6 z -= 0.1 * e.WheelDirection; z = z.Max(0.6).Min(4.5); //Native.document.title = new { camera.position.z }.ToString(); }; // X:\jsc.svn\examples\javascript\Test\TestMouseMovement\TestMouseMovement\Application.cs #region onmousemove this.canvas.onmousemove += e => { var pointerLock = this.canvas == Native.document.pointerLockElement; //Console.WriteLine(new { e.MouseButton, pointerLock, e.movementX }); if (e.MouseButton == IEvent.MouseButtonEnum.Left) { if (pointerLock) { parent.rotation.x += 0.01 * e.movementY; parent.rotation.y += 0.01 * e.movementX; //sphere.rotation.x += 0.01 * e.movementY; //sphere.rotation.y += 0.01 * e.movementX; //clouds.rotation.x += 0.01 * e.movementY; //clouds.rotation.y += 0.01 * e.movementX; } else { parent.rotation.x = old.parent.x + 0.01 * (e.CursorY - old.CursorY); parent.rotation.y = old.parent.y + 0.01 * (e.CursorX - old.CursorX); //sphere.rotation.x = old.sphere.x + 0.01 * (e.CursorY - old.CursorY); //sphere.rotation.y = old.sphere.y + 0.01 * (e.CursorX - old.CursorX); //clouds.rotation.x = old.clouds.x + 0.01 * (e.CursorY - old.CursorY); //clouds.rotation.y = old.clouds.y + 0.01 * (e.CursorX - old.CursorX); } // Native.document.title = new { e.movementX, e.movementY }.ToString(); } }; #endregion // could we Native.window.onframe += e => { if (this.canvas.parentNode == null) return; camera.aspect = canvas.clientWidth / (double)canvas.clientHeight; camera.updateProjectionMatrix(); camera.position.z += (z - camera.position.z) * e.delay.ElapsedMilliseconds / 200; // the larger the vew the slower the rotation shall be var speed = 0.0001 * e.delay.ElapsedMilliseconds + 0.007 * 96.0 / canvas.clientHeight * 1.0 / camera.position.z; //Native.document.title = new { s = 96.0 / canvas.clientHeight }.ToString(); //Native.document.title = new { speed }.ToString(); //controls.update(); //sphere.rotation.y += speed; //clouds.rotation.y += speed; parent.rotation.y += speed; renderer.render(scene, camera); }; Native.window.onresize += delegate { //if (canvas.parentNode == Native.document.body) // are we embedded? if (page != null) renderer.setSize(); }; //new IStyle(this.canvas.css.before) //{ // content = "'do a middle click to maximize the earth dashboard'", // left = "1em", // bottom = "1em", // color = "white", // position = IStyle.PositionEnum.absolute //}; }
private void Initialize(IHTMLCanvas c, WebGLRenderingContext gl, IDefault page) { // http://cs.helsinki.fi/u/ilmarihe/metatunnel.html // http://wakaba.c3.cx/w/puls.html Action <string> alert = Native.window.alert; c.style.border = "1px solid yellow"; page.MaxTextures.innerText = "" + gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS); // https://www.khronos.org/webgl/public-mailing-list/archives/1007/msg00034.html var vs = ""; vs += "precision highp float; \n"; vs += "attribute vec3 aVertexPosition;"; vs += "attribute vec2 aTextureCoord;"; vs += "uniform mat4 uModelViewMatrix;"; vs += "uniform mat4 uProjectionMatrix;"; vs += "varying vec2 vTextureCoord;"; vs += "void main(void) {"; vs += "gl_Position = uProjectionMatrix * uModelViewMatrix * vec4(aVertexPosition, 1.0);"; vs += "vTextureCoord = vec2(aTextureCoord.x, 1.0 - aTextureCoord.y);"; vs += "}"; var fs = ""; fs += "precision highp float; \n"; fs += "varying vec2 vTextureCoord;"; fs += "uniform sampler2D uSamplerDiffuse1;"; fs += "uniform sampler2D uSamplerDiffuse2;"; fs += "uniform sampler2D uSamplerDiffuse3;"; fs += "uniform sampler2D uSamplerDiffuse4;"; fs += "uniform sampler2D uSamplerDiffuse5;"; fs += "uniform sampler2D uSamplerDiffuse6;"; fs += "void main(void) {"; fs += "gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0) * texture2D(uSamplerDiffuse1, vTextureCoord)"; fs += "+ vec4(0.0, 1.0, 0.0, 1.0) * texture2D(uSamplerDiffuse2, vTextureCoord)"; fs += "+ vec4(0.0, 0.0, 1.0, 1.0) * texture2D(uSamplerDiffuse3, vTextureCoord)"; fs += "+ vec4(0.0, 1.0, 1.0, 1.0) * texture2D(uSamplerDiffuse4, vTextureCoord)"; fs += "+ vec4(1.0, 0.0, 1.0, 1.0) * texture2D(uSamplerDiffuse5, vTextureCoord)"; fs += "+ vec4(1.0, 1.0, 0.0, 1.0) * texture2D(uSamplerDiffuse6, vTextureCoord);"; fs += "}"; var xfs = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(xfs, fs); gl.compileShader(xfs); if ((int)gl.getShaderParameter(xfs, gl.COMPILE_STATUS) != 1) { // vs: ERROR: 0:2: '' : Version number not supported by ESSL // fs: ERROR: 0:1: '' : No precision specified for (float) var error = gl.getShaderInfoLog(xfs); Native.window.alert("fs: " + error); return; } var xvs = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(xvs, vs); gl.compileShader(xvs); if ((int)gl.getShaderParameter(xvs, gl.COMPILE_STATUS) != 1) { // vs: ERROR: 0:2: '' : Version number not supported by ESSL // vs: ERROR: 0:10: '-' : wrong operand types no operation '-' exists that takes a left-hand operand of type 'const mediump int' and a right operand of type 'float' (or there is no acceptable conversion) var error = gl.getShaderInfoLog(xvs); Native.window.alert("vs: " + error); return; } var shader = new foo(); shader.program = gl.createProgram(); gl.attachShader(shader.program, xvs); gl.attachShader(shader.program, xfs); gl.linkProgram(shader.program); var linked = gl.getProgramParameter(shader.program, gl.LINK_STATUS); if (linked == null) { var error = gl.getProgramInfoLog(shader.program); Native.window.alert("Error while linking: " + error); return; } gl.useProgram(shader.program); shader.aVertexPosition = gl.getAttribLocation(shader.program, "aVertexPosition"); shader.aTextureCoord = gl.getAttribLocation(shader.program, "aTextureCoord"); gl.enableVertexAttribArray((uint)shader.aVertexPosition); gl.enableVertexAttribArray((uint)shader.aTextureCoord); shader.u["uModelViewMatrix"] = gl.getUniformLocation(shader.program, "uModelViewMatrix"); shader.u["uProjectionMatrix"] = gl.getUniformLocation(shader.program, "uProjectionMatrix"); shader.u["uSamplerDiffuse1"] = gl.getUniformLocation(shader.program, "uSamplerDiffuse1"); shader.u["uSamplerDiffuse2"] = gl.getUniformLocation(shader.program, "uSamplerDiffuse2"); shader.u["uSamplerDiffuse3"] = gl.getUniformLocation(shader.program, "uSamplerDiffuse3"); shader.u["uSamplerDiffuse4"] = gl.getUniformLocation(shader.program, "uSamplerDiffuse4"); shader.u["uSamplerDiffuse5"] = gl.getUniformLocation(shader.program, "uSamplerDiffuse5"); shader.u["uSamplerDiffuse6"] = gl.getUniformLocation(shader.program, "uSamplerDiffuse6"); shader.MV_MATRIX = new float[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }; shader.PROJECTION_MATRIX = new float[] { 1.000f, 0.000f, 0.000f, 0.000f, 0.000f, 1.000f, 0.000f, 0.000f, 0.000f, 0.000f, 0.002f, 0.000f, 0.000f, 0.000f, 0.998f, 1.000f }; var bar = default(bar); bar = initObject( gl, delegate { if (bar == null) { return; } renderFrame(gl, shader, bar); c.style.border = "2px solid green"; } ); }
private static void InitializeContent() { Action __WoodsXmasByRobert_loaded = null; Console.WriteLine( new { Native.window.opener, Native.window.parent } ); Native.window.parent.With( parent => { parent.postMessage("WoodsXmasByRobert.preparing"); Console.WriteLine("WoodsXmasByRobert.preparing"); __WoodsXmasByRobert_loaded = delegate { Console.WriteLine("will post WoodsXmasByRobert.loaded"); __WoodsXmasByRobert_loaded = null; parent.postMessage("WoodsXmasByRobert.loaded"); }; } ); //<!-- Snow flakes --> new IHTMLScript { type = "x-shader/x-vertex", id = "vertexshader", innerText = new Shaders.particlesVertexShader().ToString() }.AttachToDocument(); new IHTMLScript { type = "x-shader/x-fragment", id = "fragmentshader", innerText = new Shaders.particlesFragmentShader().ToString() }.AttachToDocument(); var w = Native.window; dynamic window = w; // http://stackoverflow.com/questions/4923136/why-doesnt-firefox-support-mp3-file-format-in-audio // Timestamp: 12/28/2012 1:22:05 PM //Warning: HTTP "Content-Type" of "audio/mpeg3" is not supported. Load of media resource http://192.168.1.100:27248/assets/WoodsXmasByRobert/unfiltered_mix.mp3 failed. //Source File: http://192.168.1.100:27248/ //Line: 0 #region snd var snd = new HTML.Audio.FromAssets.unfiltered_mix { volume = 0.9 }; window.snd = snd; Native.window.onfocus += delegate { Console.WriteLine("WoodsXmasByRobert onfocus"); snd.volume = 0.9; }; Native.window.onblur += delegate { Console.WriteLine("WoodsXmasByRobert onblur"); snd.volume = 0.1; // if we are also not visible anymore // and animations frame stop // we should stop all sound }; #endregion var canvas = new IHTMLCanvas(); object webglRenderer_args = new object().With( (dynamic a) => { a.clearColor = 0x000000; a.clearAlpha = 1.0; a.preserveDrawingBuffer = true; a.canvas = canvas; } ); var webglRenderer = new THREE.WebGLRenderer( webglRenderer_args ); webglRenderer.autoClear = false; //var canvas = (IHTMLCanvas)webglRenderer.domElement; canvas.AttachToDocument(); webglRenderer.setSize(Native.window.Width, Native.window.Height); var camera = new THREE.PerspectiveCamera(75, Native.window.Width / Native.window.Height, 1, 100000); camera.position.z = 0; camera.position.x = 0; camera.position.y = 0; window.camera = camera; var cameraTarget = new THREE.Vector3(); cameraTarget.z = -400; camera.lookAt(cameraTarget); window.cameraTarget = cameraTarget; var loadingImage = THREE.ImageUtils.loadTexture(new loading().src); var map = THREE.ImageUtils.loadTexture(new snowflake().src); var starImage = THREE.ImageUtils.loadTexture(new flare().src); window.loadingImage = loadingImage; window.map = map; window.starImage = starImage; #region cursor var cursor = new pointer(); cursor.style.zIndex = 0x1000; cursor.Hide(); cursor.AttachToDocument(); dynamic style = Native.Document.body.style; //http://stackoverflow.com/questions/7849002/how-can-i-set-the-hotspot-to-the-center-of-a-custom-cursor // http://stackoverflow.com/questions/5649608/custom-css-cursors style.cursor = "url(" + cursor.src + ") 16 16,pointer"; #endregion var mouseXpercent = 0.5; var mouseYpercent = 0.5; #region onmousemove var CursorX = 0; var CursorY = 0; Native.Document.onmousemove += e => { if (Native.Document.pointerLockElement == Native.Document.body) { cursor.Show(); CursorX += e.movementX; CursorY += e.movementY; } else { cursor.Hide(); CursorX = e.CursorX; CursorY = e.CursorY; } // keep cursor in view CursorX = CursorX.Max(0).Min(Native.window.Width); CursorY = CursorY.Max(0).Min(Native.window.Height); if (Native.document.pointerLockElement == Native.document.body) { cursor.style.SetLocation(CursorX - 16, CursorY - 16); } var windowHalfX = Native.window.Width >> 1; var windowHalfY = Native.window.Height >> 1; var mouseX = (CursorX - windowHalfX); var mouseY = (CursorY - windowHalfY); mouseXpercent = mouseX / windowHalfX; mouseYpercent = mouseY / windowHalfY; window.mouseXpercent = mouseXpercent; window.mouseYpercent = mouseYpercent; }; #endregion Native.Document.onmousedown += e => { if (e.MouseButton == IEvent.MouseButtonEnum.Right) Native.Document.body.requestPointerLock(); }; new AppCode().Content.AttachToDocument().onload += delegate { // ScriptCoreLib should define this event! snd.addEventListener( "loadeddata", new Action( delegate { new IFunction("window.checkLoadingDone();").apply(Native.window); } ) ); var scene = (THREE.Scene)(object)window.scene; scene.add(camera); #region Cloud { object args = new object().With( (dynamic a) => { a.map = THREE.ImageUtils.loadTexture(new cloud().src); a.transparent = true; a.opacity = 0.17; a.fog = false; } ); var cloudPlane = new THREE.PlaneGeometry(12500, 1880); var cloud = new THREE.Mesh(cloudPlane, new THREE.MeshBasicMaterial(args)); cloud.position.set(300, 5350, -4450); cloud.lookAt(camera.position); scene.add(cloud); window.cloud = cloud; } #endregion #region Sky { object args = new object().With( (dynamic a) => { a.map = THREE.ImageUtils.loadTexture(new sky().src); a.opacity = 0.57; a.fog = false; } ); var skyPlane = new THREE.PlaneGeometry(9000, 6000); var sky = new THREE.Mesh(skyPlane, new THREE.MeshBasicMaterial(args)); sky.scale.set(4, 2.5, 2.5); sky.position.set(0, 7500, -6000); sky.lookAt(camera.position); scene.add(sky); window.sky = sky; } #endregion #region moon { dynamic moon_material_args = new object(); moon_material_args.map = THREE.ImageUtils.loadTexture(new moon().src); moon_material_args.transparent = true; moon_material_args.opacity = 0.3; moon_material_args.fog = false; moon_material_args.blending = THREE.AdditiveBlending; var moonPlane = new THREE.PlaneGeometry(1000, 1000); var moon = new THREE.Mesh(moonPlane, new THREE.MeshBasicMaterial( (object)moon_material_args ) ); moon.position.set(300, 4300, -4600); moon.lookAt(camera.position); scene.add(moon); window.moon = moon; } #endregion #region subtitleArray var subtitleArray = (IArray<THREE.Mesh>)(object)window.subtitleArray; var textPlane = new THREE.PlaneGeometry(512, 80); new SubtitlesImages().Images.WithEach( i => { object args = new object().With( (dynamic a) => { a.map = THREE.ImageUtils.loadTexture(i.src); a.transparent = true; a.depthTest = false; } ); var sub = new THREE.Mesh(textPlane, new THREE.MeshBasicMaterial(args)); sub.position.z = -800; sub.position.y = -550; sub.visible = false; camera.add(sub); subtitleArray.push(sub); } ); { var endPlane = new THREE.PlaneGeometry(500, 100); object args = new object().With( (dynamic a) => { a.map = THREE.ImageUtils.loadTexture(new xmas().src); a.transparent = true; a.opacity = 1.0; a.depthTest = false; } ); var end = new THREE.Mesh(endPlane, new THREE.MeshBasicMaterial(args)); end.position.z = -400; end.position.y = 100; end.visible = false; camera.add(end); subtitleArray.push(end); window.end = end; } new IFunction("window.setupSubtitles();").apply(Native.window); #endregion var particles = (THREE.ParticleSystem)(object)window.particles; var bgSprite = (THREE.Sprite)(object)window.bgSprite; var loadingSprite = (THREE.Sprite)(object)window.loadingSprite; var pointLight = (THREE.PointLight)(object)window.pointLight; var treeArray = (IArray<THREE.Mesh>)(object)window.treeArray; var rockArray = (IArray<THREE.Mesh>)(object)window.rockArray; var flowerArray = (IArray<THREE.Mesh>)(object)window.flowerArray; var groundMesh1 = (THREE.Mesh)(object)window.groundMesh1; var groundMesh2 = (THREE.Mesh)(object)window.groundMesh2; var renderModel = (object)window.renderModel; var effectFilm = (object)window.effectFilm; var effectVignette = (object)window.effectVignette; var effectCopy = (object)window.effectCopy; var composer = new THREE.EffectComposer(webglRenderer); composer.addPass(renderModel); composer.addPass(effectFilm); composer.addPass(effectVignette); composer.addPass(effectCopy); var speedEffector_value = (int)new IFunction("return window.speedEffector.value;").apply(Native.window); #region load Action<string, Action<object>> load = (src, yield) => { new THREE.JSONLoader().load( src, IFunction.OfDelegate(yield) ); }; #endregion #region sled load( new WoodsXmasByRobert.Design.models.sleigh().Content.src, geometry => { Console.WriteLine("got sled!"); var sled = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial() ); var scale = 4; sled.scale.set(scale, scale, scale); sled.rotation.y = -Math.PI / 2; sled.position.y = -290; sled.position.z = -80; scene.add(sled); window.sled = sled; new IFunction("window.checkLoadingDone();").apply(Native.window); } ); #endregion var random = new Random(); #region treeDead load( new WoodsXmasByRobert.Design.models.treeDead().Content.src, tree1Geo => { Console.WriteLine("got treeDead!"); load( new WoodsXmasByRobert.Design.models.treeEvergreenHigh().Content.src, tree2Geo => { Console.WriteLine("got treeEvergreenHigh!"); var gridSize = 500; for (var x = 0; x < 8; x++) { for (var z = 0; z < 12; z++) { var geo = tree2Geo; if (random.NextDouble() < 0.25) if (x != 0 && x != 7) { geo = tree1Geo; } var mesh = new THREE.Mesh(geo, new THREE.MeshFaceMaterial()); var scale = 1.2 + random.NextDouble(); mesh.scale.set(scale, scale * 2, scale); var posx = 0.0; if (x < 4) { posx = (x * gridSize) - (gridSize * 4) - 100 + random.NextDouble() * 100 - 50; } else { posx = (x * gridSize) - 1400 + random.NextDouble() * 100 - 50; }; var posz = -(z * gridSize) + random.NextDouble() * 100 - 50; mesh.position.set(posx, -400 - (random.NextDouble() * 80), posz); mesh.rotation.set((random.NextDouble() * 0.2) - 0.1, random.NextDouble() * Math.PI, (random.NextDouble() * 0.2) - 0.1); scene.add(mesh); treeArray.push(mesh); } } new IFunction("window.checkLoadingDone();").apply(Native.window); } ); } ); #endregion #region bird load( new WoodsXmasByRobert.Design.models.eagle().Content.src, geometry => { Console.WriteLine("got bird!"); dynamic args = new object(); args.color = 0x000000; args.morphTargets = true; args.fog = false; var bird = new THREE.MorphAnimMesh( geometry, new THREE.MeshBasicMaterial( (object)args ) ); bird.duration = 1000; bird.scale.set(4, 4, 4); bird.rotation.y = Math.PI; bird.position.set(0, 3000, -1500); scene.add(bird); window.bird = bird; new IFunction("window.checkLoadingDone();").apply(Native.window); } ); #endregion #region rock load( new WoodsXmasByRobert.Design.models.rock().Content.src, geometry => { Console.WriteLine("got rock!"); var numOfRocks = 25; for (var i = 0; i < numOfRocks; ++i) { dynamic args = new object(); args.color = 0x444444; var mesh = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial((object)args)); var scale = 1 + (random.NextDouble() * 0.5); mesh.scale.set(scale, scale, scale); mesh.rotation.set(0, random.NextDouble() * Math.PI, 0); mesh.position.set((random.NextDouble() * 4000) - 2000, -400, (random.NextDouble() * 6000) - 6000); if (mesh.position.x < 45) if (mesh.position.x > 0) { mesh.position.x += 450; } if (mesh.position.x > -450) if (mesh.position.x < 0) { mesh.position.x -= 450; } scene.add(mesh); rockArray.push(mesh); } new IFunction("window.checkLoadingDone();").apply(Native.window); } ); #endregion #region horse load( new WoodsXmasByRobert.Design.models.horse().Content.src, geometry => { Console.WriteLine("got horse!"); dynamic horse_material_args = new object(); horse_material_args.color = 0x090601; horse_material_args.morphTargets = true; var horse = new THREE.MorphAnimMesh(geometry, new THREE.MeshLambertMaterial( (object)horse_material_args ) ); horse.duration = 1000; horse.scale.set(2.5, 1.8, 2); horse.rotation.y = Math.PI; horse.position.set(0, -350, -700); scene.add(horse); window.horse = horse; //checkLoadingDone(); // Handles var plane = new THREE.PlaneGeometry(700, 10, 40, 1); var l = Math.Floor(plane.vertices.Length / 2.0); for (var i = 0; i < l; i++) { var offset = Math.Sin(i / 14) * 100; plane.vertices[i].y -= offset; plane.vertices[i + 41].y -= offset; plane.vertices[i].z -= (i / 5) + (offset * -1) / 8; plane.vertices[i + 41].z += (i / 5) - (offset * -1) / 8; } dynamic material_args = new object(); material_args.color = 0x090601; material_args.side = THREE.DoubleSide; var material = new THREE.MeshBasicMaterial( (object)material_args ); var leftHandle = new THREE.Mesh(plane, material); leftHandle.position.y = -120; leftHandle.position.z = -350; leftHandle.position.x = -30; leftHandle.rotation.y = -(Math.PI / 2) + 0.075; leftHandle.rotation.x = Math.PI * 2 - 0.075; scene.add(leftHandle); window.leftHandle = leftHandle; var rightHandle = new THREE.Mesh(plane, material); rightHandle.position.y = -120; rightHandle.position.z = -350; rightHandle.position.x = 30; rightHandle.rotation.y = -(Math.PI / 2) - 0.075; rightHandle.scale.z = -1; rightHandle.rotation.x = Math.PI * 2 - 0.075; scene.add(rightHandle); window.rightHandle = rightHandle; new IFunction("window.checkLoadingDone();").apply(Native.window); } ); #endregion #region flowerLoaded Action<object, bool> flowerLoaded = (geometry, halfScale) => { var numOfFlowers = 20; var half = Math.Floor(numOfFlowers / 2.0); dynamic args = new object(); args.color = 0x444444; for (var i = 0; i < half; ++i) { var mesh = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial( (object)args ) ); var scale = 1 + (random.NextDouble() * 1); if (halfScale) { scale *= 0.6; } mesh.scale.set(scale, scale, scale); mesh.rotation.set((random.NextDouble() * 0.6) - 0.3, random.NextDouble() * Math.PI, (random.NextDouble() * 0.6) - 0.3); mesh.position.set((random.NextDouble() * 1000) - 500, -310, (random.NextDouble() * 6000) - 6000); if (mesh.position.x < 100) if (mesh.position.x > 0) { mesh.position.x += 100; } if (mesh.position.x > -100) if (mesh.position.x < 0) { mesh.position.x -= 100; } scene.add(mesh); flowerArray.push(mesh); } new IFunction("window.checkLoadingDone();").apply(Native.window); }; #endregion #region weeds01 load( new WoodsXmasByRobert.Design.models.weeds01().Content.src, geometry => { Console.WriteLine("got weeds01!"); flowerLoaded(geometry, false); } ); #endregion #region glowbulb load( new WoodsXmasByRobert.Design.models.glowbulb().Content.src, geometry => { Console.WriteLine("got glowbulb!"); flowerLoaded(geometry, true); } ); #endregion #region run Action<double> run = delta => { // trees var mesh = default(THREE.Mesh); for (var i = 0; i < treeArray.length; ++i) { mesh = treeArray[i]; // respawn if (mesh.position.z > camera.position.z + 700) { mesh.position.z -= 6000; var scale = 1.2 + random.NextDouble(); mesh.scale.set(scale, scale * 2, scale); } } // rocks for (var i = 0; i < rockArray.length; ++i) { mesh = rockArray[i]; // respawn if (mesh.position.z > camera.position.z + 400) { mesh.position.z -= 6000; } } // flowers for (var i = 0; i < flowerArray.length; ++i) { mesh = flowerArray[i]; // respawn if (mesh.position.z > camera.position.z + 400) { mesh.position.z -= 6000; } } // ground respawn if (groundMesh1.position.z - 10000 > camera.position.z) { groundMesh1.position.z -= 40000; } if (groundMesh2.position.z - 10000 > camera.position.z) { groundMesh2.position.z -= 40000; } }; #endregion var oldTime = new IDate().getTime(); var r = 0.0; bool disableNextFrame = false; #region loop Action loop = delegate { var allLoaded = (bool)(object)window.allLoaded; var horse = (THREE.MorphAnimMesh)(object)window.horse; var bird = (THREE.MorphAnimMesh)(object)window.bird; var leftHandle = (THREE.Mesh)(object)window.leftHandle; var rightHandle = (THREE.Mesh)(object)window.rightHandle; var moon = (THREE.Mesh)(object)window.moon; var cloud = (THREE.Mesh)(object)window.cloud; var sky = (THREE.Mesh)(object)window.sky; var sled = (THREE.Mesh)(object)window.sled; //new IFunction("this.loop();").apply(Native.Window); var time = new IDate().getTime(); var delta = time - oldTime; oldTime = time; if (double.IsNaN(delta)) { delta = 1000 / 60; } var maxSpeed = delta / 2; if (allLoaded) { r += delta / 2000; run(delta); var noise = random.NextDouble() * 2; camera.position.x = (50 * Math.Cos(r * 2)) * speedEffector_value; camera.position.y = (2 * Math.Sin(r * 12) - 100) * speedEffector_value; camera.up.x = (Math.Sin(r * 12) / 50) * speedEffector_value; cameraTarget.y += (((camera.position.y + 80) + noise - mouseYpercent * 120) - cameraTarget.y) / 20; cameraTarget.x += (mouseXpercent * 400 - cameraTarget.x) / 20; var speed = (delta / 2) * speedEffector_value; camera.position.z -= speed; cameraTarget.z -= speed; camera.lookAt(cameraTarget); pointLight.position.z -= speed; if (moon != null) { moon.position.z -= speed; } if (cloud != null) { cloud.position.z -= speed; } if (sky != null) { sky.position.z -= speed; } #region sled if (sled != null) { sled.position.z -= speed; sled.position.x = camera.position.x; } #endregion #region bird if (bird != null) { bird.position.x = 200 * Math.Cos(r) + ((bird.position.z - camera.position.z) / 10); bird.position.y = 4000 + (Math.Sin(r) * 300); bird.position.z -= maxSpeed * 1.25; if (bird.position.z < camera.position.z - 10000) { bird.position.z = camera.position.z - 500; } bird.updateAnimation(delta); } #endregion #region horse if (horse != null) { horse.position.z -= speed; horse.position.x = camera.position.x; horse.updateAnimation(speed * 2); leftHandle.position.z -= speed; leftHandle.position.x = camera.position.x - 37; rightHandle.position.z -= speed; rightHandle.position.x = camera.position.x + 40; leftHandle.scale.y = 1 - Math.Abs(Math.Sin(camera.position.z / 150)) / 4; rightHandle.scale.y = leftHandle.scale.y; } #endregion particles.position.z -= speed; new IFunction("e", "window.uniforms.globalTime.value += e;").apply(Native.window, delta * 0.00015); new IFunction("e", "window.uniforms.speed.value = e;").apply(Native.window, speed / maxSpeed); new IFunction("window.runSubtitles();").apply(Native.window); //disableNextFrame = true; if (__WoodsXmasByRobert_loaded != null) __WoodsXmasByRobert_loaded(); } else { if (loadingSprite != null) { loadingSprite.position.set(Native.window.Width >> 1, Native.window.Height >> 1, 0); loadingSprite.rotation -= 0.08; } } if (bgSprite != null) { bgSprite.position.set(Native.window.Width >> 1, Native.window.Height >> 1, 0); } new IFunction("window.TWEEN.update();").apply(Native.window); //if (has_gl) { webglRenderer.clear(); composer.render(0.01); } }; #endregion #region animate Native.window.onframe += delegate { if (disableNextFrame) return; loop(); }; #endregion Action AtResize = delegate { // notify the renderer of the size change webglRenderer.setSize(Native.window.Width, Native.window.Height); // update the camera camera.aspect = Native.window.Width / Native.window.Height; camera.updateProjectionMatrix(); }; #region onresize Native.window.onresize += delegate { AtResize(); }; #endregion AtResize(); }; Native.Document.body.ondblclick += delegate { Native.Document.body.requestFullscreen(); }; Native.Document.body.onmousedown += e => { if (e.MouseButton == IEvent.MouseButtonEnum.Middle) { if (Native.Document.pointerLockElement == Native.Document.body) { // cant requestFullscreen while pointerLockElement Console.WriteLine("exitPointerLock"); Native.Document.exitPointerLock(); Native.Document.exitFullscreen(); return; } Native.Document.body.requestFullscreen(); Native.Document.body.requestPointerLock(); } }; Native.Document.oncontextmenu += e => { e.preventDefault(); }; }