summaryrefslogtreecommitdiffstats
path: root/o3d/samples/shader-test.html
blob: 812d067732f7f8648eaf4fcbd2d19ec6df7f7689 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
<!--
Copyright 2009, Google Inc.
All rights reserved.

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

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

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

<!--
O3D Tutorial

In this tutorial, we load a scene file and then apply various shaders to it.
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>
Shader Test
</title>
<style type="text/css">
  html, body {
    height: 100%;
    margin: 0;
    padding: 0;
    border: none;
  }
</style>
<!-- Include sample javascript library functions-->
<script type="text/javascript" src="o3djs/base.js"></script>

<!-- Our javascript code -->
<script type="text/javascript">
o3djs.require('o3djs.util');
o3djs.require('o3djs.rendergraph');
o3djs.require('o3djs.pack');
o3djs.require('o3djs.math');
o3djs.require('o3djs.camera');
o3djs.require('o3djs.effect');
o3djs.require('o3djs.loader');

// Events
// init() once the page has finished loading.
// unload() when the page is unloaded.
window.onload = init;
window.onunload = unload;

// global variables
var g_o3d;
var g_client;
var g_viewInfo;
var g_o3dElement;
var g_pack;
var g_root;
var g_math;
var g_timeMult = 1;
var g_finished = false;  // for selenium testing
var g_currentTimeParam;
var g_clock = 0;
var g_shaderSelection = 0;
var g_rotateOn = true;
var g_o3dWidth;  // width of our client area
var g_o3dHeight;  // height of our client area
var g_shaders = [
  {file: 'diffuse',               name: 'Diffuse'},
  {file: 'checker',               name: 'Checker'},
  {file: 'bump',                  name: 'Bump'},
  {file: 'bump',                  name: 'Bump With Texture'},
  {file: 'texture-only',          name: 'Texture Only'},
  {file: 'texture-colormult',     name: 'Texture with Color Multiplier'},
  {file: 'tangent',               name: 'Tangent'},
  {file: 'binormal',              name: 'Binormal'},
  {file: 'normal',                name: 'Normal'},
  {file: 'solid-color',           name: 'Solid Color'},
  {file: 'vertex-color',          name: 'Vertex Color'},
  {file: 'phong-with-colormult',  name: 'Blinn-Phong with Color Multiplier'},
  {file: 'toon',                  name: 'Toon'}];
var g_effects = [];
var g_bumpTextureSampler;
var g_bumpBumpsSampler;
var g_colorRampSampler;

// Our view and projection matrices
// The view matrix transforms objects from world space to view space.
var g_viewMatrix;
// The projection matrix projects objects from view space to the screen.
var g_projMatrix;

/**
 * Returns the path of where the file is located
 * with the trailing slash
 */
function getCurrentPath() {
  var path = window.location.href;
  var index = path.lastIndexOf('/');
  return path.substring(0, index + 1);
}

/**
 * Turn rotation on.
 */
function turnRotateOn() {
  g_rotateOn = true;
}

/**
 * Turn rotation off.
 */
function turnRotateOff() {
  g_rotateOn = false;
}

/**
 * This is the code to animate the rotation.
 * @param {o3d.RenderEvent} render_event The render event.
 */
function onrender(render_event) {
  var elapsedTime = render_event.elapsedTime * g_timeMult;
  var newWidth = g_client.width;
  var newHeight = g_client.height;
  if (newWidth != g_o3dWidth || newHeight != g_o3dHeight) {
    g_o3dWidth = newWidth;
    g_o3dHeight = newHeight;
    setupCamera(g_pack, g_root);
  }

  g_clock += elapsedTime * (g_rotateOn ? 1 : 0);
  g_root.identity();
  g_root.rotateY(g_clock);

  g_currentTimeParam.value = g_clock;
}

/**
 * Sets the camera based on the imported file.
 * @param {!o3d.Pack} pack Pack to create context in.
 * @param {!o3d.Transform} root Root of tree to search for camera info.
 */
function setupCamera(pack, root) {
  // Get a CameraInfo (an object with a view and projection matrix)
  // using our javascript library function
  var cameraInfo = o3djs.camera.getViewAndProjectionFromCameras(root,
                                                                g_o3dWidth,
                                                                g_o3dHeight);

  // Copy the view and projection to the draw context.
  g_viewInfo.drawContext.view = cameraInfo.view;
  g_viewInfo.drawContext.projection = cameraInfo.projection;
}

