File: minimal_sycl.cpp

package info (click to toggle)
embree 4.4.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 99,492 kB
  • sloc: cpp: 224,036; xml: 40,944; ansic: 2,731; python: 812; sh: 639; makefile: 228; csh: 42
file content (341 lines) | stat: -rw-r--r-- 10,365 bytes parent folder | download
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
// Copyright 2009-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0

/*
 * To use the Embree DPC++ API you have to include sycl.hpp before the
 * embree API headers.
 */
#include <sycl/sycl.hpp>
#include <embree4/rtcore.h>

#include <cstdio>
#include <limits>

#include "../common/sycl/util.h"

/*
 * A minimal tutorial. 
 *
 * It demonstrates how to intersect a ray with a single triangle. It is
 * meant to get you started as quickly as possible, and does not output
 * an image. 
 */

/* 
 * This is only required to make the tutorial compile even when
 * a custom namespace is set.
 */
#if defined(RTC_NAMESPACE_USE)
RTC_NAMESPACE_USE
#endif

const sycl::specialization_id<RTCFeatureFlags> feature_mask;
const RTCFeatureFlags required_features = RTC_FEATURE_FLAG_TRIANGLE;

struct Result {
  unsigned geomID;
  unsigned primID; 
  float tfar;
};

/*
 * This function allocated USM memory that is writeable by the device.
 */

template<typename T>
T* alignedSYCLMallocDeviceReadWrite(const sycl::queue& queue, size_t count, size_t align)
{
  if (count == 0)
    return nullptr;

  assert((align & (align - 1)) == 0);
  T *ptr = (T*)sycl::aligned_alloc(align, count * sizeof(T), queue, sycl::usm::alloc::shared);
  if (count != 0 && ptr == nullptr)
    throw std::bad_alloc();

  return ptr;
}

/*
 * This function allocated USM memory that is only readable by the
 * device. Using this mode many small allocations are possible by the
 * application.
 */

template<typename T>
T* alignedSYCLMallocDeviceReadOnly(const sycl::queue& queue, size_t count, size_t align)
{
  if (count == 0)
    return nullptr;

  assert((align & (align - 1)) == 0);
  T *ptr = (T*)sycl::aligned_alloc_shared(align, count * sizeof(T), queue, sycl::ext::oneapi::property::usm::device_read_only());
  if (count != 0 && ptr == nullptr)
    throw std::bad_alloc();

  return ptr;
}

void alignedSYCLFree(const sycl::queue& queue, void* ptr)
{
  if (ptr) sycl::free(ptr, queue);
}

/*
 * We will register this error handler with the device in initializeDevice(),
 * so that we are automatically informed on errors.
 * This is extremely helpful for finding bugs in your code, prevents you
 * from having to add explicit error checking to each Embree API call.
 */
void errorFunction(void* userPtr, enum RTCError error, const char* str)
{
  printf("error %s: %s\n", rtcGetErrorString(error), str);
}

/*
 * Embree has a notion of devices, which are entities that can run 
 * raytracing kernels.
 * We initialize our device here, and then register the error handler so that 
 * we don't miss any errors.
 *
 * rtcNewDevice() takes a configuration string as an argument. See the API docs
 * for more information.
 *
 * Note that RTCDevice is reference-counted.
 */
RTCDevice initializeDevice(sycl::context& sycl_context, sycl::device& sycl_device)
{
  RTCDevice device = rtcNewSYCLDevice(sycl_context, "");
  rtcSetDeviceSYCLDevice(device,sycl_device);

  if (!device) {
    printf("error %s: cannot create device. (reason: %s)\n", rtcGetErrorString(rtcGetDeviceError(NULL)), rtcGetDeviceLastErrorMessage(NULL));
    exit(1);
  }

  rtcSetDeviceErrorFunction(device, errorFunction, NULL);
  return device;
}

/*
 * Create a scene, which is a collection of geometry objects. Scenes are 
 * what the intersect / occluded functions work on. You can think of a 
 * scene as an acceleration structure, e.g. a bounding-volume hierarchy.
 *
 * Scenes, like devices, are reference-counted.
 */
RTCScene initializeScene(RTCDevice device, const sycl::queue& queue)
{
  RTCScene scene = rtcNewScene(device);

  /* 
   * Create a triangle mesh geometry, and initialize a single triangle.
   * You can look up geometry types in the API documentation to
   * find out which type expects which buffers.
   *
   * We create buffers directly on the device, but you can also use
   * shared buffers. For shared buffers, special care must be taken
   * to ensure proper alignment and padding. This is described in
   * more detail in the API documentation.
   */
  RTCGeometry geom = rtcNewGeometry(device, RTC_GEOMETRY_TYPE_TRIANGLE);
  
  float* vertices = alignedSYCLMallocDeviceReadOnly<float>(queue, 3 * 3, 16);

  rtcSetSharedGeometryBuffer(geom,
                             RTC_BUFFER_TYPE_VERTEX,
                             0,
                             RTC_FORMAT_FLOAT3,
                             vertices,
                             0,
                             3*sizeof(float),
                             3);

  unsigned* indices = alignedSYCLMallocDeviceReadOnly<unsigned>(queue, 3, 16);
  
  rtcSetSharedGeometryBuffer(geom,
                             RTC_BUFFER_TYPE_INDEX,
                             0,
                             RTC_FORMAT_UINT3,
                             indices,
                             0,
                             3*sizeof(unsigned),
                             1);

  if (vertices && indices)
  {
    vertices[0] = 0.f; vertices[1] = 0.f; vertices[2] = 0.f;
    vertices[3] = 1.f; vertices[4] = 0.f; vertices[5] = 0.f;
    vertices[6] = 0.f; vertices[7] = 1.f; vertices[8] = 0.f;

    indices[0] = 0; indices[1] = 1; indices[2] = 2;
  }

  /*
   * You must commit geometry objects when you are done setting them up,
   * or you will not get any intersections.
   */
  rtcCommitGeometry(geom);

  /*
   * In rtcAttachGeometry(...), the scene takes ownership of the geom
   * by increasing its reference count. This means that we don't have
   * to hold on to the geom handle, and may release it. The geom object
   * will be released automatically when the scene is destroyed.
   *
   * rtcAttachGeometry() returns a geometry ID. We could use this to
   * identify intersected objects later on.
   */
  rtcAttachGeometry(scene, geom);
  rtcReleaseGeometry(geom);

  /*
   * Like geometry objects, scenes must be committed. This lets
   * Embree know that it may start building an acceleration structure.
   */
  rtcCommitScene(scene);

  return scene;
}