/**
 * Our callback is called once the scene has been loaded into memory
 * from the web or locally.
 * @param {!o3d.Pack} pack Variable referring to the scene's pack.
 * @param {!o3d.Transform} parent Transform parent.
 * @param {*} exception null if loading succeeded.
 */
function sceneCallback(pack, parent, exception) {
  if (exception) {
    alert('Could not load scene\n' + exception);
    return;
  }
  setupCamera(pack, parent);

  // Start with diffuse as default
  applyShader(pack, 0);

  // Add some vertex colors because the teapot does not have any
  // and yet the vertex color shader requires them.
  var streamBanks = pack.getObjectsByClassName('o3d.StreamBank');
  for (var ss = 0; ss < streamBanks.length; ++ss) {
    var streamBank = streamBanks[ss];
    if (!streamBank.getVertexStream(g_o3d.Stream.COLOR, 0)) {
      var positionField = streamBank.getVertexStream(g_o3d.Stream.POSITION,
                                                     0).field;
      var buffer = positionField.buffer;
      var numElements = buffer.numElements;
      var colorField = buffer.createField('FloatField', 4);

      var colors = [];
      for (var nn = 0; nn < numElements; ++nn) {
        colors.push((nn * 40 / numElements) % 1,
                    (nn * 61 / numElements) % 1,
                    (nn * 83 / numElements) % 1,
                    1);
      }
      colorField.setAt(0, colors);
      streamBank.setVertexStream(g_o3d.Stream.COLOR, 0, colorField, 0);
    }
  }

  // Generate draw elements and setup material draw lists.
  o3djs.pack.preparePack(pack, g_viewInfo);
}

/**
 * Looks up a Param and if it exists sets its value.
 * @param {!o3d.ParamObject} object object to look for param on.
 * @param {string} name name of Param to look up.
 * @param {*} value Value to set param.
 */
function setParam(object, paramName, value) {
  var param = object.getParam(paramName);
  if (param) {
    param.value = value;
  }
}

/**
 * Apply the desired shader to our scene.
 * @param {!o3d.Pack} pack Variable referring to the scene's pack.
 * @param {number} shaderNumber Index into g_effects of which shader to use.
 */
function applyShader(pack, shaderNumber) {
  var materials = pack.getObjectsByClassName('o3d.Material');
  // Make the change to each material. For our teapot, there is only one
  // material.
  for (var m = 0; m < materials.length; m++) {
    var material = materials[m];
    g_effects[shaderNumber].createUniformParameters(material);
    material.effect = g_effects[shaderNumber];

    // Set our shader values
    var colorParamValue = [0.8, 0.8, 0.8, 1];
    var lightPosParamValue = [600, 600, 1000];

    setParam(material, 'lightPos', lightPosParamValue);
    setParam(material, 'lightWorldPos', lightPosParamValue);
    setParam(material, 'cameraEye', [197.58, -63.5702, 0]);
    setParam(material, 'color', colorParamValue);
    setParam(material, 'colorMult', [.75, .75, 75., 1]);
    // only use the texture input addition to bump mapping if on selection 3
    setParam(material, 'useTexture', (g_shaderSelection == 3) ? 1 : 0);
    setParam(material, 'lightIntensity', [0.8, 0.8, 0.8, 1]);
    setParam(material, 'ambientIntensity', [0.2, 0.2, 0.2, 1]);
    setParam(material, 'emissive', [0, 0, 0, 1]);
    setParam(material, 'ambient', [1, 1, 1, 1]);
    setParam(material, 'diffuse', colorParamValue);
    setParam(material, 'specular', [0.5, 0.5, 0.5, 1]);
    setParam(material, 'shininess', 50);
    setParam(material, 'BumpSampler', g_bumpBumpsSampler);
    setParam(material, 'AmbientSampler', g_bumpTextureSampler);
    setParam(material, 'DiffuseSampler', g_bumpTextureSampler);
    setParam(material, 'texSampler0', g_bumpTextureSampler);
    setParam(material, 'colorRamp', g_colorRampSampler);

    var timeParam = material.getParam('inputTime');
    if (timeParam) {
      timeParam.bind(g_currentTimeParam);
    }
  }
}

/**
 * Creates our client area by looking for <div>s with an id that starts with
 * "o3d".
 */
function init() {
  o3djs.util.makeClients(initStep2);
}

/**
 * Initializes O3D and loads the scene into the transform graph.
 */
function initStep2(clientElements) {
  // Initialize global variables and libraries.
  g_o3dElement = clientElements[0];
  g_o3d = g_o3dElement.o3d;
  g_math = o3djs.math;
  g_client = g_o3dElement.client;

  // Get the width and height of our client area. We will need this to create
  // a projection matrix.
  g_o3dWidth  = g_client.width;
  g_o3dHeight = g_client.height;

  // Creates a pack to manage our resources/assets
  g_pack = g_client.createPack();

  // Create the render graph for a view.
  g_viewInfo = o3djs.rendergraph.createBasicView(
      g_pack,
      g_client.root,
      g_client.renderGraphRoot);

  // Creates a transform to put our data on.
  g_root = g_pack.createObject('Transform');

  // Connects our root to the client's root.
  g_root.parent = g_client.root;

  var paramObject = g_pack.createObject('ParamObject');
  g_currentTimeParam = paramObject.createParam('timeParam','ParamFloat');

  // Load effects and fill out options.
  options = ''
  for(var s = 0; s < g_shaders.length; s++) {
    g_effects[s] = g_pack.createObject('Effect');
    var shaderString = 'shaders/' + g_shaders[s].file + '.shader';
    o3djs.effect.loadEffect(g_effects[s], shaderString);
    options += '<option value="' + s + '"' + (s == 0 ? ' selected' : '') +
               '>' + g_shaders[s].name + '</option>';
  }
  document.getElementById('shaderSelect').innerHTML = options;

  var rampWidth = 64;
  var texture = g_pack.createTexture2D(
      rampWidth, 1, g_o3d.Texture.XRGB8, 1, false);
  var pixels = [];
  for (var ii = 0; ii < rampWidth; ++ii) {
    var level = ii > rampWidth * 0.5 ? 1 : 0.3;
    pixels.push(level, level, level);
  }
  texture.set(0, pixels);
  g_colorRampSampler = g_pack.createObject('Sampler');
  g_colorRampSampler.texture = texture;
  g_colorRampSampler.addressModeU = g_o3d.Sampler.CLAMP;

  var loader = o3djs.loader.createLoader(initStep3);
  loader.loadTexture(g_pack, 'assets/normalmap.dds',
                     function(texture, exception) {
                       if (exception) {
                         alert(exception);
                       } else {
                         g_bumpBumpsSampler = g_pack.createObject('Sampler');
                         g_bumpBumpsSampler.texture = texture;
                         g_bumpBumpsSampler.mipFilter = g_o3d.Sampler.LINEAR;
                       }
                     });
  loader.loadTexture(g_pack, 'assets/rock_texture.jpg',
                     function(texture, exception) {
                       if (exception) {
                         alert(exception);
                       } else {
                         g_bumpTextureSampler = g_pack.createObject('Sampler');
                         g_bumpTextureSampler.texture = texture;
                         g_bumpTextureSampler.mipFilter = g_o3d.Sampler.LINEAR;
                       }
                     });
  var scenePath = getCurrentPath() + 'assets/teapot.o3dtgz';
  loader.loadScene(g_client, g_pack, g_root, scenePath, sceneCallback);
  loader.finish();
}

function initStep3() {
  o3djs.event.addEventListener(g_o3dElement, 'mousedown', turnRotateOff);
  o3djs.event.addEventListener(g_o3dElement, 'mouseup', turnRotateOn);

  g_rotateOn = true;

  // Tell our example to rotate.
  g_client.setRenderCallback(onrender);

  g_finished = true;  // for selenium testing.
}

/**
 * Swaps which shader we are using and applies it.
 */
function changeShader() {
  var shaderNumber = document.getElementById("shaderSelect").value;
  g_shaderSelection = parseFloat(shaderNumber);
  applyShader(g_pack, g_shaderSelection);
}

/**
 * Removes any callbacks so they don't get called after the page has unloaded.
 */
function unload() {
  if (g_client) {
    g_client.cleanup();
  }
}

</script>
</head>
<body>
<h1>Shader Test</h1>
This example is useful for testing a shader or checking a scene. Clicking on the scene will temporarily stop rotation.
<br/>
<!-- Start of O3D plugin -->
<div id="o3d" style="width: 100%; height: 80%;"></div>
<!-- End of O3D plugin -->
<p>
<select id='shaderSelect' name='shaderSelect' onChange='changeShader()'>
</select>
</body>
</html>