/*
 * Cast a single ray with origin (ox, oy, oz) and direction
 * (dx, dy, dz).
 */

void castRay(sycl::queue& queue, const RTCTraversable traversable,
             float ox, float oy, float oz,
             float dx, float dy, float dz, Result* result)
{
  queue.submit([=](sycl::handler& cgh)
  {
    cgh.set_specialization_constant<feature_mask>(required_features);

    cgh.parallel_for(sycl::range<1>(1),[=](sycl::item<1> item, sycl::kernel_handler kh)
    {
      /*
       * The intersect arguments can be used to pass a feature mask,
       * which improves performance and JIT compile times on the GPU
       */
      RTCIntersectArguments args;
      rtcInitIntersectArguments(&args);

      const RTCFeatureFlags features = kh.get_specialization_constant<feature_mask>();
      args.feature_mask = features;

      /*
       * The ray hit structure holds both the ray and the hit.
       * The user must initialize it properly -- see API documentation
       * for rtcIntersect1() for details.
       */
      struct RTCRayHit rayhit;
      rayhit.ray.org_x = ox;
      rayhit.ray.org_y = oy;
      rayhit.ray.org_z = oz;
      rayhit.ray.dir_x = dx;
      rayhit.ray.dir_y = dy;
      rayhit.ray.dir_z = dz;
      rayhit.ray.tnear = 0;
      rayhit.ray.tfar = std::numeric_limits<float>::infinity();
      rayhit.ray.mask = -1;
      rayhit.ray.flags = 0;
      rayhit.hit.geomID = RTC_INVALID_GEOMETRY_ID;
      rayhit.hit.instID[0] = RTC_INVALID_GEOMETRY_ID;

      /*
       * There are multiple variants of rtcIntersect. This one
       * intersects a single ray with the scene.
       */
      rtcTraversableIntersect1(traversable, &rayhit, &args);

      /*
       * write hit result to output buffer
       */
      result->geomID = rayhit.hit.geomID;
      result->primID = rayhit.hit.primID;
      result->tfar = rayhit.ray.tfar;
    });
  });
  queue.wait_and_throw();

  printf("%f, %f, %f: ", ox, oy, oz);
  if (result->geomID != RTC_INVALID_GEOMETRY_ID)
  {
    /* Note how geomID and primID identify the geometry we just hit.
     * We could use them here to interpolate geometry information,
     * compute shading, etc.
     * Since there is only a single triangle in this scene, we will
     * get geomID=0 / primID=0 for all hits.
     * There is also instID, used for instancing. See
     * the instancing tutorials for more information */
    printf("Found intersection on geometry %d, primitive %d at tfar=%f\n", 
           result->geomID,
           result->primID,
           result->tfar);
  }
  else
    printf("Did not find any intersection.\n");
}

/*
 * Enable persistent JIT compilation caching. These environment
 * variables must be set before the SYCL device creation.
 */

void enablePersistentJITCache()
{
#if defined(_WIN32)
  _putenv_s("SYCL_CACHE_PERSISTENT","1");
  _putenv_s("SYCL_CACHE_DIR","cache");
#else
  setenv("SYCL_CACHE_PERSISTENT","1",1);
  setenv("SYCL_CACHE_DIR","cache",1);
#endif
}

/* -------------------------------------------------------------------------- */

int main()
{
  try {
  enablePersistentJITCache();

  /* This will select the first GPU supported by Embree */
  sycl::device sycl_device;
  try {
    sycl_device = sycl::device(rtcSYCLDeviceSelector);
  } catch(std::exception& e) {
    std::cerr << "Caught exception creating sycl::device: " << e.what() << std::endl;
    embree::printAllSYCLDevices();
    return 1;
  }

  sycl::queue sycl_queue(sycl_device);
  sycl::context sycl_context(sycl_device);

  RTCDevice device = initializeDevice(sycl_context,sycl_device);
  RTCScene scene = initializeScene(device, sycl_queue);
  RTCTraversable traversable = rtcGetSceneTraversable(scene);

  Result* result = alignedSYCLMallocDeviceReadWrite<Result>(sycl_queue, 1, 16);
  result->geomID = RTC_INVALID_GEOMETRY_ID;

  /* This will hit the triangle at t=1. */
  castRay(sycl_queue, traversable, 0.33f, 0.33f, -1, 0, 0, 1, result);

  /* This will not hit anything. */
  castRay(sycl_queue, traversable, 1.00f, 1.00f, -1, 0, 0, 1, result);

  alignedSYCLFree(sycl_queue, result);

  /* Though not strictly necessary in this example, you should
   * always make sure to release resources allocated through Embree. */
  rtcReleaseScene(scene);
  rtcReleaseDevice(device);

  } catch(std::exception& e) {
    std::cerr << "Caught exception " << e.what() << std::endl;
    return 1;
  }
  return 0;
}